<commit_before>//= require <src/header.js>

CD3.Slider = Class.create({
	initialize: function(container, options){
		var options = Object.extend({
			prev: 			null,
			next:			null,
			scrollBy:		0,
			scrollType:		'horizontal',
			event:			'click',
			beforeSlide:	false,
			afterSlide:		false,
			effectDuration: 0.8
		}, options || {});

		this.container	= $(container);
		this.scroll		= options.scrollType == 'vertical' ? ['top', 'offsetHeight', 'y'] : ['left', 'offsetWidth', 'x'];
		this.prev		= $(options.prev).observe(options.event, this.slide.bind(this, options.scrollBy));
		this.next		= $(options.next).observe(options.event, this.slide.bind(this, -options.scrollBy));
		this.sliding	= false;

		this.effectOptions = {
			duration: options.effectDuration || 0.8 ,
			queue: {scope: 'cd3:slider', limit:1},
			afterFinish: this.afterSlide.bind(this, options.afterSlide)
		};

		if (options.beforeSlide){
			this.effectOptions = options.beforeSlide.bind(this);
		}

		var pos = parseInt(this.container.style[this.scroll[0]]) || 0;
		console.log(this);
		this.setVisibility('prev', pos != 0);
		this.setVisibility('next', this.container[this.scroll[1]] - (options.scrollBy - pos) >= 1);
	},
	setVisibility: function(button, visible){
		this[button].style.visibility = visible ? 'visible' : 'hidden';
	},
	slide: function(moveBy){
		if (this.sliding) return;

		var property	= parseInt(this.container.style[this.scroll[0]]) || 0,	// top or left
			offset		= this.container[this.scroll[1]]; // offsetHeight or offsetWidth

//		if ((moveBy > 0 && (property > -1 || property != 0)) || (moveBy < 0 && offset + moveBy + property < 0))
		if ((moveBy > 0 && property > 0) || (moveBy < 0 && property + offset + moveBy < 0)) return;

		this.setVisibility('prev', property + moveBy < 0);
		this.setVisibility('next', offset + property + moveBy * 2 > 1);
		this.sliding = true;

		moveBy = moveBy < 0 ? Math.max(moveBy, - (offset + property + moveBy)) : Math.min(moveBy, -property);

		var options = this.effectOptions;
		options[this.scroll[2]] = moveBy; // x or y
		console.log(options);
		new Effect.Move(this.container, options);
	},
	afterSlide: function(callback){
		this.sliding = false;
		if (callback) callback.call(this);
	}
});
<commit_msg>removed some forgotten console.log calls<commit_after>//= require <src/header.js>

CD3.Slider = Class.create({
	initialize: function(container, options){
		var options = Object.extend({
			prev: 			null,
			next:			null,
			scrollBy:		0,
			scrollType:		'horizontal',
			event:			'click',
			beforeSlide:	false,
			afterSlide:		false,
			effectDuration: 0.8
		}, options || {});

		this.container	= $(container);
		this.scroll		= options.scrollType == 'vertical' ? ['top', 'offsetHeight', 'y'] : ['left', 'offsetWidth', 'x'];
		this.prev		= $(options.prev).observe(options.event, this.slide.bind(this, options.scrollBy));
		this.next		= $(options.next).observe(options.event, this.slide.bind(this, -options.scrollBy));
		this.sliding	= false;

		this.effectOptions = {
			duration:		options.effectDuration || 0.8 ,
			queue:			{scope: 'cd3:slider', limit:1},
			afterFinish:	this.afterSlide.bind(this, options.afterSlide)
		};

		if (options.beforeSlide){
			this.effectOptions = options.beforeSlide.bind(this);
		}

		var pos = parseInt(this.container.style[this.scroll[0]]) || 0;

		this.setVisibility('prev', pos != 0);
		this.setVisibility('next', this.container[this.scroll[1]] - (options.scrollBy - pos) >= 1);
	},
	setVisibility: function(button, visible){
		this[button].style.visibility = visible ? 'visible' : 'hidden';
	},
	slide: function(moveBy){
		if (this.sliding) return;

		var property	= parseInt(this.container.style[this.scroll[0]]) || 0,	// top or left
			offset		= this.container[this.scroll[1]]; // offsetHeight or offsetWidth

		if ((moveBy > 0 && property > 0) || (moveBy < 0 && property + offset + moveBy < 0)) return;

		this.setVisibility('prev', property + moveBy < 0);
		this.setVisibility('next', offset + property + moveBy * 2 > 1);
		this.sliding = true;

		moveBy = moveBy < 0 ? Math.max(moveBy, - (offset + property + moveBy)) : Math.min(moveBy, -property);

		var options = this.effectOptions;
		options[this.scroll[2]] = moveBy; // x or y

		new Effect.Move(this.container, options);
	},
	afterSlide: function(callback){
		this.sliding = false;
		if (callback) callback.call(this);
	}
});
<|endoftext|>


<commit_before>define(['jquery', 'modules/masonit', 'lib/jquery.cookie'], function ($, masonry) {
    var menus = {
        "Tegninger": [
            "Kull",
            "Pastellkritt",
            "Blyant",
            "Tusj",
            "Akryl",
            "Akvarell"
        ],
        "Landskap": [
            "Landskap",
            "Stilleben"
        ],
        "Portretter": [
            "Portrett",
            "Akt"
        ]
    };

    var setActive = function (getClass) {
        var $getClass = $("." + getClass);

        $(".active").removeClass("active");
        $getClass.addClass("active");
        $(".item, .item2").hide();
        $getClass.show();
        if (getClass == "all") {
            $(".item, .item2").show();
        }
        masonry.turnUp();
        generateSubmenu(getClass);
    };

    var generateSubmenu = function(getClass) {

        var items = [];
        $.each(menus, function(key, val) {
            if (getClass.split("-")[1] === key) {
                $.each(val, function(k, v) {
                    items.push("
" + v + "
");
                });
            } else {
                $.each(val, function(k, v) {
                    if (getClass.split("-")[1] === v) {
                        $("." + key).addClass("active");

                        $.each(val, function (kt, va) {
                            if (va === v) {
                                items.push("
" + va + "
");
                            } else {
                                items.push("
" + va + "
");
                            }

                        });
                    }
                });
            }
        });
        $(".submenus").html(items);
    };

    var setActiveAndCookie = function(that) {
        var getClass = $(that).attr("class").replace("button-flat-empty", "").replace(" ", "");
        setActive(getClass);
        $.cookie("category", getClass);
    };

    var setActiveOnLoad = function() {
        if (($.cookie("category") !== null) && $.cookie("category") !== "null") {
            setActive($.cookie("category"));
        } else {
            setActive("all");
        }
    };

    return {
        generateSubmenu: generateSubmenu,
        setActive: setActive,
        setActiveAndCookie: setActiveAndCookie,
        setActiveOnLoad: setActiveOnLoad
    };
});<commit_msg>Uppercase error<commit_after>define(['jquery', 'modules/masonit', 'lib/jquery.cookie'], function ($, masonry) {
    var menus = {
        "Tegninger": [
            "Kull",
            "Pastellkritt",
            "Blyant",
            "Tusj",
            "Akryl",
            "Akvarell"
        ],
        "Landskap": [
            "Landskap",
            "Stilleben"
        ],
        "Portretter": [
            "Portrett",
            "Akt"
        ]
    };

    //Little off...
    var setActive = function (getClass) {
        var $getClass = $("." + getClass);

        $(".active").removeClass("active");
        $getClass.addClass("active");
        $(".item, .item2").hide();
        $getClass.show();
        if (getClass == "all") {
            $(".item, .item2").show();
        }
        masonry.turnUp();
        generateSubmenu(getClass);
    };

    var generateSubmenu = function (getClass) {

        var items = [];
        $.each(menus, function (key, val) {
            if (getClass.split("-")[1] === key) {
                $.each(val, function (k, v) {
                    items.push("
" + v + "
");
                });
            } else {
                $.each(val, function (k, v) {
                    if (getClass.split("-")[1] === v) {
                        $("." + key).addClass("active");

                        $.each(val, function (kt, va) {
                            if (va === v) {
                                items.push("
" + va + "
");
                            } else {
                                items.push("
" + va + "
");
                            }

                        });
                    }
                });
            }
        });
        $(".submenus").html(items);
    };

    var setActiveAndCookie = function (that) {
        var getClass = $(that).attr("class").replace("button-flat-empty", "").replace(" ", "");
        setActive(getClass);
        $.cookie("category", getClass);
    };

    var setActiveOnLoad = function () {
        if (($.cookie("category") !== null) && $.cookie("category") !== "null") {
            setActive($.cookie("category"));
        } else {
            setActive("all");
        }
    };

    return {
        generateSubmenu: generateSubmenu,
        setActive: setActive,
        setActiveAndCookie: setActiveAndCookie,
        setActiveOnLoad: setActiveOnLoad
    };
});<|endoftext|>


<commit_before>const fs = require('fs');
const less = require('less');
const SVGO = require('svgo');
const rollup = require('rollup');
const postcss = require('postcss');
const uglify = require('uglify-js');
const {promisify} = require('util');
const CleanCSS = require('clean-css');
const html = require('rollup-plugin-html');
const buble = require('@rollup/plugin-buble');
const replace = require('@rollup/plugin-replace');
const alias = require('@rollup/plugin-alias');
const {basename, dirname, resolve} = require('path');
const {version} = require('../package.json');
const banner = `/*! UIkit ${version} | https://www.getuikit.com | (c) 2014 - ${new Date().getFullYear()} YOOtheme | MIT License */\n`;

exports.banner = banner;
exports.validClassName = /[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/;

exports.glob = promisify(require('glob'));

const readFile = promisify(fs.readFile);
exports.read = async function (file, cb) {

    const data = await readFile(file, 'utf8');
    cb && cb(data);
    return data;

};

const writeFile = promisify(fs.writeFile);
exports.write = async function (dest, data) {

    const err = await writeFile(dest, data);

    if (err) {
        console.log(err);
        throw err;
    }

    exports.logFile(dest);

    return dest;

};

exports.logFile = async function (file) {
    const data = await exports.read(file);
    console.log(`${cyan(file)} ${getSize(data)}`);
};

exports.minify = async function (file) {

    const {styles} = await new CleanCSS({
        advanced: false,
        keepSpecialComments: 0,
        rebase: false,
        returnPromise: true
    }).minify([file]);

    await exports.write(`${resolve(dirname(file), basename(file, '.css'))}.min.css`, styles);

    return styles;

};

exports.renderLess = async function (data, options) {
    return postcss()
        .use(postcss.plugin('calc', () =>
            css => {
                css.walk(node => {
                    const {type} = node;

                    if (type === 'decl') {
                        node.value = postcss.list.space(node.value).map(value =>
                            value.startsWith('calc(')
                                ? value.replace(/(.)calc/g, '$1')
                                : value
                        ).join(' ');
                    }
                });
            }
        ))
        .process((await less.render(data, options)).css)
        .css;
};

exports.compile = async function (file, dest, {external, globals, name, aliases, replaces, minify = true}) {

    name = (name || '').replace(/[^\w]/g, '_');

    const bundle = await rollup.rollup({
        external,
        input: resolve(file),
        plugins: [
            replace(Object.assign({
                VERSION: `'${version}'`
            }, replaces)),
            alias({
                entries: Object.assign({
                    'uikit-util': './src/js/util/index.js'
                }, aliases)
            }),
            html({
                include: '**/*.svg',
                htmlMinifierOptions: {
                    collapseWhitespace: true
                }
            }),
            buble({namedFunctionExpressions: false})
        ]
    });

    let {output: [{code, map}]} = await bundle.generate({
        globals,
        format: 'umd',
        banner: exports.banner,
        amd: {id: `UIkit${name}`.toLowerCase()},
        name: `UIkit${exports.ucfirst(name)}`,
        sourcemap: !minify ? 'inline' : false
    });

    code = code.replace(/(>)\\n\s+|\\n\s+(<)/g, '$1 $2');

    return Promise.all([
        exports.write(`${dest}.js`, code + (!minify ? '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + Buffer.from(map.toString()).toString('base64') : '')),
        minify ? exports.write(`${dest}.min.js`, uglify.minify(code, {output: {preamble: exports.banner}}).code) : null
    ])[0];

};

exports.icons = async function (src) {

    const svgo = new SVGO({

        plugins: [
            {removeViewBox: false},
            {
                cleanupNumericValues: {
                    floatPrecision: 3
                }
            },
            {convertPathData: false},
            {convertShapeToPath: false},
            {mergePaths: false},
            {removeDimensions: false},
            {removeStyleElement: false},
            {removeScriptElement: false},
            {removeUnknownsAndDefaults: false},
            {removeUselessStrokeAndFill: false}
        ]

    });
    const files = await exports.glob(src, {nosort: true});
    const icons = await Promise.all(files.map(async file => {
        const data = await exports.read(file);
        const {data: svg} = await svgo.optimize(data);
        return svg;
    }));

    return JSON.stringify(files.reduce((result, file, i) => {
        result[basename(file, '.svg')] = icons[i];
        return result;
    }, {}), null, '    ');

};

exports.ucfirst = function (str) {
    return str.length ? str.charAt(0).toUpperCase() + str.slice(1) : '';
};

function cyan(str) {
    return `\x1b[1m\x1b[36m${str}\x1b[39m\x1b[22m`;
}

function getSize(data) {
    return `${(data.length / 1024).toFixed(2)}kb`;
}
<commit_msg>chore: update @rollup/plugin-replace default option<commit_after>const fs = require('fs');
const less = require('less');
const SVGO = require('svgo');
const rollup = require('rollup');
const postcss = require('postcss');
const uglify = require('uglify-js');
const {promisify} = require('util');
const CleanCSS = require('clean-css');
const html = require('rollup-plugin-html');
const buble = require('@rollup/plugin-buble');
const replace = require('@rollup/plugin-replace');
const alias = require('@rollup/plugin-alias');
const {basename, dirname, resolve} = require('path');
const {version} = require('../package.json');
const banner = `/*! UIkit ${version} | https://www.getuikit.com | (c) 2014 - ${new Date().getFullYear()} YOOtheme | MIT License */\n`;

exports.banner = banner;
exports.validClassName = /[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/;

exports.glob = promisify(require('glob'));

const readFile = promisify(fs.readFile);
exports.read = async function (file, cb) {

    const data = await readFile(file, 'utf8');
    cb && cb(data);
    return data;

};

const writeFile = promisify(fs.writeFile);
exports.write = async function (dest, data) {

    const err = await writeFile(dest, data);

    if (err) {
        console.log(err);
        throw err;
    }

    exports.logFile(dest);

    return dest;

};

exports.logFile = async function (file) {
    const data = await exports.read(file);
    console.log(`${cyan(file)} ${getSize(data)}`);
};

exports.minify = async function (file) {

    const {styles} = await new CleanCSS({
        advanced: false,
        keepSpecialComments: 0,
        rebase: false,
        returnPromise: true
    }).minify([file]);

    await exports.write(`${resolve(dirname(file), basename(file, '.css'))}.min.css`, styles);

    return styles;

};

exports.renderLess = async function (data, options) {
    return postcss()
        .use(postcss.plugin('calc', () =>
            css => {
                css.walk(node => {
                    const {type} = node;

                    if (type === 'decl') {
                        node.value = postcss.list.space(node.value).map(value =>
                            value.startsWith('calc(')
                                ? value.replace(/(.)calc/g, '$1')
                                : value
                        ).join(' ');
                    }
                });
            }
        ))
        .process((await less.render(data, options)).css)
        .css;
};

exports.compile = async function (file, dest, {external, globals, name, aliases, replaces, minify = true}) {

    name = (name || '').replace(/[^\w]/g, '_');

    const bundle = await rollup.rollup({
        external,
        input: resolve(file),
        plugins: [
            replace({
                preventAssignment: true,
                values: Object.assign({
                    VERSION: `'${version}'`
                }, replaces)}
            ),
            alias({
                entries: Object.assign({
                    'uikit-util': './src/js/util/index.js'
                }, aliases)
            }),
            html({
                include: '**/*.svg',
                htmlMinifierOptions: {
                    collapseWhitespace: true
                }
            }),
            buble({namedFunctionExpressions: false})
        ]
    });

    let {output: [{code, map}]} = await bundle.generate({
        globals,
        format: 'umd',
        banner: exports.banner,
        amd: {id: `UIkit${name}`.toLowerCase()},
        name: `UIkit${exports.ucfirst(name)}`,
        sourcemap: !minify ? 'inline' : false
    });

    code = code.replace(/(>)\\n\s+|\\n\s+(<)/g, '$1 $2');

    return Promise.all([
        exports.write(`${dest}.js`, code + (!minify ? '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + Buffer.from(map.toString()).toString('base64') : '')),
        minify ? exports.write(`${dest}.min.js`, uglify.minify(code, {output: {preamble: exports.banner}}).code) : null
    ])[0];

};

exports.icons = async function (src) {

    const svgo = new SVGO({

        plugins: [
            {removeViewBox: false},
            {
                cleanupNumericValues: {
                    floatPrecision: 3
                }
            },
            {convertPathData: false},
            {convertShapeToPath: false},
            {mergePaths: false},
            {removeDimensions: false},
            {removeStyleElement: false},
            {removeScriptElement: false},
            {removeUnknownsAndDefaults: false},
            {removeUselessStrokeAndFill: false}
        ]

    });
    const files = await exports.glob(src, {nosort: true});
    const icons = await Promise.all(files.map(async file => {
        const data = await exports.read(file);
        const {data: svg} = await svgo.optimize(data);
        return svg;
    }));

    return JSON.stringify(files.reduce((result, file, i) => {
        result[basename(file, '.svg')] = icons[i];
        return result;
    }, {}), null, '    ');

};

exports.ucfirst = function (str) {
    return str.length ? str.charAt(0).toUpperCase() + str.slice(1) : '';
};

function cyan(str) {
    return `\x1b[1m\x1b[36m${str}\x1b[39m\x1b[22m`;
}

function getSize(data) {
    return `${(data.length / 1024).toFixed(2)}kb`;
}
<|endoftext|>


<commit_before>(function(window) {
  var Recorder;

  var RECORDED_AUDIO_TYPE = "audio/wav";

  Recorder = {
    recorder: null,
    recorderOriginalWidth: 0,
    recorderOriginalHeight: 0,
    uploadFormId: null,
    uploadFieldName: null,
    isReady: false,

    connect: function(name, attempts) {
      if(navigator.appName.indexOf("Microsoft") != -1) {
        Recorder.recorder = window[name];
      } else {
        Recorder.recorder = document[name];
      }

      if(attempts >= 40) {
        return;
      }

      // flash app needs time to load and initialize
      if(Recorder.recorder && Recorder.recorder.init) {
        Recorder.recorderOriginalWidth = Recorder.recorder.width;
        Recorder.recorderOriginalHeight = Recorder.recorder.height;
        if(Recorder.uploadFormId && $) {
          var frm = $(Recorder.uploadFormId);
          Recorder.recorder.init(frm.attr('action').toString(), Recorder.uploadFieldName, frm.serializeArray());
        }
        return;
      }

      setTimeout(function() {Recorder.connect(name, attempts+1);}, 100);
    },

    playBack: function(name) {
      // TODO: Rename to `playback`
      Recorder.recorder.playBack(name);
    },

    pausePlayBack: function(name) {
      // TODO: Rename to `pausePlayback`
      Recorder.recorder.pausePlayBack(name);
    },

    playBackFrom: function(name, time) {
      // TODO: Rename to `playbackFrom`
      Recorder.recorder.playBackFrom(name, time);
    },

    record: function(name, filename) {
      Recorder.recorder.record(name, filename);
    },

    stopRecording: function() {
      Recorder.recorder.stopRecording();
    },

    stopPlayBack: function() {
      // TODO: Rename to `stopPlayback`
      Recorder.recorder.stopPlayBack();
    },

    observeLevel: function() {
      Recorder.recorder.observeLevel();
    },

    stopObservingLevel: function() {
      Recorder.recorder.stopObservingLevel();
    },

    observeSamples: function() {
      Recorder.recorder.observeSamples();
    },

    stopObservingSamples: function() {
      Recorder.recorder.stopObservingSamples();
    },

    resize: function(width, height) {
      Recorder.recorder.width = width + "px";
      Recorder.recorder.height = height + "px";
    },

    defaultSize: function() {
      Recorder.resize(Recorder.recorderOriginalWidth, Recorder.recorderOriginalHeight);
    },

    show: function() {
      Recorder.recorder.show();
    },

    hide: function() {
      Recorder.recorder.hide();
    },

    duration: function(name) {
      // TODO: rename to `getDuration`
      return Recorder.recorder.duration(name || Recorder.uploadFieldName);
    },

    getBase64: function(name) {
      var data = Recorder.recorder.getBase64(name);
      return 'data:' + RECORDED_AUDIO_TYPE + ';base64,' + data;
    },

    getBlob: function(name) {
      var base64Data = Recorder.getBase64(name).split(',')[1];
      return base64toBlob(base64Data, RECORDED_AUDIO_TYPE);
    },

    getCurrentTime: function(name) {
    	return Recorder.recorder.getCurrentTime(name);
    },

    isMicrophoneAccessible: function() {
      return Recorder.recorder.isMicrophoneAccessible();
    },

    updateForm: function() {
      var frm = $(Recorder.uploadFormId);
      Recorder.recorder.update(frm.serializeArray());
    },

    showPermissionWindow: function(options) {
      Recorder.resize(240, 160);
      // need to wait until app is resized before displaying permissions screen
      var permissionCommand = function() {
        // if (options && options.permanent) {
        //   Recorder.recorder.permitPermanently();
        // } else {
          Recorder.recorder.permit();
        // }
      };
      setTimeout(permissionCommand, 1);
    },

    configure: function(rate, gain, silenceLevel, silenceTimeout) {
      rate = parseInt(rate || 22);
      gain = parseInt(gain || 100);
      silenceLevel = parseInt(silenceLevel || 0);
      silenceTimeout = parseInt(silenceTimeout || 4000);
      switch(rate) {
      case 44:
      case 22:
      case 11:
      case 8:
      case 5:
        break;
      default:
        throw("invalid rate " + rate);
      }

      if(gain < 0 || gain > 100) {
        throw("invalid gain " + gain);
      }

      if(silenceLevel < 0 || silenceLevel > 100) {
        throw("invalid silenceLevel " + silenceLevel);
      }

      if(silenceTimeout < -1) {
        throw("invalid silenceTimeout " + silenceTimeout);
      }

      Recorder.recorder.configure(rate, gain, silenceLevel, silenceTimeout);
    },

    setUseEchoSuppression: function(val) {
      if(typeof(val) != 'boolean') {
        throw("invalid value for setting echo suppression, val: " + val);
      }

      Recorder.recorder.setUseEchoSuppression(val);
    },

    setLoopBack: function(val) {
      if(typeof(val) != 'boolean') {
        throw("invalid value for setting loop back, val: " + val);
      }

      Recorder.recorder.setLoopBack(val);
    }
  };

  function base64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      var slice = byteCharacters.slice(offset, offset + sliceSize);

      var byteNumbers = new Array(slice.length);
      for (var i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      var byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, {type: contentType});
  }

  window.FWRecorder = Recorder;

})(this);<commit_msg>flash wav recorder update<commit_after>(function(window) {
  var Recorder;

  var RECORDED_AUDIO_TYPE = "audio/wav";

  Recorder = {
    recorder: null,
    recorderOriginalWidth: 0,
    recorderOriginalHeight: 0,
    uploadFormId: null,
    uploadFieldName: null,
    isReady: false,

    connect: function(name, attempts) {
      if(navigator.appName.indexOf("Microsoft") != -1) {
        Recorder.recorder = window[name];
      } else {
        Recorder.recorder = document[name];
      }

      if(attempts >= 40) {
        return;
      }

      // flash app needs time to load and initialize
      if(Recorder.recorder && Recorder.recorder.init) {
        Recorder.recorderOriginalWidth = Recorder.recorder.width;
        Recorder.recorderOriginalHeight = Recorder.recorder.height;
        if(Recorder.uploadFormId && $) {
          var frm = $(Recorder.uploadFormId);
          Recorder.recorder.init(frm.attr('action').toString(), Recorder.uploadFieldName, frm.serializeArray());
        }
        return;
      }

      setTimeout(function() {Recorder.connect(name, attempts+1);}, 100);
    },

    playBack: function(name) {
      // TODO: Rename to `playback`
      Recorder.recorder.playBack(name);
    },

    pausePlayBack: function(name) {
      // TODO: Rename to `pausePlayback`
      Recorder.recorder.pausePlayBack(name);
    },

    playBackFrom: function(name, time) {
      // TODO: Rename to `playbackFrom`
      Recorder.recorder.playBackFrom(name, time);
    },

    record: function(name, filename) {
      Recorder.recorder.record(name, filename);
    },

    stopRecording: function() {
      Recorder.recorder.stopRecording();
    },

    stopPlayBack: function() {
      // TODO: Rename to `stopPlayback`
      Recorder.recorder.stopPlayBack();
    },

    observeLevel: function() {
      Recorder.recorder.observeLevel();
    },

    stopObservingLevel: function() {
      Recorder.recorder.stopObservingLevel();
    },

    observeSamples: function() {
      Recorder.recorder.observeSamples();
    },

    stopObservingSamples: function() {
      Recorder.recorder.stopObservingSamples();
    },

    resize: function(width, height) {
      Recorder.recorder.width = width + "px";
      Recorder.recorder.height = height + "px";
    },

    defaultSize: function() {
      Recorder.resize(Recorder.recorderOriginalWidth, Recorder.recorderOriginalHeight);
    },

    show: function() {
      Recorder.recorder.show();
    },

    hide: function() {
      Recorder.recorder.hide();
    },

    duration: function(name) {
      // TODO: rename to `getDuration`
      return Recorder.recorder.duration(name || Recorder.uploadFieldName);
    },

    getBase64: function(name) {
      var data = Recorder.recorder.getBase64(name);
      return 'data:' + RECORDED_AUDIO_TYPE + ';base64,' + data;
    },

    getBlob: function(name) {
      var base64Data = Recorder.getBase64(name).split(',')[1];
      return base64toBlob(base64Data, RECORDED_AUDIO_TYPE);
    },

    getCurrentTime: function(name) {
    	return Recorder.recorder.getCurrentTime(name);
    },

    isMicrophoneAccessible: function() {
      return Recorder.recorder.isMicrophoneAccessible();
    },

    updateForm: function() {
      var frm = $(Recorder.uploadFormId);
      Recorder.recorder.update(frm.serializeArray());
    },

    showPermissionWindow: function(options) {
      Recorder.resize(240, 160);
      // need to wait until app is resized before displaying permissions screen
      var permissionCommand = function() {
        // if (options && options.permanent) {
          Recorder.recorder.permitPermanently();
        // } else {
          // Recorder.recorder.permit();
        // }
      };
      setTimeout(permissionCommand, 1);
    },

    configure: function(rate, gain, silenceLevel, silenceTimeout) {
      rate = parseInt(rate || 22);
      gain = parseInt(gain || 100);
      silenceLevel = parseInt(silenceLevel || 0);
      silenceTimeout = parseInt(silenceTimeout || 4000);
      switch(rate) {
      case 44:
      case 22:
      case 11:
      case 8:
      case 5:
        break;
      default:
        throw("invalid rate " + rate);
      }

      if(gain < 0 || gain > 100) {
        throw("invalid gain " + gain);
      }

      if(silenceLevel < 0 || silenceLevel > 100) {
        throw("invalid silenceLevel " + silenceLevel);
      }

      if(silenceTimeout < -1) {
        throw("invalid silenceTimeout " + silenceTimeout);
      }

      Recorder.recorder.configure(rate, gain, silenceLevel, silenceTimeout);
    },

    setUseEchoSuppression: function(val) {
      if(typeof(val) != 'boolean') {
        throw("invalid value for setting echo suppression, val: " + val);
      }

      Recorder.recorder.setUseEchoSuppression(val);
    },

    setLoopBack: function(val) {
      if(typeof(val) != 'boolean') {
        throw("invalid value for setting loop back, val: " + val);
      }

      Recorder.recorder.setLoopBack(val);
    }
  };

  function base64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      var slice = byteCharacters.slice(offset, offset + sliceSize);

      var byteNumbers = new Array(slice.length);
      for (var i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      var byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, {type: contentType});
  }

  window.FWRecorder = Recorder;

})(this);<|endoftext|>


<commit_before>var glow = function(whattoglow, color){
    oofoofoofoof = document.getElementById(whattoglow);
    oofoofoofoof.style.color = color;
    oofoofoofoof.style.textShadow = "0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color;
}

//What to add?
<commit_msg>Testing<commit_after>var glow = function(whattoglow, color){
    oofoofoofoof = document.getElementById(whattoglow);
    oofoofoofoof.style.color = color;
    oofoofoofoof.style.textShadow = "0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color + ", 0px 0px 15px " + color;
}

//What to add?
var createAnimation = function(){
    var args = arguments;
}
<|endoftext|>


<commit_before>/*\
title: $:/core/modules/widgets/checklist.js
type: application/javascript
module-type: widget

Implements the <$checklist> widget - to render a list of checkboxes representing a checklist.
The name field must be specified if there is more than one checklist in a tiddler to disambiguate where the checklist data should be saved.

```
<$checklist name=""/>
```

\*/

(function(){

/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;

var ChecklistWidget = function(parseTreeNode,options) {
    this.initialise(parseTreeNode,options);
};

ChecklistWidget.prototype = new Widget();

ChecklistWidget.prototype.render = function(parent,nextSibling) {
    this.allowActionPropagation();
    this.parentDomNode = parent;
    this.computeAttributes();
    this.execute();
    var domNode = this.create(parent,nextSibling);
    this.domNodes.push(domNode);
    parent.insertBefore(domNode,nextSibling);

    // We don't want to render the actual text in the checkbox widget
    //this.renderChildren(domNode,null);
};

ChecklistWidget.prototype.execute = function() {
    this.tiddlerTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));

    // Generate the name for the storage tiddler
    var name = this.getAttribute("name");
    var storageBase = "$:/checklistPlugin/data/";
    if (name !== undefined || name !== "") {
        this.storageName = storageBase + this.tiddlerTitle;
    } else {
        this.storageName = storageBase + this.tiddlerTitle + "-" + name;
    }

    // Make child widgets
    this.makeChildWidgets();
};

/*
Selectively refreshes the widget if needed. Returns true if the widget or any of its children needed re-rendering
*/
ChecklistWidget.prototype.refresh = function(changedTiddlers) {
    var changedAttributes = this.computeAttributes();
    if(changedAttributes.filter || changedAttributes.list || changedAttributes.tiddler) {
        this.refreshSelf();
        return true;
    } else {
        return this.refreshChildren(changedTiddlers);
    }
};

ChecklistWidget.prototype.removeChildDomNodes = function() {
    $tw.utils.each(this.domNodes,function(domNode) {
        domNode.parentNode.removeChild(domNode);
    });
    this.domNodes = [];
};

ChecklistWidget.prototype.create = function() {
    var domNode = $tw.utils.domMaker("div",{class:"checklist"});
    var domList = document.createElement("ul");
    domNode.appendChild(domList);

    // Store the ul so we can add items to it later
    this.domList = domList;

    var listItems = this.wiki.getTiddlerData(this.storageName, {});
    for (var index in listItems) {
        var checklistItem = listItems[index];
        var listItem = document.createElement('li');

        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "box-" + index;
        checkbox.id = "box-" + index;
        if (checklistItem.checked) {
            checkbox.checked = true;
        }

        var itemText = document.createElement('input');
        itemText.type = "text";
        itemText.value = checklistItem.text;
        itemText.id = "itemtext-" + index;

        var del = document.createElement('button');
        del.innerHTML = "✘";
        del.className = "checklist-del";
        del.id = "del-" + index;

        // add handler to change list item state when checkbox state is changed
        $tw.utils.addEventListeners(checkbox, [
            {name: "change", handlerObject: this, handlerMethod: "handleChangeEvent"}
        ]);

        // add handler to update list item text on textbox blur
        $tw.utils.addEventListeners(itemText, [
            {name: "blur", handlerObject: this, handlerMethod: "handleItemTextChangeEvent"}
        ]);

        // add handler to delete tiddler when ✘ button is clicked
        $tw.utils.addEventListeners(del, [
            {name: "click", handlerObject: this, handlerMethod: "handleDeleteItemEvent"}
        ]);

        listItem.appendChild(checkbox);
        listItem.appendChild(itemText);
        listItem.appendChild(del);
        domList.appendChild(listItem);
    }

    var addItemButton = document.createElement('button');
    addItemButton.innerHTML = "New List Item";
    addItemButton.className = "checklist-ctrl";
    $tw.utils.addEventListeners(addItemButton, [
        {name:"click", handlerObject: this, handlerMethod: "handleAddItemButton"}
    ]);
    domNode.appendChild(addItemButton);

    var clearChecksButton = document.createElement('button');
    clearChecksButton.innerHTML = "Clear Checks";
    clearChecksButton.className = "checklist-ctrl";
    $tw.utils.addEventListeners(clearChecksButton, [
        {name:"click", handlerObject: this, handlerMethod: "handleClearChecksButton"}
    ]);
    domNode.appendChild(clearChecksButton);

    return domNode;
};

ChecklistWidget.prototype.extractItemID = function(event) {
    var itemName = event.target.id;
    return itemName.split("-")[1];
}

ChecklistWidget.prototype.handleItemTextChangeEvent = function(event) {
    var index = this.extractItemID(event);
    var listItem = this.wiki.getTiddlerData(this.storageName)[index];
    listItem.text = event.target.value;
    this.updateListItem(index, listItem);
};

ChecklistWidget.prototype.handleAddItemButton = function(event) {
    var newItem = document.createElement('input');
    newItem.type = "text";
    newItem.placeholder = "New Item";

    $tw.utils.addEventListeners(newItem, [
        {name:"blur", handlerObject: this, handlerMethod: "handleNewItemBlur"}
    ]);

    this.domList.appendChild(newItem);

    newItem.focus();
    return true;
};

ChecklistWidget.prototype.handleNewItemBlur = function(event) {
    var text = event.target.value;
    if (text !== "") {
        this.addListItem(text);
    }

    this.refreshSelf();
};

ChecklistWidget.prototype.handleClearChecksButton = function(event) {
    var listItems = this.wiki.getTiddlerData(this.storageName, {});
    for (var index in listItems) {
        listItems[index].checked = false;
        this.updateListItem(index, listItems[index]);
    }

    this.refreshSelf();
};

ChecklistWidget.prototype.handleDeleteItemEvent = function(event) {
    var index = this.extractItemID(event);
    this.deleteListItem(index);

    this.refreshSelf();
    return true;
};

ChecklistWidget.prototype.deleteListItem = function(index) {
    this.updateListItem(index, undefined);

    var listItems = this.wiki.getTiddlerData(this.storageName, {});
    var lastIndex;
    for (var i in listItems) {
        lastIndex = i;
        if (i <= index) {
            continue;
        }

        this.updateListItem(i-1, listItems[i]);
    }

    if (lastIndex > index) {
        this.updateListItem(lastIndex, undefined);
    }
};

ChecklistWidget.prototype.updateListItem = function(index, data) {
    this.wiki.setText(this.storageName, "text", index, data);
};

ChecklistWidget.prototype.addListItem = function(text) {
    var existingListItems = this.wiki.getTiddlerData(this.storageName, {});
    var index = Object.keys(existingListItems).length + 1;
    this.updateListItem(index, {"text": text, "checked": false});
};

ChecklistWidget.prototype.toggleChecked = function(index) {
    var listItem = this.wiki.getTiddlerData(this.storageName)[index];
    listItem.checked = !listItem.checked;

    this.updateListItem(index, listItem);
};

ChecklistWidget.prototype.handleChangeEvent = function(event) {
    var index = this.extractItemID(event);
    this.toggleChecked(index);

    // refresh this widget, and thereby the child widgets AND the enclosed
    // content of this widget
    this.refreshSelf();
    return true;
};

exports.checklist = ChecklistWidget;

})();
<commit_msg>Add documentation to function definitions<commit_after>/*\
title: $:/core/modules/widgets/checklist.js
type: application/javascript
module-type: widget

Implements the <$checklist> widget - to render a list of checkboxes representing a checklist.
The name field must be specified if there is more than one checklist in a tiddler to disambiguate where the checklist data should be saved.

```
<$checklist name=""/>
```

\*/

(function(){

/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var Widget = require("$:/core/modules/widgets/widget.js").widget;

var ChecklistWidget = function(parseTreeNode,options) {
    this.initialise(parseTreeNode,options);
};

ChecklistWidget.prototype = new Widget();

ChecklistWidget.prototype.render = function(parent,nextSibling) {
    this.allowActionPropagation();
    this.parentDomNode = parent;
    this.computeAttributes();
    this.execute();
    var domNode = this.create(parent,nextSibling);
    this.domNodes.push(domNode);
    parent.insertBefore(domNode,nextSibling);

    // We don't want to render the actual text in the checkbox widget
    //this.renderChildren(domNode,null);
};

ChecklistWidget.prototype.execute = function() {
    this.tiddlerTitle = this.getAttribute("tiddler",this.getVariable("currentTiddler"));

    // Generate the name for the storage tiddler
    var name = this.getAttribute("name");
    var storageBase = "$:/checklistPlugin/data/";
    if (name !== undefined || name !== "") {
        this.storageName = storageBase + this.tiddlerTitle;
    } else {
        this.storageName = storageBase + this.tiddlerTitle + "-" + name;
    }

    // Make child widgets
    this.makeChildWidgets();
};

// Selectively refresh the widget, returning true if the widget or children need
// re-rendering
ChecklistWidget.prototype.refresh = function(changedTiddlers) {
    var changedAttributes = this.computeAttributes();
    if(changedAttributes.filter || changedAttributes.list || changedAttributes.tiddler) {
        this.refreshSelf();
        return true;
    } else {
        return this.refreshChildren(changedTiddlers);
    }
};

ChecklistWidget.prototype.removeChildDomNodes = function() {
    $tw.utils.each(this.domNodes,function(domNode) {
        domNode.parentNode.removeChild(domNode);
    });
    this.domNodes = [];
};

// Create the actual checkbox UI, one list item for each checklist item
ChecklistWidget.prototype.create = function() {
    var domNode = $tw.utils.domMaker("div",{class:"checklist"});
    var domList = document.createElement("ul");
    domNode.appendChild(domList);

    // Store the ul so we can add items to it later
    this.domList = domList;

    var listItems = this.wiki.getTiddlerData(this.storageName, {});
    for (var index in listItems) {
        var checklistItem = listItems[index];
        var listItem = document.createElement('li');

        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "box-" + index;
        checkbox.id = "box-" + index;
        if (checklistItem.checked) {
            checkbox.checked = true;
        }

        var itemText = document.createElement('input');
        itemText.type = "text";
        itemText.value = checklistItem.text;
        itemText.id = "itemtext-" + index;

        var del = document.createElement('button');
        del.innerHTML = "✘";
        del.className = "checklist-del";
        del.id = "del-" + index;

        // add handler to change list item state when checkbox state is changed
        $tw.utils.addEventListeners(checkbox, [
            {name: "change", handlerObject: this, handlerMethod: "handleCheckboxChangeEvent"}
        ]);

        // add handler to update list item text on textbox blur
        $tw.utils.addEventListeners(itemText, [
            {name: "blur", handlerObject: this, handlerMethod: "handleItemTextChangeEvent"}
        ]);

        // add handler to delete tiddler when ✘ button is clicked
        $tw.utils.addEventListeners(del, [
            {name: "click", handlerObject: this, handlerMethod: "handleDeleteItemEvent"}
        ]);

        listItem.appendChild(checkbox);
        listItem.appendChild(itemText);
        listItem.appendChild(del);
        domList.appendChild(listItem);
    }

    var addItemButton = document.createElement('button');
    addItemButton.innerHTML = "New List Item";
    addItemButton.className = "checklist-ctrl";
    $tw.utils.addEventListeners(addItemButton, [
        {name:"click", handlerObject: this, handlerMethod: "handleAddItemButton"}
    ]);
    domNode.appendChild(addItemButton);

    var clearChecksButton = document.createElement('button');
    clearChecksButton.innerHTML = "Clear Checks";
    clearChecksButton.className = "checklist-ctrl";
    $tw.utils.addEventListeners(clearChecksButton, [
        {name:"click", handlerObject: this, handlerMethod: "handleClearChecksButton"}
    ]);
    domNode.appendChild(clearChecksButton);

    return domNode;
};

// Helper function to extract the data-tiddler index from a UI element
ChecklistWidget.prototype.extractItemID = function(event) {
    var itemName = event.target.id;
    return itemName.split("-")[1];
}

// Event handler which runs when a text box is changed (on blur)
ChecklistWidget.prototype.handleItemTextChangeEvent = function(event) {
    var index = this.extractItemID(event);
    var listItem = this.wiki.getTiddlerData(this.storageName)[index];
    listItem.text = event.target.value;
    this.updateListItem(index, listItem);
};

// Event handler which runs when the "New List Item" button is clicked
ChecklistWidget.prototype.handleAddItemButton = function(event) {
    var newItem = document.createElement('input');
    newItem.type = "text";
    newItem.placeholder = "New Item";

    $tw.utils.addEventListeners(newItem, [
        {name:"blur", handlerObject: this, handlerMethod: "handleNewItemBlur"}
    ]);

    this.domList.appendChild(newItem);

    newItem.focus();
    return true;
};

// Event handler which runs on blur of a new list item (save)
ChecklistWidget.prototype.handleNewItemBlur = function(event) {
    var text = event.target.value;
    if (text !== "") {
        this.addListItem(text);
    }

    this.refreshSelf();
};

// Event handler which runs when the "Clear Checks" button is clicked
ChecklistWidget.prototype.handleClearChecksButton = function(event) {
    var listItems = this.wiki.getTiddlerData(this.storageName, {});
    for (var index in listItems) {
        listItems[index].checked = false;
        this.updateListItem(index, listItems[index]);
    }

    this.refreshSelf();
};

// Event handler which runs when a list item delete button is clicked
ChecklistWidget.prototype.handleDeleteItemEvent = function(event) {
    var index = this.extractItemID(event);
    this.deleteListItem(index);

    this.refreshSelf();
    return true;
};

// Helper function to remove an item from the list
ChecklistWidget.prototype.deleteListItem = function(index) {
    this.updateListItem(index, undefined);

    var listItems = this.wiki.getTiddlerData(this.storageName, {});
    var lastIndex;
    for (var i in listItems) {
        lastIndex = i;
        if (i <= index) {
            continue;
        }

        this.updateListItem(i-1, listItems[i]);
    }

    if (lastIndex > index) {
        this.updateListItem(lastIndex, undefined);
    }
};

// Helper function to change the value of an item in the data tiddler
ChecklistWidget.prototype.updateListItem = function(index, data) {
    this.wiki.setText(this.storageName, "text", index, data);
};

// Helper function to add a new item to the data tiddler
ChecklistWidget.prototype.addListItem = function(text) {
    var existingListItems = this.wiki.getTiddlerData(this.storageName, {});
    var index = Object.keys(existingListItems).length + 1;
    this.updateListItem(index, {"text": text, "checked": false});
};

// Helper function to change the checked status of an item in the data tiddler
ChecklistWidget.prototype.toggleChecked = function(index) {
    var listItem = this.wiki.getTiddlerData(this.storageName)[index];
    listItem.checked = !listItem.checked;

    this.updateListItem(index, listItem);
};

// Event handler which runs when a list item checkbox is clicked
ChecklistWidget.prototype.handleCheckboxChangeEvent = function(event) {
    var index = this.extractItemID(event);
    this.toggleChecked(index);

    // refresh this widget, and thereby the child widgets AND the enclosed
    // content of this widget
    this.refreshSelf();
    return true;
};

exports.checklist = ChecklistWidget;

})();
<|endoftext|>


<commit_before>
/*

  cli.js

*/

var program   = require("commander"),
    chalk     = require("chalk"),
    data      = require("./data-editor"),
    locals    = require("./locals-editor"),
    pipelines = require("./pipelines-editor"),
    routes    = require("./routes-editor"),
    utils     = require("./cli-utils");

module.exports = function() {

  program
    .version("0.7.0")

  program
    .command("start")
    .action(start);

  program
    .command("help")
    .action(showHelp);

  program
    .command("config")
    .action(function() {
      listPipelines()
      listFolders("data");
      listFolders("scripts");
      listFolders("statics");
      listFolders("styles");
      listFolders("views");
    });

  program
    .command("data")
    .action(data.list);

  program
    .command("data:add <folder>")
    .action(data.add);

  program
    .command("data:remove <folder>")
    .action(data.remove);

  program
    .command("locals")
    .action(locals.list);

  program
    .command("locals:add <key> <value>")
    .action(locals.add);

  program
    .command("locals:remove <key>")
    .action(locals.remove);

  program
    .command("pipelines")
    .action(pipelines.list);

  program
    .command("pipelines:add <extension> <pipeline>")
    .action(pipelines.add);

  program
    .command("pipelines:remove <extension>")
    .action(pipelines.remove);

  // Set start as default argument
  if ("undefined" == typeof process.argv[2]) process.argv[2] = "start";
  program.parse(process.argv);

};

function start() {

  console.log(chalk.green.bold("\nStarting server...\n"));
  require("../server/")();

}

function showHelp() {

  console.log("");
  console.log(chalk.cyan(" Usage:"));
  console.log("");
  console.log("    " + chalk.magenta("sneakers") + chalk.yellow(" <command> [<args>]"));
  console.log("");
  console.log(chalk.cyan(" Commands:"));
  console.log("");

  readHelpFile("main.json").forEach(listCommand);

}

readHelpFile = function(p) {
  return JSON.parse(utils.readFile(require("path").join(__dirname, "help", "main.json"), "utf8"));
}

listCommand = function(command, description) {

  var key = command.command;

  // Allow for blank line
  if ("" === key) return console.log("");

  // Pad key
  key = utils.pad(key, 39);

  // Replace <commands> with yellow
  key = key.replace(/\"?\<[^\>]+\>\"?/g, function(x) { return chalk.yellow(x) });;
  console.log("    " + key + "  " + command.description);
}
<commit_msg>cli#start: adds browserSync functionality (removed from server)<commit_after>
/*

  cli.js

*/

var program   = require("commander"),
    chalk     = require("chalk"),
    data      = require("./data-editor"),
    locals    = require("./locals-editor"),
    pipelines = require("./pipelines-editor"),
    routes    = require("./routes-editor"),
    utils     = require("./cli-utils");

module.exports = function() {

  program
    .version("0.7.0")

  program
    .command("start")
    .action(start);

  program
    .command("help")
    .action(showHelp);

  program
    .command("config")
    .action(function() {
      listPipelines()
      listFolders("data");
      listFolders("scripts");
      listFolders("statics");
      listFolders("styles");
      listFolders("views");
    });

  program
    .command("data")
    .action(data.list);

  program
    .command("data:add <folder>")
    .action(data.add);

  program
    .command("data:remove <folder>")
    .action(data.remove);

  program
    .command("locals")
    .action(locals.list);

  program
    .command("locals:add <key> <value>")
    .action(locals.add);

  program
    .command("locals:remove <key>")
    .action(locals.remove);

  program
    .command("pipelines")
    .action(pipelines.list);

  program
    .command("pipelines:add <extension> <pipeline>")
    .action(pipelines.add);

  program
    .command("pipelines:remove <extension>")
    .action(pipelines.remove);

  // Set start as default argument
  if ("undefined" == typeof process.argv[2]) process.argv[2] = "start";
  program.parse(process.argv);

};

/**

  Starts the server

**/

function start() {

  var server = require("../server/");

  // Start the server
  console.log(chalk.green.bold("\nStarting server...\n"));
  server({
    liveRefresh: true
  });

  // Start browser sync and proxy
  global.server.init({ proxy : "localhost:" + global.ports.proxy });

}

function showHelp() {

  console.log("");
  console.log(chalk.cyan(" Usage:"));
  console.log("");
  console.log("    " + chalk.magenta("sneakers") + chalk.yellow(" <command> [<args>]"));
  console.log("");
  console.log(chalk.cyan(" Commands:"));
  console.log("");

  readHelpFile("main.json").forEach(listCommand);

}

readHelpFile = function(p) {
  return JSON.parse(utils.readFile(require("path").join(__dirname, "help", "main.json"), "utf8"));
}

listCommand = function(command, description) {

  var key = command.command;

  // Allow for blank line
  if ("" === key) return console.log("");

  // Pad key
  key = utils.pad(key, 39);

  // Replace <commands> with yellow
  key = key.replace(/\"?\<[^\>]+\>\"?/g, function(x) { return chalk.yellow(x) });;
  console.log("    " + key + "  " + command.description);
}
<|endoftext|>


<commit_before>#! /usr/bin/env node

const net = require('net')
const fs = require('fs')
const path = require('path')
const util = require('util')
const assert = require('assert')
const program = require('commander')
const xTime = require('x-time')
const spawn = require('child_process').spawn
const Tail = require('tail').Tail
const leftpad = require('leftpad')
const rightpad = require('rightpad')

const z1 = require('./../remote/index')
const pack = require('./../package.json')
const spam = require('./message')
const features = require('./features')
const parser = require('./parser')

const SPACER = '--'

const argv = process.argv.slice()
let args = []
if(argv.includes(SPACER)) {
  args = argv.splice(argv.indexOf(SPACER))
  args.shift()
}

program
  .version(pack.version)
  .action(function (cmd) {
    handle(new Error(`command "${cmd}" not found`))
  })

program
  .command('resurrect')
  .description('start the apps that were started before exit')
  .action(() => {
    spam.start()
    z1.resurrect().then(data => {
      spam.stop()
      console.log('workers started:', data.started)
    }).catch(handle)
  })

program
  .command('start [dir]')
  .usage('[options] [dir] [-- [arguments]]')
  .description('start the app in the dir')
  .option('-n, --name <name>', 'name of your app')
  .option('-p, --ports <ports>', 'ports that your app listens to', parser.ports)
  .option('-w, --workers <workers>', 'count of workers (default: number of CPUs)', parseInt)
  .option('-o, --output <output>', 'directory for the log files of this app', parser.path)
  .option('-e, --env <env>', 'environment variables e.g. NODE_ENV=development', parser.env)
  .action((dir, opts) => {

    // prepare opts
    const opt = {
      name: opts.name,
      workers: opts.workers,
      ports: opts.ports,
      output: opts.output
    }

    // parse environment variables
    const env = Object.assign({}, process.env, opts.env)

    spam.start()
    z1.start(dir, args, opt, env).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('ports:', data.ports.join())
      console.log('workers started:', data.started)
    }).catch(handle)
  })

program
  .command('stop [appName]')
  .description('stop the app specified by the appName')
  .option('-t, --timeout <timeout>', 'time until the workers get killed')
  .option('-s, --signal <signal>', 'kill signal')
  .action((appName = getAppName(), opts) => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    z1.stop(appName, opt).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('restart [appName]')
  .description('restart the app specified by the appName')
  .option('-t, --timeout <timeout>', 'time until the old workers get killed')
  .option('-s, --signal <signal>', 'kill signal for the old workers')
  .action((appName = getAppName(), opts) => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    z1.restart(appName, opt).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('ports:', data.ports.join())
      console.log('workers started:', data.started)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('restart-all')
  .description('restart all apps')
  .option('-t, --timeout <timeout>', 'time until the old workers get killed')
  .option('-s, --signal <signal>', 'kill signal for the old workers')
  .action(opts => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    z1.restartAll(opt).then(data => {
      spam.stop()
      console.log('workers started:', data.started)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('logs [appName]')
  .description('show the output of an app')
  .action((appName = getAppName()) => {
    const configPath = path.join(process.env.HOME, '.z1', 'config.json')

    let config = null
    try {
      config = require(configPath)
    } catch(err) {
      handle(new Error('config.json not found'))
    }

    let streams = []
    let oldFiles = []

    const app = config.apps.find(e => e.name === appName)

    const output = (app && app.opt.output) || path.join(process.env.HOME, '.z1', appName)

    updateLogs()
    setInterval(updateLogs, 5000)

    function updateLogs() {
      fs.readdir(output, (err, files) => {
        if(err) {
          if(err.code === 'ENOENT') {
            handle(new Error(`app "${appName}" not found`))
          } else {
            handle(err)
          }
        }

        files = files.sort().slice(-2)

        if(oldFiles.join() === files.join()) {
          return
        }

        // stop old streams
        streams.forEach(stream => {
          stream.unwatch()
        })

        oldFiles = files

        if(!files.length) {
          return
        }

        // add new streams
        streams = files.map(file => {
          const stream = new Tail(path.join(output, file))
          stream.on('line', line => {
            console.log(line)
          })
          stream.on('error', handle)
          stream.watch()

          return stream
        })
      })
    }
  })

program
  .command('info [appName]')
  .description('show specific infos about an app')
  .action((appName = getAppName()) => {
    z1.info(appName).then(stats => {
      console.log('name:', stats.name)
      console.log('directory:', stats.dir)
      console.log('ports:', stats.ports.join())
      console.log('workers:')
      console.log('  pending:', stats.pending)
      console.log('  available:', stats.available)
      console.log('  killed:', stats.killed)
      console.log('revive count:', stats.reviveCount)
    })
  })

program
  .command('list')
  .description('overview of all running workers')
  .option('-m, --minimal', 'minimalistic list (easy to parse)')
  .action(opt => {
    z1.list().then(data => {
      const props = Object.keys(data.stats)

      if(opt.minimal) {
        console.log(props.join(' '))
        return
      }

      if(!props.length) {
        console.log('no workers running')
        return
      }

      const max = process.stdout.columns

      console.log('workers  name                 ports')
      for(const prop of props) {
        const obj = data.stats[prop]
        const p = leftpad(obj.pending, 2)
        const a = leftpad(obj.available, 2)
        const k = leftpad(obj.killed, 2)
        const name = rightpad(prop, 20)
        const ports = obj.ports.join() || '-'
        console.log(p, a, k, name, ports)
      }
      console.log(' |  |  |')
      console.log(' |  | killed')
      console.log(' | available')
      console.log('pending')

      if(data.isResurrectable) {
        console.log('\nThe listed apps are currently not running.\nType "z1 resurrect" to start them.')
      }
    }).catch(handle)
  })

program
  .command('exit')
  .description('kill the z1 daemon')
  .action(() => {
    z1.exit().then(data => {
      console.log('daemon stopped')
    }).catch(handle)
  })

program
  .command('install [feature]')
  .description('install additional features')
  .option('-m, --minimal', 'minimalistic list (easy to parse)')
  .action((feature, opts) => {
    // features:
    // zsh (completion)
    // bash (completion)
    // cron (resurrect)

    const folder = path.join(__dirname, '..', 'install')

    if(opts.minimal) {
      Object.keys(features).forEach((feature, i, list) => {
        process.stdout.write(feature)
        if(list[i+1]) {
          process.stdout.write(' ')
        }
      })
      process.stdout.write('\n')

    } else if(!feature) {
      console.log('\nFeatures:\n')
      Object.keys(features).forEach(feature => {
        console.log(`${feature} - ${features[feature]}`)
      })
      console.log()
    } else if (features.hasOwnProperty(feature)) {
      const file = path.join(folder, feature)
      const installer = spawn(file, [], {
        cwd: folder,
        stdio: 'inherit',
        shell: true
      })
      installer.on('error', handle)
      installer.on('exit', (code) => {
        process.exit(code)
      })
    } else {
      handle(new Error('feature not found'))
    }
  })

  program
    .command('uninstall <feature>')
    .description('uninstall features')
    .action((feature, opts) => {

      const folder = path.join(__dirname, '..', 'uninstall')

      if (features.hasOwnProperty(feature)) {
        const file = path.join(folder, feature)
        const uninstaller = spawn(file, [], {
          cwd: folder,
          stdio: 'inherit',
          shell: true
        })
        uninstaller.on('error', handle)
        uninstaller.on('exit', (code) => {
          process.exit(code)
        })
      } else {
        handle(new Error('feature not found'))
      }
    })

if(process.argv.length === 2) {
  handle(new Error('no command given'))
}

program.parse(argv)

function getAppName() {
  log('no appName given')
  log('searching directory for package.json')
  try {
    const file = path.join(process.cwd(), 'package.json')
    const pack = require(file)
    assert(pack.name)
    log(`found name "${pack.name}" in package.json`)
    return pack.name
  } catch(err) {
    console.error(`no package.json file found`)
    handle(new Error('missing argument `appName\''))
  }
}

function log(...msg) {
  if(process.env.DEBUG) {
    console.log(...msg)
  }
}

function handle(err) {
  if(process.env.DEBUG) {
    console.error(err)
  } else {
    console.error(`\n  error: ${err.message}\n`)
  }
  process.exit(1)
}
<commit_msg>catch errors in info command<commit_after>#! /usr/bin/env node

const net = require('net')
const fs = require('fs')
const path = require('path')
const util = require('util')
const assert = require('assert')
const program = require('commander')
const xTime = require('x-time')
const spawn = require('child_process').spawn
const Tail = require('tail').Tail
const leftpad = require('leftpad')
const rightpad = require('rightpad')

const z1 = require('./../remote/index')
const pack = require('./../package.json')
const spam = require('./message')
const features = require('./features')
const parser = require('./parser')

const SPACER = '--'

const argv = process.argv.slice()
let args = []
if(argv.includes(SPACER)) {
  args = argv.splice(argv.indexOf(SPACER))
  args.shift()
}

program
  .version(pack.version)
  .action(function (cmd) {
    handle(new Error(`command "${cmd}" not found`))
  })

program
  .command('resurrect')
  .description('start the apps that were started before exit')
  .action(() => {
    spam.start()
    z1.resurrect().then(data => {
      spam.stop()
      console.log('workers started:', data.started)
    }).catch(handle)
  })

program
  .command('start [dir]')
  .usage('[options] [dir] [-- [arguments]]')
  .description('start the app in the dir')
  .option('-n, --name <name>', 'name of your app')
  .option('-p, --ports <ports>', 'ports that your app listens to', parser.ports)
  .option('-w, --workers <workers>', 'count of workers (default: number of CPUs)', parseInt)
  .option('-o, --output <output>', 'directory for the log files of this app', parser.path)
  .option('-e, --env <env>', 'environment variables e.g. NODE_ENV=development', parser.env)
  .action((dir, opts) => {

    // prepare opts
    const opt = {
      name: opts.name,
      workers: opts.workers,
      ports: opts.ports,
      output: opts.output
    }

    // parse environment variables
    const env = Object.assign({}, process.env, opts.env)

    spam.start()
    z1.start(dir, args, opt, env).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('ports:', data.ports.join())
      console.log('workers started:', data.started)
    }).catch(handle)
  })

program
  .command('stop [appName]')
  .description('stop the app specified by the appName')
  .option('-t, --timeout <timeout>', 'time until the workers get killed')
  .option('-s, --signal <signal>', 'kill signal')
  .action((appName = getAppName(), opts) => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    z1.stop(appName, opt).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('restart [appName]')
  .description('restart the app specified by the appName')
  .option('-t, --timeout <timeout>', 'time until the old workers get killed')
  .option('-s, --signal <signal>', 'kill signal for the old workers')
  .action((appName = getAppName(), opts) => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    z1.restart(appName, opt).then(data => {
      spam.stop()
      console.log('name:', data.app)
      console.log('ports:', data.ports.join())
      console.log('workers started:', data.started)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('restart-all')
  .description('restart all apps')
  .option('-t, --timeout <timeout>', 'time until the old workers get killed')
  .option('-s, --signal <signal>', 'kill signal for the old workers')
  .action(opts => {
    const opt = {
      timeout: opts.timeout,
      signal: opts.signal
    }
    spam.start()
    z1.restartAll(opt).then(data => {
      spam.stop()
      console.log('workers started:', data.started)
      console.log('workers killed:', data.killed)
    }).catch(handle)
  })

program
  .command('logs [appName]')
  .description('show the output of an app')
  .action((appName = getAppName()) => {
    const configPath = path.join(process.env.HOME, '.z1', 'config.json')

    let config = null
    try {
      config = require(configPath)
    } catch(err) {
      handle(new Error('config.json not found'))
    }

    let streams = []
    let oldFiles = []

    const app = config.apps.find(e => e.name === appName)

    const output = (app && app.opt.output) || path.join(process.env.HOME, '.z1', appName)

    updateLogs()
    setInterval(updateLogs, 5000)

    function updateLogs() {
      fs.readdir(output, (err, files) => {
        if(err) {
          if(err.code === 'ENOENT') {
            handle(new Error(`app "${appName}" not found`))
          } else {
            handle(err)
          }
        }

        files = files.sort().slice(-2)

        if(oldFiles.join() === files.join()) {
          return
        }

        // stop old streams
        streams.forEach(stream => {
          stream.unwatch()
        })

        oldFiles = files

        if(!files.length) {
          return
        }

        // add new streams
        streams = files.map(file => {
          const stream = new Tail(path.join(output, file))
          stream.on('line', line => {
            console.log(line)
          })
          stream.on('error', handle)
          stream.watch()

          return stream
        })
      })
    }
  })

program
  .command('info [appName]')
  .description('show specific infos about an app')
  .action((appName = getAppName()) => {
    z1.info(appName).then(stats => {
      console.log('name:', stats.name)
      console.log('directory:', stats.dir)
      console.log('ports:', stats.ports.join())
      console.log('workers:')
      console.log('  pending:', stats.pending)
      console.log('  available:', stats.available)
      console.log('  killed:', stats.killed)
      console.log('revive count:', stats.reviveCount)
    }).catch(handle)
  })

program
  .command('list')
  .description('overview of all running workers')
  .option('-m, --minimal', 'minimalistic list (easy to parse)')
  .action(opt => {
    z1.list().then(data => {
      const props = Object.keys(data.stats)

      if(opt.minimal) {
        console.log(props.join(' '))
        return
      }

      if(!props.length) {
        console.log('no workers running')
        return
      }

      const max = process.stdout.columns

      console.log('workers  name                 ports')
      for(const prop of props) {
        const obj = data.stats[prop]
        const p = leftpad(obj.pending, 2)
        const a = leftpad(obj.available, 2)
        const k = leftpad(obj.killed, 2)
        const name = rightpad(prop, 20)
        const ports = obj.ports.join() || '-'
        console.log(p, a, k, name, ports)
      }
      console.log(' |  |  |')
      console.log(' |  | killed')
      console.log(' | available')
      console.log('pending')

      if(data.isResurrectable) {
        console.log('\nThe listed apps are currently not running.\nType "z1 resurrect" to start them.')
      }
    }).catch(handle)
  })

program
  .command('exit')
  .description('kill the z1 daemon')
  .action(() => {
    z1.exit().then(data => {
      console.log('daemon stopped')
    }).catch(handle)
  })

program
  .command('install [feature]')
  .description('install additional features')
  .option('-m, --minimal', 'minimalistic list (easy to parse)')
  .action((feature, opts) => {
    // features:
    // zsh (completion)
    // bash (completion)
    // cron (resurrect)

    const folder = path.join(__dirname, '..', 'install')

    if(opts.minimal) {
      Object.keys(features).forEach((feature, i, list) => {
        process.stdout.write(feature)
        if(list[i+1]) {
          process.stdout.write(' ')
        }
      })
      process.stdout.write('\n')

    } else if(!feature) {
      console.log('\nFeatures:\n')
      Object.keys(features).forEach(feature => {
        console.log(`${feature} - ${features[feature]}`)
      })
      console.log()
    } else if (features.hasOwnProperty(feature)) {
      const file = path.join(folder, feature)
      const installer = spawn(file, [], {
        cwd: folder,
        stdio: 'inherit',
        shell: true
      })
      installer.on('error', handle)
      installer.on('exit', (code) => {
        process.exit(code)
      })
    } else {
      handle(new Error('feature not found'))
    }
  })

  program
    .command('uninstall <feature>')
    .description('uninstall features')
    .action((feature, opts) => {

      const folder = path.join(__dirname, '..', 'uninstall')

      if (features.hasOwnProperty(feature)) {
        const file = path.join(folder, feature)
        const uninstaller = spawn(file, [], {
          cwd: folder,
          stdio: 'inherit',
          shell: true
        })
        uninstaller.on('error', handle)
        uninstaller.on('exit', (code) => {
          process.exit(code)
        })
      } else {
        handle(new Error('feature not found'))
      }
    })

if(process.argv.length === 2) {
  handle(new Error('no command given'))
}

program.parse(argv)

function getAppName() {
  log('no appName given')
  log('searching directory for package.json')
  try {
    const file = path.join(process.cwd(), 'package.json')
    const pack = require(file)
    assert(pack.name)
    log(`found name "${pack.name}" in package.json`)
    return pack.name
  } catch(err) {
    console.error(`no package.json file found`)
    handle(new Error('missing argument `appName\''))
  }
}

function log(...msg) {
  if(process.env.DEBUG) {
    console.log(...msg)
  }
}

function handle(err) {
  if(process.env.DEBUG) {
    console.error(err)
  } else {
    console.error(`\n  error: ${err.message}\n`)
  }
  process.exit(1)
}
<|endoftext|>


<commit_before>/**

  cli

**/

//
//  Dependencies
//

var program    = require("commander"),
    chalk      = require("chalk"),
    data       = require("./data-editor"),
    middleware = require("./middleware-editor"),
    pipelines  = require("./pipelines-editor"),
    routes     = require("./routes-editor"),
    utils      = require("./cli-utils"),
    vars       = require("./vars-editor");

//
//  Exports
//

module.exports = function() {

  var command = process.argv[2];

  // Set start as default argument
  if ("undefined" == typeof process.argv[2]) process.argv[2] = "help";

  // Throw error with pipelines if missing quotes
  if ("pipelines:add" === process.argv[2] && !(/^('.+'|".+")$/.test(process.argv[4]))) {

    // Chalk colors are ignored in console.error. We must use chalk.styles
    var msg = chalk.styles.red.open + "\n   Error! " + chalk.styles.red.close;
    console.error(msg + "Pipelines must be surrounded by quotes to prevent the > operator from creating a file.");
    console.error("          You may want to ensure that no additional file was created.\n");
    return;
  }

  program
    .version("0.7.0");

  program
    .command("start")
    .action(start);

  program
    .command("help")
    .action(showHelp);

  program
    .command("config")
    .action(function() {
      data.list();
      vars.listEnvs();
      vars.listLocals();
      middleware.list();
      pipelines.list();
      routes.list();
    });

  program
    .command("data")
    .action(data.list);

  program
    .command("data:add <folder> [route]")
    .action(data.add);

  program
    .command("data:remove <folder>")
    .action(data.remove);

  program
    .command("defaults")
    .action(listDefaults);

  program
    .command("defaults:restore")
    .action(restoreDefaults);

  program
    .command("env")
    .action(vars.listEnvs);

  program
    .command("env:add <key> <value>")
    .action(vars.addEnv);

  program
    .command("env:remove <key>")
    .action(vars.removeEnv);

  program
    .command("locals")
    .action(vars.listLocals);

  program
    .command("locals:add <key> <value>")
    .action(vars.addLocal);

  program
    .command("locals:remove <key>")
    .action(vars.removeLocal);

  program
    .command("middleware")
    .action(middleware.list);

  program
    .command("middleware:add <position> <package>")
    .action(middleware.add);

  program
    .command("middleware:remove <position> <package>")
    .action(middleware.remove);

  program
    .command("pipelines")
    .action(pipelines.list);

  program
    .command("pipelines:add <extension> <pipeline>")
    .action(pipelines.add);

  program
    .command("pipelines:remove <extension>")
    .action(pipelines.remove);

  program
    .command("routes")
    .action(routes.list);

  program
    .command("routes:scripts <route> <folder> <bundleFolders>")
    .action(routes.scripts);

  program
    .command("routes:statics <route> <folder>")
    .action(routes.statics);

  program
    .command("routes:styles <route> <folder>")
    .action(routes.styles);

  program
    .command("routes:views <route> <folder>")
    .action(routes.views);

  program
    .command("routes:remove <route>")
    .action(routes.remove);

  program.parse(process.argv);

};

/**

  Starts the server

**/

function start(env) {

  var server = require("../server/");

  // Start the server
  console.log(chalk.green.bold("\nStarting server...\n"));

  if (/^prod/i.test(env)) {
    process.env.NODE_ENV = "production";
    server();
  } else {
    // Start browser sync and proxy
    server({ liveRefresh: true });
    global.server.init({ proxy : "localhost:" + global.ports.server });
  }

}

/**

  Shows help on commands

**/

function showHelp() {

  var columns = [];

  console.log("");
  console.log("To start the server, run", chalk.magenta("shipp start"));
  console.log("");
  console.log(chalk.cyan(" Usage:"));
  console.log("");
  console.log("    " + chalk.magenta("shipp") + chalk.yellow(" <command> [<args>]"));
  console.log("");
  console.log(chalk.cyan(" Commands:"));
  console.log("");

  readHelpFile("main.json").forEach(listCommand);

}

/**

  Helper to read in a file from the help directory

**/

function readHelpFile(filename) {
  return JSON.parse(utils.readFile(require("path").join(__dirname, "help", filename), "utf8"));
}

/**

  Helper to list a command, properly spaced

**/

function listCommand(command, description) {

  var key = command.command;

  // Allow for blank line
  if ("" === key) return console.log("");

  // Pad key
  key = utils.pad(key, 39);

  // Replace <commands> with yellow
  key = key.replace(/\"?<[^>]+>\"?/g, function(x) { return chalk.yellow(x); });
  console.log("    " + key + "  " + command.description);

}

/**

  Lists defaults

**/

function listDefaults() {

  require("./config-editor").loadDefaults();

  console.log("");
  console.log(chalk.magenta(" Note:"), "The following settings are the defaults and may or may not reflect your");
  console.log("       app's configuration. To see your config, use the", chalk.yellow("config"), "command. To");
  console.log("       restore defaults, use the", chalk.yellow("defaults:restore"), "command.");

  data.list();
  vars.listEnvs();
  vars.listLocals();
  middleware.list();
  pipelines.list();
  routes.list();

}

/**

  Deletes the shipp.json file and restores defaults.

**/

function restoreDefaults() {

  var str;

  console.log("");
  str  = chalk.red("   Warning!") + " This command will delete your ";
  str += chalk.yellow("shipp.json") + " file (using default options instead)";
  console.log(str);
  console.log("   To continue type DELETE and press enter.");

  process.stdout.write("   > ");

  process.stdout.on("data", function(res) {
    console.log("");
    res = res.toString().trim();

    if (/^delete$/i.test(res)) {
      console.log("   We've restored defaults by deleting your", chalk.yellow("shipp.json"), "file");
      require("./config-editor").remove();
    } else
      console.log("   Nothing done. Come back if you need us.");

    console.log("");
    process.exit();
  });

}
<commit_msg>cli: removes "quotation" requirement (does not work)<commit_after>/**

  cli

**/

//
//  Dependencies
//

var program    = require("commander"),
    chalk      = require("chalk"),
    data       = require("./data-editor"),
    middleware = require("./middleware-editor"),
    pipelines  = require("./pipelines-editor"),
    routes     = require("./routes-editor"),
    utils      = require("./cli-utils"),
    vars       = require("./vars-editor");

//
//  Exports
//

module.exports = function() {

  var command = process.argv[2];

  // Set start as default argument
  if ("undefined" == typeof process.argv[2]) process.argv[2] = "help";

  program
    .version("0.7.0");

  program
    .command("start")
    .action(start);

  program
    .command("help")
    .action(showHelp);

  program
    .command("config")
    .action(function() {
      data.list();
      vars.listEnvs();
      vars.listLocals();
      middleware.list();
      pipelines.list();
      routes.list();
    });

  program
    .command("data")
    .action(data.list);

  program
    .command("data:add <folder> [route]")
    .action(data.add);

  program
    .command("data:remove <folder>")
    .action(data.remove);

  program
    .command("defaults")
    .action(listDefaults);

  program
    .command("defaults:restore")
    .action(restoreDefaults);

  program
    .command("env")
    .action(vars.listEnvs);

  program
    .command("env:add <key> <value>")
    .action(vars.addEnv);

  program
    .command("env:remove <key>")
    .action(vars.removeEnv);

  program
    .command("locals")
    .action(vars.listLocals);

  program
    .command("locals:add <key> <value>")
    .action(vars.addLocal);

  program
    .command("locals:remove <key>")
    .action(vars.removeLocal);

  program
    .command("middleware")
    .action(middleware.list);

  program
    .command("middleware:add <position> <package>")
    .action(middleware.add);

  program
    .command("middleware:remove <position> <package>")
    .action(middleware.remove);

  program
    .command("pipelines")
    .action(pipelines.list);

  program
    .command("pipelines:add <extension> <pipeline>")
    .action(pipelines.add);

  program
    .command("pipelines:remove <extension>")
    .action(pipelines.remove);

  program
    .command("routes")
    .action(routes.list);

  program
    .command("routes:scripts <route> <folder> <bundleFolders>")
    .action(routes.scripts);

  program
    .command("routes:statics <route> <folder>")
    .action(routes.statics);

  program
    .command("routes:styles <route> <folder>")
    .action(routes.styles);

  program
    .command("routes:views <route> <folder>")
    .action(routes.views);

  program
    .command("routes:remove <route>")
    .action(routes.remove);

  program.parse(process.argv);

};

/**

  Starts the server

**/

function start(env) {

  var server = require("../server/");

  // Start the server
  console.log(chalk.green.bold("\nStarting server...\n"));

  if (/^prod/i.test(env)) {
    process.env.NODE_ENV = "production";
    server();
  } else {
    // Start browser sync and proxy
    server({ liveRefresh: true });
    global.server.init({ proxy : "localhost:" + global.ports.server });
  }

}

/**

  Shows help on commands

**/

function showHelp() {

  var columns = [];

  console.log("");
  console.log("To start the server, run", chalk.magenta("shipp start"));
  console.log("");
  console.log(chalk.cyan(" Usage:"));
  console.log("");
  console.log("    " + chalk.magenta("shipp") + chalk.yellow(" <command> [<args>]"));
  console.log("");
  console.log(chalk.cyan(" Commands:"));
  console.log("");

  readHelpFile("main.json").forEach(listCommand);

}

/**

  Helper to read in a file from the help directory

**/

function readHelpFile(filename) {
  return JSON.parse(utils.readFile(require("path").join(__dirname, "help", filename), "utf8"));
}

/**

  Helper to list a command, properly spaced

**/

function listCommand(command, description) {

  var key = command.command;

  // Allow for blank line
  if ("" === key) return console.log("");

  // Pad key
  key = utils.pad(key, 39);

  // Replace <commands> with yellow
  key = key.replace(/\"?<[^>]+>\"?/g, function(x) { return chalk.yellow(x); });
  console.log("    " + key + "  " + command.description);

}

/**

  Lists defaults

**/

function listDefaults() {

  require("./config-editor").loadDefaults();

  console.log("");
  console.log(chalk.magenta(" Note:"), "The following settings are the defaults and may or may not reflect your");
  console.log("       app's configuration. To see your config, use the", chalk.yellow("config"), "command. To");
  console.log("       restore defaults, use the", chalk.yellow("defaults:restore"), "command.");

  data.list();
  vars.listEnvs();
  vars.listLocals();
  middleware.list();
  pipelines.list();
  routes.list();

}

/**

  Deletes the shipp.json file and restores defaults.

**/

function restoreDefaults() {

  var str;

  console.log("");
  str  = chalk.red("   Warning!") + " This command will delete your ";
  str += chalk.yellow("shipp.json") + " file (using default options instead)";
  console.log(str);
  console.log("   To continue type DELETE and press enter.");

  process.stdout.write("   > ");

  process.stdout.on("data", function(res) {
    console.log("");
    res = res.toString().trim();

    if (/^delete$/i.test(res)) {
      console.log("   We've restored defaults by deleting your", chalk.yellow("shipp.json"), "file");
      require("./config-editor").remove();
    } else
      console.log("   Nothing done. Come back if you need us.");

    console.log("");
    process.exit();
  });

}
<|endoftext|>


<commit_before>function ajax(params){
	params = params||{};
	if (!params.url) {
        throw new Error('Necessary parameters are missing.'); //必要参数未填
    }
	var options = {
		url: params.url||'',	//接口地址
		type: (params.type||'GET').toUpperCase(),	//请求方式
		timeout: params.timeout||5000,	//超时等待时间
		async : true,	//是否异步
		xhrFields:{},	//设置XHR对象属性键值对。如果需要，可设置withCredentials为true的跨域请求。
		dataType: params.dataType||'json',	//请求的数据类型
		data: params.data||{},	//参数
		jsonp:'callback',
		jsonpCallback:('jsonp_' + Math.random()).replace('.',''),
		error: params.error||function() {},
		success: params.success||function(){},
		complete: params.complete||function(){}
	};
	var formatParams = function(json) {
        var arr = [];
        for(var i in json) {
            arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(json[i]));
        }
        return arr.join("&");
    };
	if(options.dataType=='jsonp'){
		//插入动态脚本及回调函数
		var $head = document.getElementsByTagName('head')[0];
		var $script = document.createElement('script');
		$head.appendChild($script);
        window[options.jsonpCallback] = function (json) {
            $head.removeChild($script);
            window[options.jsonpCallback] = null;
            hander && clearTimeout(hander);
            options.success(json);
            options.complete();
        };
        //发送请求
        options.data[options.jsonp] = options.jsonpCallback;
        $script.src = options.url + '?' + formatParams(options.data);
        //超时处理
        var hander = setTimeout(function(){
            $head.removeChild($script);
            window[options.jsonpCallback] = null;
            options.error();
            options.complete();
        }, options.timeout);
	}else{
		//创建xhr对象
		var xhr = new (self.XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP");
		if(!xhr){
			return false;
		}
		//发送请求
		options.data = formatParams(options.data);
		if (options.type == 'POST') {
			xhr.open(options.type, options.url, options.async);
			xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
		}else{
			options.url += options.url.indexOf('?')>-1?'&'+options.data:'?'+options.data;
			options.data = null;
			xhr.open(options.type, options.url + '?'+ options.data, options.async);
		}
		if(options.xhrFields){
			for(var field in options.xhrFields){
				xhr[field]= options.xhrFields[field];
			}
		}
		xhr.send(options.data);
		//超时处理
		var requestDone = false;
		setTimeout(function() {
			requestDone = true;
			if(xhr.readyState != 4){
				xhr.abort();
			}
		}, options.timeout);
		//状态处理
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4&&!requestDone) {
				if(xhr.status>=200 && xhr.status<300) {
					var data = options.dataType == "xml" ? xhr.responseXML : xhr.responseText;
					if (options.dataType == "json") {
						try{
							data =  JSON.parse(data);
						}catch(e){
							data = eval('(' + data + ')');
						}
					}
					options.success(data);
				} else {
					options.error();
				}
				options.complete();
			}
		};
	}
}
<commit_msg>updated 超时及浏览器缓存处理<commit_after>function ajax(params){
	params = params||{};
	if (!params.url) {
        throw new Error('Necessary parameters are missing.'); //必要参数未填
    }
	var options = {
		url: params.url||'',	//接口地址
		type: (params.type||'GET').toUpperCase(),	//请求方式
		timeout: params.timeout||5000,	//超时等待时间
		async : true,	//是否异步
		xhrFields:{},	//设置XHR对象属性键值对。如果需要，可设置withCredentials为true的跨域请求。
		dataType: params.dataType||'json',	//请求的数据类型
		data: params.data||{},	//参数
		jsonp:'callback',
		jsonpCallback:('jsonp_' + Math.random()).replace('.',''),
		error: params.error||function() {},
		success: params.success||function(){},
		complete: params.complete||function(){}
	};
	var formatParams = function(json) {
        var arr = [];
        for(var i in json) {
            arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(json[i]));
        }
        return arr.join("&");
    };
	if(options.dataType=='jsonp'){
		//插入动态脚本及回调函数
		var $head = document.getElementsByTagName('head')[0];
		var $script = document.createElement('script');
		$head.appendChild($script);
        window[options.jsonpCallback] = function (json) {
            $head.removeChild($script);
            window[options.jsonpCallback] = null;
            hander && clearTimeout(hander);
            options.success(json);
            options.complete();
        };
        //发送请求
        options.data[options.jsonp] = options.jsonpCallback;
        $script.src = options.url + '?' + formatParams(options.data);
        //超时处理
        var hander = setTimeout(function(){
            $head.removeChild($script);
            window[options.jsonpCallback] = null;
            options.error();
            options.complete();
        }, options.timeout);
	}else{
		//创建xhr对象
		var xhr = new (self.XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP");
		if(!xhr){
			return false;
		}
		//发送请求
		options.data = formatParams(options.data);
		if (options.type == 'POST') {
			xhr.open(options.type, options.url, options.async);
			xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
		}else{
			options.url += options.url.indexOf('?')>-1?'&'+options.data:'?'+options.data;
			options.data = null;
			xhr.open(options.type, options.url + '?'+ options.data, options.async);
		}
		if(options.xhrFields){
			for(var field in options.xhrFields){
				xhr[field]= options.xhrFields[field];
			}
		}
		xhr.send(options.data);
		//超时处理
		var requestDone = false;
		setTimeout(function() {
			requestDone = true;
			if(xhr.readyState != 4){
				xhr.abort();
				options.error();
			}
			options.complete();
		}, options.timeout);
		//状态处理
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4&&!requestDone) {
				if(xhr.status>=200 && xhr.status<300||xhr.status == 304) {
					var data = options.dataType == "xml" ? xhr.responseXML : xhr.responseText;
					if (options.dataType == "json") {
						try{
							data =  JSON.parse(data);
						}catch(e){
							data = eval('(' + data + ')');
						}
					}
					options.success(data);
				} else {
					options.error();
				}
				options.complete();
			}
		};
	}
}
<|endoftext|>


<commit_before>(function() {
  var Communist, Socialist,
    __slice = [].slice;

  Communist = function(fun) {
    var bUrl, blob, body, _worker,
      _this = this;
    if (typeof fun !== "function") {
      return;
    }
    window.URL = window.URL || window.webkiURL;
    body = "var _f =  " + (fun.toString()) + ";self.addEventListener('message', function(_e) {self.send = function(data){self.postMessage({messege:data,cb:_e.data.cb})};try{self.postMessage({body:_f.apply(null, _e.data.body),cb:_e.data.cb})}catch(_err){self.postMessege({error:_err,cb:_e.data.cb})}})";
    blob = new Blob([body], {
      type: "text/javascript"
    });
    bUrl = window.URL.createObjectURL(blob);
    _worker = new Worker(bUrl);
    this.CBs = {};
    this.send = function() {
      var cb, data, id, _i;
      data = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), cb = arguments[_i++];
      id = ("" + Math.random()).slice(2);
      _this.CBs[id] = cb;
      _worker.postMessage({
        body: data,
        cb: id
      });
      _worker.onmessage = function(e) {
        if (e.data.body) {
          _this.CBs[e.data.cb](null, e.data.body);
          delete _this.CBs[e.data.cb];
        } else if (e.data.messege) {
          _this.CBs[e.data.cb](null, e.data.messege);
        } else if (e.data.error) {
          CBs[e.data.cb](e.data.error);
          delete _this.CBs[e.data.cb];
        }
        return true;
      };
      _worker.onerror = function(e) {
        cb(e);
        return true;
      };
      return true;
    };
    this.close = function() {
      _worker.terminate();
      return true;
    };
    return true;
  };

  Socialist = function(fun) {
    var _func;
    _func = fun;
    this.send = function() {
      var cb, data, _i;
      data = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), cb = arguments[_i++];
      this.self = {};
      this.self.send = function(m) {
        return cb.apply(this, [null, m]);
      };
      try {
        cb.apply(this, [null, _func.apply(null, data)]);
      } catch (err) {
        cb(err);
      }
      return true;
    };
    this.close = function() {
      _func = void 0;
      return true;
    };
    return true;
  };

  window.communist = function(fun) {
    if (window.Worker) {
      return new Communist(fun);
    } else {
      return new Socialist(fun);
    }
  };

}).call(this);
<commit_msg>build<commit_after>(function() {
  var Communist, Socialist,
    __slice = [].slice;

  Communist = function(fun) {
    var bUrl, blob, body, _worker,
      _this = this;
    if (typeof fun !== "function") {
      return;
    }
    window.URL = window.URL || window.webkiURL;
    body = "var _f =  " + (fun.toString()) + ";self.addEventListener('message', function(_e) {self.send = function(data){self.postMessage({messege:data,cb:_e.data.cb})};try{self.postMessage({body:_f.apply(null, _e.data.body),cb:_e.data.cb})}catch(_err){self.postMessege({error:_err,cb:_e.data.cb})}})";
    blob = new Blob([body], {
      type: "text/javascript"
    });
    bUrl = window.URL.createObjectURL(blob);
    _worker = new Worker(bUrl);
    this.CBs = {};
    this.send = function() {
      var cb, data, id, _i;
      data = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), cb = arguments[_i++];
      id = ("" + Math.random()).slice(2);
      _this.CBs[id] = cb;
      _worker.postMessage({
        body: data,
        cb: id
      });
      _worker.onmessage = function(e) {
        if (e.data.body) {
          _this.CBs[e.data.cb](null, e.data.body);
          delete _this.CBs[e.data.cb];
        } else if (e.data.messege) {
          _this.CBs[e.data.cb](null, e.data.messege);
        } else if (e.data.error) {
          CBs[e.data.cb](e.data.error);
          delete _this.CBs[e.data.cb];
        }
        return true;
      };
      _worker.onerror = function(e) {
        cb(e);
        return true;
      };
      return true;
    };
    this.close = function() {
      _worker.terminate();
      return true;
    };
    return this;
  };

  Socialist = function(fun) {
    var _func;
    _func = fun;
    this.send = function() {
      var cb, data, _i;
      data = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), cb = arguments[_i++];
      this.self = {};
      this.self.send = function(m) {
        return cb.apply(this, [null, m]);
      };
      try {
        cb.apply(this, [null, _func.apply(null, data)]);
      } catch (err) {
        cb(err);
      }
      return true;
    };
    this.close = function() {
      _func = void 0;
      return true;
    };
    return this;
  };

  window.communist = function(fun) {
    if (window.Worker) {
      return new Communist(fun);
    } else {
      return new Socialist(fun);
    }
  };

}).call(this);
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var config = require('./config.js');
var logger = require('../libs/logger.js');

var mongoose_uri = process.env.OPENSHIFT_MONGODB_DB_URL || config.get("mongoose:uri")

mongoose.connect(mongoose_uri);

mongoose.connection.on('error', function callback() {
	logger.error('Could not connect to %s', mongoose_uri + config.get("mongoose:name"));
});

mongoose.connection.once('open', function callback () {
	logger.info('Database is connected to %s', mongoose_uri);
});

module.exports = mongoose;<commit_msg>Update DB config<commit_after>var mongoose = require('mongoose');
var config = require('./config.js');
var logger = require('../libs/logger.js');

var mongoose_uri = process.env.OPENSHIFT_MONGODB_DB_URL || config.get("mongoose:uri")

mongoose.connect(mongoose_uri + config.get("mongoose:name"));

mongoose.connection.on('error', function callback() {
	logger.error('Could not connect to %s', mongoose_uri + config.get("mongoose:name"));
});

mongoose.connection.once('open', function callback () {
	logger.info('Database is connected to %s', mongoose_uri + config.get("mongoose:name"));
});

module.exports = mongoose;<|endoftext|>