<commit_before>// Dependencies
var Barbe = require("barbe")
  , Fs = require("fs")
  , Path = require("path")
  , JxUtils = require("jxutils")
  , MarkDox = require("markdox")
  , IsThere = require("is-there")
  , ReadJson = require("r-json")
  , WriteJson = require("w-json")
  , ParentSearch = require("parent-search")
  , Streamp = require("streamp")
  , Ul = require("ul")
  , SameTime = require("same-time")
  ;

// Constants
const BLAH_DIR = ".blah"
    , README_NAME = "README.md"
    , TEMPLATES = "templates"
    , PACKAGE_JSON = "package.json"
    , INDEX_JSON = "index.json"
    , DOCUMENTATION_FILE_NAME = "DOCUMENTATION.md"
    , MARKDOX_EJS = "markdox.ejs"
    ;

/*!
 * Blah
 * Creates a new `Blah` instance.
 *
 * @name Blah
 * @function
 */
function Blah(options) {
    if (typeof options === "string") {
        options = {
            path: options
        };
    }

    options = Ul.merge(options, {
        path: process.cwd()
      , templates_path: Path.join(Ul.USER_DIR, ".blah-templates")
    });

    this.blah_dir = Path.join(options.path, BLAH_DIR);
    this.blah_index = Path.join(this.blah_dir, INDEX_JSON);
    this.path = options.path;
    this.templates = {};
    this.pack = {};
    this.blah = {};

    if (IsThere(options.templates_path)) {
        this.templates_path = options.templates_path;
    } else {
        this.templates_path = Path.join(__dirname, TEMPLATES)
    }
}

Blah.prototype.search = function (file, callback) {
    var self = this
      , tries = [

            // Local .blah/file
            Path.join(self.blah_dir, file)

            // Templates: ~/.blah-templates/file
          , Path.join(self.templates_path, file)

            // Library templates: templates/file
          , Path.join(__dirname, "templates", file)
        ]
      ;

    SameTime(tries.map(function (cPath) {
        return function (cb) {
            IsThere(cPath, function (exists) {
                cb(null, cPath, exists);
            });
        }
    }), function (err, fields, exists) {
        if (err) { return callback(err); }
        for (var i = 0; i < exists.length; ++i) {
            if (exists[i]) {
                return callback(null, fields[i]);
            }
        }
    });
};

/**
 * prepare
 * Prepares the Blah data.
 *
 * @name prepare
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.prepare = function (callback) {
    var self = this;
    SameTime([
        self.search.bind(self, MARKDOX_EJS)
      , function (cb) {
            ParentSearch(self.path, PACKAGE_JSON, { obj: true }, function (data) {
                cb(null, data);
            });
        }
        // Read the readme template
      , Fs.readFile.bind(self, Path.join(self.templates_path, README_NAME), "utf-8")
        // Read the .blah/index.json
      , function (cb) {
            ReadJson(self.blah_index, function (err, blahData) {
                if (err) {
                    err = null;
                    blahData = {};
                }
                cb(err, blahData);
            });
        }
    ], function (err, data) {
        if (err) { return callback(err); }
        self.markdox_tmpl = data[0];
        ReadJson(data[1].p, function (err, pack) {
            if (err) { return callback(err); }
            self.pack = pack;
            callback();
        });
        self.templates.readme = data[2];
        self.templates.blah = data[3];
    });
};

/**
 * init
 * Inits the `.blah` directory in the current project.
 *
 * @name init
 * @function
 * @param {Object} options An object containing the following fields:
 *
 *  - `readme` (Object): Data to render the `README.md` template.
 *  - `blah` (Object): An object which will be written to `.blah/index.json`
 *
 * @param {Function} callback The callback function.
 */
Blah.prototype.init = function (options, callback) {

    if (typeof options === "function") {
        callback = options;
        options = {};
    }

    options = Ul.merge(options, {
        blah: {}
      , readme: {}
    });

    var self = this
      , readme = new Streamp.writable(Path.join(self.blah_dir, README_NAME))
      ;

    // Run the init tasks
    SameTime([
        // Prepare data
        self.prepare.bind(self)
    ], function (err, data) {
        if (err) { return callback(err); }

        self.blah_data = Ul.merge(options.blah, self.templates.blah);

        SameTime([
            WriteJson.bind(self, self.blah_index, self.blah_data)
          , function (cb) {
                readme.end(Barbe(self.templates.readme, options.readme));
                callback();
            }
        ], callback);
    });
};

/**
 * generateDocs
 * Generate documentation file from package.json main file.
 *
 * @name generateDocs
 * @function
 * @param {String} input Input file name (default: main file from package.json)
 * @param {String} output Output file name (default: `DOCUMENTATION.md`)
 * @param {Function} callback The callback function
 */
Blah.prototype.docs = function (input, output, callback) {
    var self = this;
    if (typeof output === "function") {
        callback = output;
        output = DOCUMENTATION_FILE_NAME;
    }
    self.prepare(function (err) {
        if (err) { return callback(err); }
        MarkDox.process(input, {
            template: self.markdox_tmpl
          , output: output
        }, callback);
    });
};

/**
 * generateReadme
 * Returns a string representing the readme content of the project.
 *
 * @name generateReadme
 * @function
 * @param {Function} callback The callback function
 * @return {undefined}
 */
Blah.prototype.readme = function (callback) {

    var self = this;

    self.prepare(function (err) {
        if (err) { return callback(err); }
        SameTime([
            function (cb) {
                IsThere(self.pack.main, function (exists) {
                    if (!exists) { return cb(null, ""); }
                    MarkDox.process(self.pack.main, {
                        template: self.markdox_tmpl
                    }, function (err, docs) {
                        cb(err, docs);
                    });
                });
            }
        ], function (err, data) {
            if (err) { return callback(err); }
            content = Barbe(self.templates.readme, ["{", "}"], {
                pack: self.pack
              , docs: data[0]
            });
            Fs.writeFile("README.md", content, callback);
        });
    });
};

/**
 * generateGitignore
 * Returns the content of .gitignore file
 *
 * @name generateGitignore
 * @function
 * @return {String} Content of gitignore file.
 */
Blah.prototype.generateGitignore = function () {

    var content =
        "*.swp\n" +
        "*.swo\n" +
        "*~\n" +
        "*.log\n" +
        "node_modules"
      ;

    return content;
};
//
///**
// * generateLicense
// * Returns the content of the LICENSE by providing the `@licenseName`.
// *
// * @name generateLicense
// * @function
// * @param {String} licenseName The license name (e.g. `mit`)
// * @return {String} The content of license.
// */
//Blah.prototype.generateLicense = function (licenseName) {
//
//    var fullName = null
//      , pack = require(process.env.PWD + "/package")
//      ;
//
//    try {
//        var gitconfigLines = Fs.readFileSync(
//            require('path-extra').homedir() + "/.gitconfig"
//        ).toString().replace(/\t/g, "").split("\n");
//        for (var i = 0; i < gitconfigLines.length; ++i) {
//            var cLine = gitconfigLines[i].trim();
//            if (/^name/.test(cLine)) {
//                fullName = cLine.split("=")[1].trim();
//                break;
//            }
//        }
//    } catch(e) {
//    }
//
//    if (!fullName) {
//        console.log("No fullname found in .gitconfig. Please modify LICENSE [fullname] manually");
//        fullName = "[fullname]";
//    }
//
//    return Fs
//        .readFileSync(__dirname + "/templates/licenses/" + licenseName.toLowerCase() + ".txt")
//        .toString()
//        .replace("[project]", pack.name)
//        .replace("[year]", new Date().getFullYear())
//        .replace("[fullname]", fullName)
//        .replace("[description]", pack.description)
//        ;
//};

module.exports = Blah;
<commit_msg>Simplified the init function<commit_after>// Dependencies
var Barbe = require("barbe")
  , Fs = require("fs")
  , Path = require("path")
  , JxUtils = require("jxutils")
  , MarkDox = require("markdox")
  , IsThere = require("is-there")
  , ReadJson = require("r-json")
  , WriteJson = require("w-json")
  , ParentSearch = require("parent-search")
  , Streamp = require("streamp")
  , Ul = require("ul")
  , SameTime = require("same-time")
  , Deffy = require("deffy")
  , Ejs = require("ejs")
  , Ncp = require("ncp")
  ;

// Constants
const BLAH_DIR = ".blah"
    , README_NAME = "README.ejs"
    , TEMPLATES = "templates"
    , PACKAGE_JSON = "package.json"
    , INDEX_JSON = "index.json"
    , DOCUMENTATION_FILE_NAME = "DOCUMENTATION.md"
    , MARKDOX_EJS = "markdox.ejs"
    ;

/*!
 * Blah
 * Creates a new `Blah` instance.
 *
 * @name Blah
 * @function
 */
function Blah(options) {
    if (typeof options === "string") {
        options = {
            path: options
        };
    }

    options = Ul.merge(options, {
        path: process.cwd()
    });

    // .blah/
    this.blah_dir = Path.join(options.path, BLAH_DIR);

    // ~/.blah-templates
    this.usr_templates = Path.join(Ul.USER_DIR, ".blah-templates");

    // templates/
    this.lib_templates = Path.join(__dirname, TEMPLATES);

    // TODO
    this.path = options.path;
    this.templates = {};
    this.pack = {};
    this.blah = {};
    this.paths = {};
}

Blah.prototype.search = function (file, callback) {
    if (typeof file === "function") {
        callback = file;
        file = "";
    }
    var self = this
      , tries = [

            // Local .blah/file
            Path.join(self.blah_dir, file)

            // Templates: ~/.blah-templates/file
          , Path.join(self.usr_templates, file)

            // Library templates: templates/file
          , Path.join(self.lib_templates, "templates", file)
        ]
      ;

    SameTime(tries.map(function (cPath) {
        return function (cb) {
            IsThere(cPath, function (exists) {
                cb(null, cPath, exists);
            });
        }
    }), function (err, fields, exists) {
        if (err) { return callback(err); }
        for (var i = 0; i < exists.length; ++i) {
            if (exists[i]) {
                return callback(null, fields[i]);
            }
        }
        callback(new Error("Cannot find searched file: " + file));
    });
};

/**
 * prepare
 * Prepares the Blah data.
 *
 * @name prepare
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.prepare = function (callback) {
    var self = this;

    // Find the paths
    SameTime([
        self.search.bind(self, MARKDOX_EJS)
      , self.search.bind(self, README_NAME)
      , self.search.bind(self, ".gitignore")
      , self.search.bind(self, "CONTRIBUTING.md")
      , self.search.bind(self, "blah.json")
      , function (cb) {
            ParentSearch(self.path, PACKAGE_JSON, cb.bind(this, null));
        }
    ], function (err, data) {
        if (err) { return callback(err); }

        self.paths.markdox = data[0];
        self.paths.readme = data[1];
        self.paths.gitignore = data[2];
        self.paths.contributing = data[3];
        self.paths.blah = data[4];
        self.paths.pack = data[5];

        // Read the template data
        SameTime([
            function (cb) {
                ReadJson(self.paths.pack, function (err, pack) {
                    pack = Deffy(pack, {});
                    cb(null, pack);
                });
            }
        ], function (err, data) {
            if (err) { return callback(err); }
            self.pack = data[0];
        });
    });
};

/**
 * init
 * Inits the `.blah` directory in the current project.
 *
 * @name init
 * @function
 * @param {Function} callback The callback function.
 */
Blah.prototype.init = function (callback) {
    var self = this;
    self.prepare(function (err) {
        if (err) { return callback(err); }
        self.search(function (err, path_templates) {
            if (err) { return callback(err); }
            Ncp(path_templates, self.blah_dir, callback);
        });
    });
};

/**
 * generateDocs
 * Generate documentation file from package.json main file.
 *
 * @name generateDocs
 * @function
 * @param {String} input Input file name (default: main file from package.json)
 * @param {String} output Output file name (default: `DOCUMENTATION.md`)
 * @param {Function} callback The callback function
 */
Blah.prototype.docs = function (input, output, callback) {
    var self = this;
    if (typeof output === "function") {
        callback = output;
        output = DOCUMENTATION_FILE_NAME;
    }
    self.prepare(function (err) {
        if (err) { return callback(err); }
        MarkDox.process(input, {
            template: self.markdox_tmpl
          , output: output
        }, callback);
    });
};

/**
 * generateReadme
 * Returns a string representing the readme content of the project.
 *
 * @name generateReadme
 * @function
 * @param {Function} callback The callback function
 * @return {undefined}
 */
Blah.prototype.readme = function (callback) {

    var self = this;

    self.prepare(function (err) {
        if (err) { return callback(err); }
        SameTime([
            function (cb) {
                IsThere(self.pack.main, function (exists) {
                    if (!exists) { return cb(null, ""); }
                    MarkDox.process(self.pack.main, {
                        template: self.markdox_tmpl
                    }, function (err, docs) {
                        cb(err, docs);
                    });
                });
            }
        ], function (err, data) {
            if (err) { return callback(err); }
            content = Barbe(self.templates.readme, ["{", "}"], {
                pack: self.pack
              , docs: data[0]
            });
            Fs.writeFile("README.md", content, callback);
        });
    });
};

/**
 * generateGitignore
 * Returns the content of .gitignore file
 *
 * @name generateGitignore
 * @function
 * @return {String} Content of gitignore file.
 */
Blah.prototype.generateGitignore = function () {

    var content =
        "*.swp\n" +
        "*.swo\n" +
        "*~\n" +
        "*.log\n" +
        "node_modules"
      ;

    return content;
};
//
///**
// * generateLicense
// * Returns the content of the LICENSE by providing the `@licenseName`.
// *
// * @name generateLicense
// * @function
// * @param {String} licenseName The license name (e.g. `mit`)
// * @return {String} The content of license.
// */
//Blah.prototype.generateLicense = function (licenseName) {
//
//    var fullName = null
//      , pack = require(process.env.PWD + "/package")
//      ;
//
//    try {
//        var gitconfigLines = Fs.readFileSync(
//            require('path-extra').homedir() + "/.gitconfig"
//        ).toString().replace(/\t/g, "").split("\n");
//        for (var i = 0; i < gitconfigLines.length; ++i) {
//            var cLine = gitconfigLines[i].trim();
//            if (/^name/.test(cLine)) {
//                fullName = cLine.split("=")[1].trim();
//                break;
//            }
//        }
//    } catch(e) {
//    }
//
//    if (!fullName) {
//        console.log("No fullname found in .gitconfig. Please modify LICENSE [fullname] manually");
//        fullName = "[fullname]";
//    }
//
//    return Fs
//        .readFileSync(__dirname + "/templates/licenses/" + licenseName.toLowerCase() + ".txt")
//        .toString()
//        .replace("[project]", pack.name)
//        .replace("[year]", new Date().getFullYear())
//        .replace("[fullname]", fullName)
//        .replace("[description]", pack.description)
//        ;
//};

module.exports = Blah;
<|endoftext|>


<commit_before>'use strict';

var ace = require('brace');
require('brace/mode/javascript');
require('brace/theme/monokai');

module.exports = function createEditor(container, src, opts) {
  var editorContainer = document.createElement('div');
  editorContainer.setAttribute('class', 'scriptie-talkie-editor');
  container.appendChild(editorContainer);

  var editor = ace.edit(editorContainer);
  editor.setTheme("ace/theme/monokai");
  editor.getSession().setMode("ace/mode/javascript");
  editor.$highlightActiveLine = false;
  editor.setValue(src);
  return { container: editorContainer, editor: editor };
};
<commit_msg>tabsize 2<commit_after>'use strict';

var ace = require('brace');
require('brace/mode/javascript');
require('brace/theme/monokai');

module.exports = function createEditor(container, src, opts) {
  var editorContainer = document.createElement('div');
  editorContainer.setAttribute('class', 'scriptie-talkie-editor');
  container.appendChild(editorContainer);

  var editor = ace.edit(editorContainer)
    , session = editor.getSession();

  editor.setTheme("ace/theme/monokai");
  session.setMode("ace/mode/javascript");
  session.$tabSize = 2;
  editor.$highlightActiveLine = false;
  editor.setValue(src);
  return { container: editorContainer, editor: editor };
};
<|endoftext|>


<commit_before>var Promise = require('bluebird');
var _ = require('lodash');
var inherits = require('inherits');
var EventEmitter = require('events').EventEmitter;
var fs = require('fs-extra');
var path = require('path');
var url = require('url');
var winresourcer = Promise.promisify(require('winresourcer'));
var spawn = require('child_process').spawn;
var semver = require('semver');

var NwVersions = require('./versions');
var Utils = require('./utils');
var Downloader = require('./downloader');

// We inherit from EventEmitter for logging
inherits(NwBuilder, EventEmitter);
module.exports = NwBuilder;
function NwBuilder(options) {
    var self = this;
    var defaults = {
        files: null,
        appName: false,
        appVersion: false,
        platforms: ['win','osx'],
        version: 'latest',
        buildDir: './build',
        cacheDir: './cache',
        downloadUrl: 'http://dl.node-webkit.org/',
        buildType: 'default',
        forceDownload: false,
        macCredits: false,
        macIcns: false,
        macZip: false,
        macPlist: false,
        winIco: null
    };

    // Assing options
    this.options = _.defaults(options, defaults);
    this._platforms = [{
        platform: 'win',
        needsZip: true,
        runable: 'nw.exe',
        files: { // First file must be the executable
            '<=0.9.2': ['nw.exe', 'ffmpegsumo.dll', 'icudt.dll', 'libEGL.dll', 'libGLESv2.dll', 'nw.pak'],
            '>0.9.2': ['nw.exe', 'ffmpegsumo.dll', 'icudtl.dat', 'libEGL.dll', 'libGLESv2.dll', 'nw.pak']
        }
    },{
        platform: 'osx',
        runable: 'node-webkit.app/Contents/MacOS/node-webkit',
        files: {
            '*': ['node-webkit.app']
        }
    },{
        platform: 'linux32',
        needsZip: true,
        chmod: '0755',
        runable: 'nw',
        files: { // First file must be the executable
            '<=0.9.2': ['nw', 'nw.pak', 'libffmpegsumo.so'],
            '>0.9.2': ['nw', 'nw.pak', 'libffmpegsumo.so', 'icudtl.dat']
        }
    },{
        platform: 'linux64',
        needsZip: true,
        chmod: '0755', // chmod file file to be executable
        runable: 'nw',
        files: { // First file must be the executable
            '<=0.9.2': ['nw', 'nw.pak', 'libffmpegsumo.so'],
            '>0.9.2': ['nw', 'nw.pak', 'libffmpegsumo.so', 'icudtl.dat']
        }
    }];

    // Some Option checking
    if(!this.options.files) {
        throw new Error('Please specify some files');
    }

    // Check Platforms
    this._platforms.forEach(function (platform) {
        platform.active = (self.options.platforms.indexOf(platform.platform) === -1 ? false : true);
    });
    // Platforms
    this._platforms = _.where(this._platforms, {'active':true});

    if(this._platforms.length === 0 || this._platforms.length === undefined) {
        throw new Error('No platform to build!');
    }

    return this;
};

NwBuilder.prototype.build = function (callback) {
    var hasCallback = (typeof callback === 'function'),
        done = Promise.defer();

    // Let's create a node Webkit app
    this.checkFiles().bind(this)
        .then(this.resolveLatestVersion)
        .then(this.checkVersion)
        .then(this.platformFilesForVersion)
        .then(this.downloadNodeWebkit)
        .then(this.createReleaseFolder)
        .then(this.copyNodeWebkit)
        .then(this.zipAppFiles)
        .then(this.mergeAppFiles)
        .then(this.handleMacApp)
        .then(this.handleWinApp)
        .then(function (info) {
            if(hasCallback) {
                callback(false, info);
            } else {
                done.resolve(info);
            }
        })
        .catch(function (error) {
            if(hasCallback) {
                callback(error);
            } else {
                done.reject(error);
            }
        });

    return hasCallback ? true : done.promise;
};

NwBuilder.prototype.run = function (callback) {
    var hasCallback = (typeof callback === 'function'),
        done = Promise.defer();

    // Let's run this node Webkit app
    this.checkFiles().bind(this)
        .then(this.resolveLatestVersion)
        .then(this.checkVersion)
        .then(this.platformFilesForVersion)
        .then(this.downloadNodeWebkit)
        .then(this.runApp)
        .then(function (info) {
            if(hasCallback) {
                callback(false, info);
            } else {
                done.resolve(info);
            }
        })
        .catch(function (error) {
            if(hasCallback) {
                callback(true, error);
            } else {
                done.reject(error);
            }
        });

    return hasCallback ? true : done.promise;
};

NwBuilder.prototype.checkFiles = function () {
    var self = this;

    return Utils.getFileList(this.options.files).then(function (data) {

        self._appPkg = data.json;
        self._files = data.files;

        if(!self.options.appName || self.options.appVersion) {
            return Utils.getPackageInfo(self._appPkg).then(function (appPkg) {
               self._appPkg = appPkg;
               self.options.appName = (self.options.appName ? self.options.appName : appPkg.name);
               self.options.appVersion = (self.options.appVersion ? self.options.appVersion : appPkg.version);
            });
        }
    });

};

NwBuilder.prototype.resolveLatestVersion = function () {
    var self = this;

    if(self.options.version !== 'latest') return Promise.resolve();

    return NwVersions.getLatestVersion(self.options.downloadUrl).then(function(latestVersion){
        self.emit('log', 'Latest Version: v' + latestVersion);
        self.options.version = latestVersion;
    });
};

NwBuilder.prototype.checkVersion = function () {
    var version = this.options.version.replace('v', '');

    if(!semver.valid(this.options.version)){
        return Promise.reject('The version ' + this.options.version + ' is not valid.');
    } else {
        this._version = NwVersions.getVersionNames( version );
        this.emit('log', 'Using v' + this._version.version);
    }

    return Promise.resolve();
};

NwBuilder.prototype.platformFilesForVersion = function () {
    var self = this;

    this._platforms.forEach(function (single_platform) {
        var satisfied = !Object.keys(single_platform.files).every(function(range) {
            if (semver.satisfies(self._version.version, range)) {
                single_platform.files = single_platform.files[range];
                return false;
            }
            return true;
        });

        if (!satisfied) {
            throw new Error("Unsupported node-webkit version '" + this._version.version + "' for platform '" + platform.type + "'");
        }
    });

    return true;
};

NwBuilder.prototype.downloadNodeWebkit = function () {
    var self = this,
        downloads = [];

    this._platforms.map(function (single_platform) {
        single_platform.cache = path.resolve(self.options.cacheDir, self._version.version, single_platform.platform);
        single_platform.url = url.resolve(self.options.downloadUrl, self._version.platforms[single_platform.platform]);

        // Ensure that there is a cache folder
        if(self.options.forceDownload) {
            fs.removeSync(single_platform.cache);
        }

        fs.mkdirpSync(single_platform.cache);
        self.emit('log', 'Create cache folder in ' + path.resolve(self.options.cacheDir, self._version.version));

        if(!Downloader.checkCache(single_platform.cache, single_platform.files)) {
            downloads.push(
                Downloader.downloadAndUnpack(single_platform.cache, single_platform.url)
                    .catch(function(err){
                        if(err.statusCode === 404){
                            self.emit('log', 'ERROR: The version '+self._version.version+' does not have a corresponding build posted at http://dl.node-webkit.org/. Please choose a version from that list.')
                        } else {
                            self.emit('log', err.msg)
                        }

                        return Promise.reject('Unable to download nodewebkit.');
                    })
            );
            self.emit('log', 'Downloading: ' + single_platform.url);
        } else {
            self.emit('log', 'Using cache for: ' + single_platform.platform);
        }

        return single_platform;
    });

    return Promise.all(downloads)
        .then(function(data) {
            Downloader.clearProgressbar();
            return data;
        });
};

NwBuilder.prototype.buildGypModules = function () {
    // @todo
    // If we trigger a rebuild we have to copy
    // the node_modules to a tmp location because
    // we don't want to change the source files

};

NwBuilder.prototype.createReleaseFolder = function () {
    var self = this,
        releasePath;

    if (_.isFunction(self.options.buildType)) {
      releasePath = self.options.buildType.call(self.options);
    } else {
      // buildTypes
      switch(self.options.buildType) {
          case 'timestamped':
              releasePath = self.options.appName + ' - ' + Math.round(Date.now() / 1000).toString();
          break;

          case 'versioned':
              releasePath = self.options.appName + ' - v' + self.options.appVersion;
          break;

          default:
              releasePath = self.options.appName;
      }
    }

    this._platforms.forEach(function (single_platform) {
        single_platform.releasePath = path.resolve(self.options.buildDir, releasePath, single_platform.platform);

        // Ensure that there is a release Folder, delete and create it.
        fs.removeSync(single_platform.releasePath);
        fs.mkdirpSync(single_platform.releasePath);
        self.emit('log', 'Create release folder in ' + single_platform.releasePath);
    });

    return true;

};

NwBuilder.prototype.copyNodeWebkit = function () {
    var self = this,
        copiedFiles = [];

    this._platforms.forEach(function (single_platform) {
        var executable = single_platform.runable.split('/')[0];
        single_platform.files.forEach(function (file, i) {
            var destFile = file;
            if(i===0) {
                // rename executable to app name
                destFile = self.options.appName + path.extname(file);
                // save new filename back to files list
                single_platform.files[0] = destFile;
            }
            copiedFiles.push(Utils.copyFile(path.resolve(single_platform.cache, file), path.resolve(single_platform.releasePath, destFile)));
        });
    });

    return Promise.all(copiedFiles);
};

NwBuilder.prototype.zipAppFiles = function () {
    var self = this;

    // Check if zip is needed
    this._needsZip = (self.options.macZip || _.any(this._platforms, {'needsZip':true}));

    return new Promise(function(resolve, reject) {
        if(self._needsZip) {
            Utils.generateZipFile(self._files, self).then(function (nwFile) {
                self._nwFile = nwFile;
                resolve();
            }, reject);
        } else {
            self._nwFile = null;
            resolve();
        }
    });
};

NwBuilder.prototype.mergeAppFiles = function () {
    var self = this,
        copiedFiles = [];

    this._platforms.forEach(function (single_platform) {
        // We copy the app files if we are on mac and don't force zip
        if(single_platform.platform === 'osx') {
            // no zip, copy the files
            if(!self.options.macZip) {
                self._files.forEach(function (file) {
                    var dest = path.resolve(single_platform.releasePath, self.options.appName+'.app', 'Contents', 'Resources', 'app.nw', file.dest);
                    copiedFiles.push(Utils.copyFile(file.src, dest));
                });
            } else {
                // zip just copy the app.nw
                copiedFiles.push(Utils.copyFile(self._nwFile, path.resolve(single_platform.releasePath, self.options.appName+'.app', 'Contents', 'Resources', 'nw.icns')));
            }
        } else {
            // We cat the app.nw file into the .exe / nw
            copiedFiles.push(Utils.mergeFiles(path.resolve(single_platform.releasePath, _.first(single_platform.files)), self._nwFile), single_platform.chmod);
        }
    });

    return Promise.all(copiedFiles);
};

NwBuilder.prototype.handleMacApp = function () {
    var self = this, allDone = [];
    var macPlatform = _.findWhere(self._platforms, {'platform':'osx'});
    if(!macPlatform) return Promise.resolve();

    // Let's first handle the mac icon
    if(self.options.macIcns) {
        allDone.push(Utils.copyFile(self.options.macIcns, path.resolve(macPlatform.releasePath, self.options.appName+'.app', 'Contents', 'Resources', 'nw.icns')));
    }

    // Let handle the Plist
    var PlistPath = path.resolve(macPlatform.releasePath, self.options.appName+'.app', 'Contents', 'Info.plist');

    // If the macPlist is a string we just copy the file
    if(typeof self.options.macPlist === 'String') {
        allDone.push(Utils.copyFile(self.options.macPlist, PlistPath));
    } else {
        // Setup the Plst
        var defaultPlist = {
            appName: self.options.appName,
            appVersion: self.options.appVersion,
            copyright: self._appPkg.copyright || false
        };

        var plistOptions = (self.options.macPlist ? _.defaults(self.options.macPlist, defaultPlist) : defaultPlist);
        allDone.push(Utils.editPlist(PlistPath, PlistPath, plistOptions));
    }

    return Promise.all(allDone);

};

NwBuilder.prototype.handleWinApp = function () {
    var self = this,
        done = Promise.defer();
    var winPlatform = _.findWhere(self._platforms, {'platform':'win'});
    if(!winPlatform || !self.options.winIco) return Promise.resolve();

    // Set icon
    if (self.options.winIco) {
        self.emit('log', 'Update executable icon');
        winresourcer({
            operation: "Update",
            exeFile: path.resolve(winPlatform.releasePath, _.first(winPlatform.files)),
            resourceType: "Icongroup",
            resourceName: "IDR_MAINFRAME",
            lang: 1033, // Required, except when updating or deleting
            resourceFile: path.resolve(self.options.winIco)
        }, function(err) {
            if(err) {
                done.reject('Error while updating the Windows icon.' +
                    (process.platform !== "win32" ? ' Wine (winehq.org) must be installed to add custom icons from Mac and Linux.' : '')
                );
            }
            else {
                done.resolve();
            }
        });
    }

    return done.promise;
};

NwBuilder.prototype.runApp = function () {
    var self = this,
        platform = this._platforms[0],
        executable = path.resolve(platform.cache, platform.runable);

        self.emit('log', 'Launching App');
        return new Promise(function(resolve, reject) {
            var p = spawn(executable, ['--enable-logging', self.options.files.replace(/\*[\/\*]*/,"")]);

            p.stdout.on('data', function(data) {
                self.emit('stdout', data);
            });

            p.stderr.on('data', function(data) {
                self.emit('stderr', data);
            });

            p.on('close', function(code) {
                self.emit('log', 'App exited with code ' + code);
                resolve();
            });
        });
};
<commit_msg>Fix macCredits option doesn't work<commit_after>var Promise = require('bluebird');
var _ = require('lodash');
var inherits = require('inherits');
var EventEmitter = require('events').EventEmitter;
var fs = require('fs-extra');
var path = require('path');
var url = require('url');
var winresourcer = Promise.promisify(require('winresourcer'));
var spawn = require('child_process').spawn;
var semver = require('semver');

var NwVersions = require('./versions');
var Utils = require('./utils');
var Downloader = require('./downloader');

// We inherit from EventEmitter for logging
inherits(NwBuilder, EventEmitter);
module.exports = NwBuilder;
function NwBuilder(options) {
    var self = this;
    var defaults = {
        files: null,
        appName: false,
        appVersion: false,
        platforms: ['win','osx'],
        version: 'latest',
        buildDir: './build',
        cacheDir: './cache',
        downloadUrl: 'http://dl.node-webkit.org/',
        buildType: 'default',
        forceDownload: false,
        macCredits: false,
        macIcns: false,
        macZip: false,
        macPlist: false,
        winIco: null
    };

    // Assing options
    this.options = _.defaults(options, defaults);
    this._platforms = [{
        platform: 'win',
        needsZip: true,
        runable: 'nw.exe',
        files: { // First file must be the executable
            '<=0.9.2': ['nw.exe', 'ffmpegsumo.dll', 'icudt.dll', 'libEGL.dll', 'libGLESv2.dll', 'nw.pak'],
            '>0.9.2': ['nw.exe', 'ffmpegsumo.dll', 'icudtl.dat', 'libEGL.dll', 'libGLESv2.dll', 'nw.pak']
        }
    },{
        platform: 'osx',
        runable: 'node-webkit.app/Contents/MacOS/node-webkit',
        files: {
            '*': ['node-webkit.app']
        }
    },{
        platform: 'linux32',
        needsZip: true,
        chmod: '0755',
        runable: 'nw',
        files: { // First file must be the executable
            '<=0.9.2': ['nw', 'nw.pak', 'libffmpegsumo.so'],
            '>0.9.2': ['nw', 'nw.pak', 'libffmpegsumo.so', 'icudtl.dat']
        }
    },{
        platform: 'linux64',
        needsZip: true,
        chmod: '0755', // chmod file file to be executable
        runable: 'nw',
        files: { // First file must be the executable
            '<=0.9.2': ['nw', 'nw.pak', 'libffmpegsumo.so'],
            '>0.9.2': ['nw', 'nw.pak', 'libffmpegsumo.so', 'icudtl.dat']
        }
    }];

    // Some Option checking
    if(!this.options.files) {
        throw new Error('Please specify some files');
    }

    // Check Platforms
    this._platforms.forEach(function (platform) {
        platform.active = (self.options.platforms.indexOf(platform.platform) === -1 ? false : true);
    });
    // Platforms
    this._platforms = _.where(this._platforms, {'active':true});

    if(this._platforms.length === 0 || this._platforms.length === undefined) {
        throw new Error('No platform to build!');
    }

    return this;
};

NwBuilder.prototype.build = function (callback) {
    var hasCallback = (typeof callback === 'function'),
        done = Promise.defer();

    // Let's create a node Webkit app
    this.checkFiles().bind(this)
        .then(this.resolveLatestVersion)
        .then(this.checkVersion)
        .then(this.platformFilesForVersion)
        .then(this.downloadNodeWebkit)
        .then(this.createReleaseFolder)
        .then(this.copyNodeWebkit)
        .then(this.zipAppFiles)
        .then(this.mergeAppFiles)
        .then(this.handleMacApp)
        .then(this.handleWinApp)
        .then(function (info) {
            if(hasCallback) {
                callback(false, info);
            } else {
                done.resolve(info);
            }
        })
        .catch(function (error) {
            if(hasCallback) {
                callback(error);
            } else {
                done.reject(error);
            }
        });

    return hasCallback ? true : done.promise;
};

NwBuilder.prototype.run = function (callback) {
    var hasCallback = (typeof callback === 'function'),
        done = Promise.defer();

    // Let's run this node Webkit app
    this.checkFiles().bind(this)
        .then(this.resolveLatestVersion)
        .then(this.checkVersion)
        .then(this.platformFilesForVersion)
        .then(this.downloadNodeWebkit)
        .then(this.runApp)
        .then(function (info) {
            if(hasCallback) {
                callback(false, info);
            } else {
                done.resolve(info);
            }
        })
        .catch(function (error) {
            if(hasCallback) {
                callback(true, error);
            } else {
                done.reject(error);
            }
        });

    return hasCallback ? true : done.promise;
};

NwBuilder.prototype.checkFiles = function () {
    var self = this;

    return Utils.getFileList(this.options.files).then(function (data) {

        self._appPkg = data.json;
        self._files = data.files;

        if(!self.options.appName || self.options.appVersion) {
            return Utils.getPackageInfo(self._appPkg).then(function (appPkg) {
               self._appPkg = appPkg;
               self.options.appName = (self.options.appName ? self.options.appName : appPkg.name);
               self.options.appVersion = (self.options.appVersion ? self.options.appVersion : appPkg.version);
            });
        }
    });

};

NwBuilder.prototype.resolveLatestVersion = function () {
    var self = this;

    if(self.options.version !== 'latest') return Promise.resolve();

    return NwVersions.getLatestVersion(self.options.downloadUrl).then(function(latestVersion){
        self.emit('log', 'Latest Version: v' + latestVersion);
        self.options.version = latestVersion;
    });
};

NwBuilder.prototype.checkVersion = function () {
    var version = this.options.version.replace('v', '');

    if(!semver.valid(this.options.version)){
        return Promise.reject('The version ' + this.options.version + ' is not valid.');
    } else {
        this._version = NwVersions.getVersionNames( version );
        this.emit('log', 'Using v' + this._version.version);
    }

    return Promise.resolve();
};

NwBuilder.prototype.platformFilesForVersion = function () {
    var self = this;

    this._platforms.forEach(function (single_platform) {
        var satisfied = !Object.keys(single_platform.files).every(function(range) {
            if (semver.satisfies(self._version.version, range)) {
                single_platform.files = single_platform.files[range];
                return false;
            }
            return true;
        });

        if (!satisfied) {
            throw new Error("Unsupported node-webkit version '" + this._version.version + "' for platform '" + platform.type + "'");
        }
    });

    return true;
};

NwBuilder.prototype.downloadNodeWebkit = function () {
    var self = this,
        downloads = [];

    this._platforms.map(function (single_platform) {
        single_platform.cache = path.resolve(self.options.cacheDir, self._version.version, single_platform.platform);
        single_platform.url = url.resolve(self.options.downloadUrl, self._version.platforms[single_platform.platform]);

        // Ensure that there is a cache folder
        if(self.options.forceDownload) {
            fs.removeSync(single_platform.cache);
        }

        fs.mkdirpSync(single_platform.cache);
        self.emit('log', 'Create cache folder in ' + path.resolve(self.options.cacheDir, self._version.version));

        if(!Downloader.checkCache(single_platform.cache, single_platform.files)) {
            downloads.push(
                Downloader.downloadAndUnpack(single_platform.cache, single_platform.url)
                    .catch(function(err){
                        if(err.statusCode === 404){
                            self.emit('log', 'ERROR: The version '+self._version.version+' does not have a corresponding build posted at http://dl.node-webkit.org/. Please choose a version from that list.')
                        } else {
                            self.emit('log', err.msg)
                        }

                        return Promise.reject('Unable to download nodewebkit.');
                    })
            );
            self.emit('log', 'Downloading: ' + single_platform.url);
        } else {
            self.emit('log', 'Using cache for: ' + single_platform.platform);
        }

        return single_platform;
    });

    return Promise.all(downloads)
        .then(function(data) {
            Downloader.clearProgressbar();
            return data;
        });
};

NwBuilder.prototype.buildGypModules = function () {
    // @todo
    // If we trigger a rebuild we have to copy
    // the node_modules to a tmp location because
    // we don't want to change the source files

};

NwBuilder.prototype.createReleaseFolder = function () {
    var self = this,
        releasePath;

    if (_.isFunction(self.options.buildType)) {
      releasePath = self.options.buildType.call(self.options);
    } else {
      // buildTypes
      switch(self.options.buildType) {
          case 'timestamped':
              releasePath = self.options.appName + ' - ' + Math.round(Date.now() / 1000).toString();
          break;

          case 'versioned':
              releasePath = self.options.appName + ' - v' + self.options.appVersion;
          break;

          default:
              releasePath = self.options.appName;
      }
    }

    this._platforms.forEach(function (single_platform) {
        single_platform.releasePath = path.resolve(self.options.buildDir, releasePath, single_platform.platform);

        // Ensure that there is a release Folder, delete and create it.
        fs.removeSync(single_platform.releasePath);
        fs.mkdirpSync(single_platform.releasePath);
        self.emit('log', 'Create release folder in ' + single_platform.releasePath);
    });

    return true;

};

NwBuilder.prototype.copyNodeWebkit = function () {
    var self = this,
        copiedFiles = [];

    this._platforms.forEach(function (single_platform) {
        var executable = single_platform.runable.split('/')[0];
        single_platform.files.forEach(function (file, i) {
            var destFile = file;
            if(i===0) {
                // rename executable to app name
                destFile = self.options.appName + path.extname(file);
                // save new filename back to files list
                single_platform.files[0] = destFile;
            }
            copiedFiles.push(Utils.copyFile(path.resolve(single_platform.cache, file), path.resolve(single_platform.releasePath, destFile)));
        });
    });

    return Promise.all(copiedFiles);
};

NwBuilder.prototype.zipAppFiles = function () {
    var self = this;

    // Check if zip is needed
    this._needsZip = (self.options.macZip || _.any(this._platforms, {'needsZip':true}));

    return new Promise(function(resolve, reject) {
        if(self._needsZip) {
            Utils.generateZipFile(self._files, self).then(function (nwFile) {
                self._nwFile = nwFile;
                resolve();
            }, reject);
        } else {
            self._nwFile = null;
            resolve();
        }
    });
};

NwBuilder.prototype.mergeAppFiles = function () {
    var self = this,
        copiedFiles = [];

    this._platforms.forEach(function (single_platform) {
        // We copy the app files if we are on mac and don't force zip
        if(single_platform.platform === 'osx') {
            // no zip, copy the files
            if(!self.options.macZip) {
                self._files.forEach(function (file) {
                    var dest = path.resolve(single_platform.releasePath, self.options.appName+'.app', 'Contents', 'Resources', 'app.nw', file.dest);
                    copiedFiles.push(Utils.copyFile(file.src, dest));
                });
            } else {
                // zip just copy the app.nw
                copiedFiles.push(Utils.copyFile(self._nwFile, path.resolve(single_platform.releasePath, self.options.appName+'.app', 'Contents', 'Resources', 'nw.icns')));
            }
        } else {
            // We cat the app.nw file into the .exe / nw
            copiedFiles.push(Utils.mergeFiles(path.resolve(single_platform.releasePath, _.first(single_platform.files)), self._nwFile), single_platform.chmod);
        }
    });

    return Promise.all(copiedFiles);
};

NwBuilder.prototype.handleMacApp = function () {
    var self = this, allDone = [];
    var macPlatform = _.findWhere(self._platforms, {'platform':'osx'});
    if(!macPlatform) return Promise.resolve();

    // Let's first handle the mac icon
    if(self.options.macIcns) {
        allDone.push(Utils.copyFile(self.options.macIcns, path.resolve(macPlatform.releasePath, self.options.appName+'.app', 'Contents', 'Resources', 'nw.icns')));
    }

    // Handle mac credits
    if(self.options.macCredits) {
        allDone.push(Utils.copyFile(self.options.macCredits, path.resolve(macPlatform.releasePath, self.options.appName+'.app', 'Contents', 'Resources', 'Credits.html')));
    }

    // Let handle the Plist
    var PlistPath = path.resolve(macPlatform.releasePath, self.options.appName+'.app', 'Contents', 'Info.plist');

    // If the macPlist is a string we just copy the file
    if(typeof self.options.macPlist === 'String') {
        allDone.push(Utils.copyFile(self.options.macPlist, PlistPath));
    } else {
        // Setup the Plst
        var defaultPlist = {
            appName: self.options.appName,
            appVersion: self.options.appVersion,
            copyright: self._appPkg.copyright || false
        };

        var plistOptions = (self.options.macPlist ? _.defaults(self.options.macPlist, defaultPlist) : defaultPlist);
        allDone.push(Utils.editPlist(PlistPath, PlistPath, plistOptions));
    }

    return Promise.all(allDone);

};

NwBuilder.prototype.handleWinApp = function () {
    var self = this,
        done = Promise.defer();
    var winPlatform = _.findWhere(self._platforms, {'platform':'win'});
    if(!winPlatform || !self.options.winIco) return Promise.resolve();

    // Set icon
    if (self.options.winIco) {
        self.emit('log', 'Update executable icon');
        winresourcer({
            operation: "Update",
            exeFile: path.resolve(winPlatform.releasePath, _.first(winPlatform.files)),
            resourceType: "Icongroup",
            resourceName: "IDR_MAINFRAME",
            lang: 1033, // Required, except when updating or deleting
            resourceFile: path.resolve(self.options.winIco)
        }, function(err) {
            if(err) {
                done.reject('Error while updating the Windows icon.' +
                    (process.platform !== "win32" ? ' Wine (winehq.org) must be installed to add custom icons from Mac and Linux.' : '')
                );
            }
            else {
                done.resolve();
            }
        });
    }

    return done.promise;
};

NwBuilder.prototype.runApp = function () {
    var self = this,
        platform = this._platforms[0],
        executable = path.resolve(platform.cache, platform.runable);

        self.emit('log', 'Launching App');
        return new Promise(function(resolve, reject) {
            var p = spawn(executable, ['--enable-logging', self.options.files.replace(/\*[\/\*]*/,"")]);

            p.stdout.on('data', function(data) {
                self.emit('stdout', data);
            });

            p.stderr.on('data', function(data) {
                self.emit('stderr', data);
            });

            p.on('close', function(code) {
                self.emit('log', 'App exited with code ' + code);
                resolve();
            });
        });
};
<|endoftext|>


<commit_before>const gateway = require('gateway');
var paypal = require('paypal-sdk');
module.exports = function (opts) {
	if( typeof opts != 'object' || !opts.client_id || !opts.client_secret )
		throw new Error('The configuration is dont exist');

	paypal.configure({
		'mode': opts.mode || 'sandbox', //sandbox or live
		'client_id': opts.client_id,
		'client_secret': opts.client_secret
	});

	var payment = new Gateway.Strategy('paypal-web', 0.054, 0.33, opts.url, opts);

	payment.add('create', function (options, callback) {
		var paypalPayment = {
			"intent": "sale",
			"payer": {
				"payment_method": "paypal"
			},
			"redirect_urls": {},
			"transactions": [{
				"amount": {
						"currency": opts.currency || 'USD'
					}
				}
			]
		};

		var data = {
			method : opts.showMethod || opts.showMethod,
			id : opts.id
		};

		paypalPayment.redirect_urls.return_url = options.return_url || payment.url('return', data );
		paypalPayment.redirect_urls.cancel_url = options.cancel_url || payment.url('cancel', data );

		if( options.items ){
			for (var i = options.items.length - 1; i >= 0; i--) {
				paypalPayment.transactions[i].currency = options.items[i].currency;
				paypalPayment.transactions[i].amount.total = options.items[i].amount;
				paypalPayment.transactions[i].description = options.items[i].description;
				paypalPayment.transactions[i].title = options.items[i].title;
			};
		} else {
			if( options.items[i].currency )
				paypalPayment.transactions[0].currency = options.items[i].currency;
			paypalPayment.transactions[0].amount.total = options.items[i].amount;
			paypalPayment.transactions[0].description = options.items[i].description;
			paypalPayment.transactions[0].title = options.items[i].title;
		}

		paypal.payment.create(paypalPayment, {}, function (err, resp) {
			if(err) return callback(err);
			var link = resp.links;
			for (var i = 0; i < link.length; i++) {
				if (link[i].rel === 'approval_url') {
					res.redirect(link[i].href);
				}
			}
		});
	});

	payment.add('payment', function (req, data, options, cb) {
		var payer = { payer_id : req.query.PayerID };
		paypal.payment.execute(order.payment_id, payer, {}, function (err, resp) {
			if(err) return cb(err);
			cb(err, resp);
		});
	});

	return payment;
};<commit_msg>Ok all<commit_after>const gateway = require('gateway');
var paypal = require('paypal-sdk');
module.exports = function (opts) {
	if( typeof opts != 'object' || !opts.client_id || !opts.client_secret )
		throw new Error('The configuration is dont exist');

	paypal.configure({
		'mode': opts.mode || 'sandbox', //sandbox or live
		'client_id': opts.client_id,
		'client_secret': opts.client_secret
	});

	var payment = new Gateway.Strategy('paypal-web', opts.porcent || 0.054, opts.more 0.33, opts.url, opts);

	payment.add('create', function (options, callback) {
		var paymentData = payment.data();
		var paypalPayment = {
			"intent": "sale",
			"payer": {
				"payment_method": "paypal"
			},
			"redirect_urls": {},
			"transactions": [{
				"amount": {
						"currency": opts.currency || 'USD'
					}
				}
			]
		};

		var data = {
			method : opts.showMethod || options.showMethod,
			id : options.id
		};

		paypalPayment.redirect_urls.return_url = options.return_url || payment.url('return', data );
		paypalPayment.redirect_urls.cancel_url = options.cancel_url || payment.url('cancel', data );

		if( options.items ){
			for (var i = options.items.length - 1; i >= 0; i--) {
				paypalPayment.transactions[i].currency = options.items[i].currency;
				paypalPayment.transactions[i].amount.total = options.items[i].amount;
				if( options.add )
					paypalPayment.transactions[i].amount.total = ( options.items[i].amount * paymentData.aditional ) + options.items[i].amount;
				paypalPayment.transactions[i].description = options.items[i].description;
				paypalPayment.transactions[i].title = options.items[i].title;
			};
		} else {
			paypalPayment.transactions[0].amount.total = options.items[i].amount;
				if( options.add )
					paypalPayment.transactions[0].amount.total = ( options.items[i].amount * paymentData.aditional ) + options.items[i].amount;
			if( options.items[i].currency )
				paypalPayment.transactions[0].currency = options.items[i].currency;
			paypalPayment.transactions[0].description = options.items[i].description;
			paypalPayment.transactions[0].title = options.items[i].title;
		}

		paypal.payment.create(paypalPayment, function (err, resp) {
			if(err) return callback(err);
			var link = resp.links;
			for (var i = 0; i < link.length; i++) {
				if (link[i].rel === 'approval_url') {
					res.redirect(link[i].href);
				}
			}
		});
	});

	payment.add('payment', function (req, params, data, cb) {
		var payer = {
			payer_id : ''
		};

		if( req.query[ params.id ] )
			payer.payer_id = req.query[ params.id ];

		if( req.params[ params.id ] )
			payer.payer_id = req.params[ params.id ];

		paypal.payment.execute(data, payer, function (err, doc) {
			if(err) return cb(err);
			// TODO
		});
	});

	return payment;
};<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.6.3
(function() {
  var BaseModel, Issues, _ref,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  BaseModel = require('./BaseModel');

  Issues = (function(_super) {
    __extends(Issues, _super);

    function Issues() {
      this.all = __bind(this.all, this);
      _ref = Issues.__super__.constructor.apply(this, arguments);
      return _ref;
    }

    Issues.prototype.all = function(params, fn) {
      if (params == null) {
        params = {};
      }
      if (fn == null) {
        fn = null;
      }
      if ('function' === typeof params) {
        fn = params;
        params = {};
      }
      this.debug("Issues::all()");
      if (params.page == null) {
        params.page = 1;
      }
      if (params.per_page == null) {
        params.per_page = 100;
      }
      return (function() {
        var cb, data,
          _this = this;
        data = [];
        cb = function(retData) {
          if (retData.length === 100) {
            _this.debug("Recurse Issues::all()");
            data = data.concat(retData);
            params.page++;
            return _this.all(params, cb);
          } else {
            data = data.concat(retData);
            if (fn) {
              return fn(data);
            }
          }
        };
        return this.get("issues", params, cb);
      }).bind(this)();
    };

    return Issues;

  })(BaseModel);

  module.exports = function(client) {
    return new Issues(client);
  };

}).call(this);
<commit_msg>added show and create methods for Issues<commit_after>// Generated by CoffeeScript 1.6.3
(function() {
  var BaseModel, Issues, _ref,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  BaseModel = require('./BaseModel');

  Issues = (function(_super) {
    __extends(Issues, _super);

    function Issues() {
      this.create = __bind(this.create, this);
      this.show = __bind(this.show, this);
      this.all = __bind(this.all, this);
      _ref = Issues.__super__.constructor.apply(this, arguments);
      return _ref;
    }

    Issues.prototype.all = function(params, fn) {
      if (params == null) {
        params = {};
      }
      if (fn == null) {
        fn = null;
      }
      if ('function' === typeof params) {
        fn = params;
        params = {};
      }
      this.debug("Issues::all()");
      if (params.page == null) {
        params.page = 1;
      }
      if (params.per_page == null) {
        params.per_page = 100;
      }
      return (function() {
        var cb, data,
          _this = this;
        data = [];
        cb = function(retData) {
          if (retData.length === 100) {
            _this.debug("Recurse Issues::all()");
            data = data.concat(retData);
            params.page++;
            return _this.all(params, cb);
          } else {
            data = data.concat(retData);
            if (fn) {
              return fn(data);
            }
          }
        };
        return this.get("issues", params, cb);
      }).bind(this)();
    };

    Issues.prototype.show = function(projectId, fn) {
      var _this = this;
      if (fn == null) {
        fn = null;
      }
      this.debug("Issues::show()");
      if (projectId.indexOf("/") !== -1) {
        projectId = encodeURIComponent(projectId);
      } else {
        projectId = parseInt(projectId);
      }
      return this.get("issues/" + projectId, function(data) {
        if (fn) {
          return fn(data);
        }
      });
    };

    Issues.prototype.create = function(params, fn) {
      if (params == null) {
        params = {};
      }
      if (fn == null) {
        fn = null;
      }
      this.debug("Issues::create()");
      return this.post("issues", params, function(data) {
        if (fn) {
          return fn(data);
        }
      });
    };

    return Issues;

  })(BaseModel);

  module.exports = function(client) {
    return new Issues(client);
  };

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


<commit_before>const $ = require('jquery');
require('./board');

const Board = require('./board');

$(document).ready( function () {

  var shapes = ['triangle.png', 'triangle.png', 'circle.png', 'circle.png', 'star.png', 'star.png', 'square.png', 'square.png'];

  var letters = ['a.png', 'a.png', 'b.png', 'b.png', 'c.png', 'c.png', 'd.png', 'd.png'];

  var mystery = ['horace.png', 'horace.png', 'mike.png', 'mike.png', 'jeff.png', 'jeff.png', 'andrew.png', 'andrew.png'];

  var sesame = ['elmo.jpg', 'elmo.jpg', 'berternie.jpg', 'berternie.jpg', 'cookie.jpg', 'cookie.jpg', 'bigbird.jpg', 'bigbird.jpg'];

  var colors = ['red.jpg', 'red.jpg', 'blue.jpg', 'blue.jpg', 'green.jpg', 'green.jpg', 'yellow.jpg', 'yellow.jpg'];

  var shapesDeck = document.getElementById('shapes');
  shapesDeck.addEventListener('click', function() {
    var board = new Board(shapes);
    board.render();
    board.bindCardListeners();
    $("button.deck" ).remove();
  });

  var mysteryDeck = document.getElementById('mystery');
  mysteryDeck.addEventListener('click', function() {
    var board = new Board(mystery);
    board.render();
    board.bindCardListeners();
    $("button.deck" ).remove();
  });

  var sesameDeck = document.getElementById('sesame');
  sesameDeck.addEventListener('click', function() {
    var board = new Board(sesame);
    board.render();
    board.bindCardListeners();
    $("button.deck" ).remove();
  });

  var lettersDeck = document.getElementById('letters');
  lettersDeck.addEventListener('click', function() {
    var board = new Board(letters);
    board.render();
    board.bindCardListeners();
    $("button.deck" ).remove();
  });

  var colorsDeck = document.getElementById('colors');
  colorsDeck.addEventListener('click', function() {
    var board = new Board(colors);
    board.render();
    board.bindCardListeners();
    $("button.deck" ).remove();
  });

  var quit = document.getElementById('quit');
  quit.addEventListener('click', function() {
    location.reload();
  });

});
<commit_msg>Vastly refactored index.js. Made selecting deck function dynamic<commit_after>const $ = require('jquery');
require('./board');

const Board = require('./board');

$(document).ready( function () {

  var tileSets = {
    shapes: ['triangle.png', 'triangle.png', 'circle.png', 'circle.png', 'star.png', 'star.png', 'square.png', 'square.png'],
    letters: ['a.png', 'a.png', 'b.png', 'b.png', 'c.png', 'c.png', 'd.png', 'd.png'],
    mystery: ['horace.png', 'horace.png', 'mike.png', 'mike.png', 'jeff.png', 'jeff.png', 'andrew.png', 'andrew.png'],
    sesame: ['elmo.jpg', 'elmo.jpg', 'berternie.jpg', 'berternie.jpg', 'cookie.jpg', 'cookie.jpg', 'bigbird.jpg', 'bigbird.jpg'],
    colors: ['red.jpg', 'red.jpg', 'blue.jpg', 'blue.jpg', 'green.jpg', 'green.jpg', 'yellow.jpg', 'yellow.jpg']
  };

  for (var tileSet in tileSets) {
    createNewGameListener(tileSet, tileSets[tileSet]);
  }

  function createNewGameListener(setName, tiles) {
  	var el = document.getElementById(setName);
  	el.addEventListener('click', function() {
 	    var board = new Board(tiles);
      board.render();
      board.bindCardListeners();
      $("button.deck" ).remove();
    });
  }

  var quit = document.getElementById('quit');
  quit.addEventListener('click', function() {
    location.reload();
  });

});
<|endoftext|>


<commit_before>
"use strict";require("earlgrey-runtime/5");var q$0 = undefined;var $targ$0 = undefined;q$0 = require("quaint");$targ$0 = function () {
  var t0$0 = undefined;var fn$0 = undefined;var $targ$1 = undefined;var $it$0 = undefined;var self$0 = undefined;$targ$1 = this;t0$0 = $targ$1;$it$0 = t0$0;self$0 = t0$0;[$it$0, self$0];fn$0 = function fn() {
    var format$0 = undefined;var format$1 = undefined;var rval$0 = undefined;var src$0 = undefined;var opts$0 = undefined;var t0$1 = undefined;var m$0$0 = undefined;m$0$0 = arguments;t0$1 = m$0$0.length;if (t0$1 >= 1 && t0$1 <= 2) {
      src$0 = m$0$0[0];if (1 >= t0$1) {
        opts$0 = {};
      } else {
        opts$0 = m$0$0[1];
      }if (opts$0.format === null) {
        $it$0.log("Quaint: Defaulting to HTML");format$0 = "html";format$0;
      } else {
        format$1 = opts$0.format;format$1;
      }delete opts$0.format;rval$0 = false;try {
        rval$0 = q$0.create().translate(src$0, format$1, opts$0);rval$0;
      } catch (excv$0) {
        var e$0 = undefined;e$0 = excv$0;throw e$0;rval$0;
      }return rval$0;
    } else {
      return ___match_error(m$0$0);
    }
  };return $it$0.filter("quaint", fn$0, { extension: ".q" });
};module.exports = $targ$0;void 0;<commit_msg>Build :package:<commit_after>
"use strict";require("earlgrey-runtime/5");var q$0 = undefined;var $targ$0 = undefined;q$0 = require("quaint");$targ$0 = function () {
  var t0$0 = undefined;var fn$0 = undefined;var $targ$1 = undefined;var $it$0 = undefined;var self$0 = undefined;$targ$1 = this;t0$0 = $targ$1;$it$0 = t0$0;self$0 = t0$0;[$it$0, self$0];fn$0 = function fn(src$0, opts$0) {
    var format$0 = undefined;var format$1 = undefined;var rval$0 = undefined;if (!opts$0) {
      opts$0 = {};opts$0;
    }if (opts$0.format === null) {
      $it$0.log("Quaint: Defaulting to HTML");format$0 = "html";format$0;
    } else {
      format$1 = opts$0.format;format$1;
    }delete opts$0.format;rval$0 = false;try {
      rval$0 = q$0.create().translate(src$0, format$1, opts$0);rval$0;
    } catch (excv$0) {
      var e$0 = undefined;e$0 = excv$0;throw e$0;rval$0;
    }return rval$0;
  };return $it$0.filter("quaint", fn$0, { extension: ".q" });
};module.exports = $targ$0;void 0;<|endoftext|>


<commit_before>console.log("ljswitchboard-kipling index.js");

var gui = require('nw.gui');
var path = require('path');
var q = require('q');
var win = gui.Window.get();

var package_loader = require('ljswitchboard-package_loader');
var gns = package_loader.getNameSpace();
var window_manager = require('ljswitchboard-window_manager');
var GLOBAL_SUBPROCESS_REFERENCE = undefined;
var GLOBAL_ALLOW_SUBPROCESS_TO_RESTART = true;

var K3_ON_APPLICATION_EXIT_LISTENER = function() {
	GLOBAL_ALLOW_SUBPROCESS_TO_RESTART = false;

	io_interface.off(io_interface.eventList.PROCESS_CLOSE);
	// console.log(JSON.stringify(['Quitting Application', GLOBAL_ALLOW_SUBPROCESS_TO_RESTART, GLOBAL_SUBPROCESS_REFERENCE]));
	try {
		if(GLOBAL_SUBPROCESS_REFERENCE) {
			GLOBAL_SUBPROCESS_REFERENCE.kill('SIGHUP');
		}
	} catch(err) {
		console.log('Error quitting subprocess', err);
	}
	console.log('Quit sub-process');
};
window_manager.on(
	window_manager.eventList.QUITTING_APPLICATION,
	K3_ON_APPLICATION_EXIT_LISTENER
);

// Prevent application from auto-closing so that we can have an asynchronous hook
// aka close app manually.
window_manager.windowManager.managedWindows.kipling.runInBackground = true;

/*
SCRATCH PAD:
// Prevent app from closing
window_manager.windowManager.managedWindows.kipling.runInBackground = true;

// quit app.
window_manager.windowManager.managedWindows.kipling.win.close(true)
*/
var K3_EXIT_LISTENERS = {};
function ADD_K3_EXIT_LISTENER(name, func) {
	K3_EXIT_LISTENERS[name] = func;
}
function DELETE_K3_EXIT_LISTENER(name) {
	delete(K3_EXIT_LISTENERS[name]);
}
function GET_ALL_K3_EXIT_LISTENERS() {
	var listeners = [];
	var keys = Object.keys(K3_EXIT_LISTENERS);
	keys.forEach(function(key) {
		listeners.push(K3_EXIT_LISTENERS[key]);
	});
	return listeners;
}
function K3_ON_APPLICATION_EXIT_WINDOW_LISTENER() {

	var asyncProcesses = GET_ALL_K3_EXIT_LISTENERS();
	async.eachSeries(
		asyncProcesses,
		function closeAppAsyncProcess(process, cb) {
			try {
				process().then(function(res) {
					cb();
				}, function(err) {
					cb();
				}).catch(function(err) {
					cb();
				});
			} catch(err) {
				// Error...
				cb();
			}
		},
		function finishedClosingAsyncProcesses(err) {
			// Close app.
			// K3_ON_APPLICATION_EXIT_LISTENER();
			// window_manager.windowManager.managedWindows.kipling.win.close(true);
			closeApp();
		});

	function closeApp() {
		var interval;
		var numWaited = 0;
		var numToWait = 2;
		function waitToClose() {
			if(numWaited < numToWait) {
				numWaited += 1;
				console.log('Waiting to close.....', numWaited);
			} else {
				// Close app.
				try {
					K3_ON_APPLICATION_EXIT_LISTENER();
				} catch(err) {
					console.error('Error exiting things...', err);
				}
				window_manager.windowManager.managedWindows.kipling.win.close(true);
			}
		}
		interval = setInterval(waitToClose, 1000);
	}
}
window_manager.on(
	window_manager.eventList.PREVENTING_WINDOW_FROM_CLOSING,
	K3_ON_APPLICATION_EXIT_WINDOW_LISTENER
);
var startDir = global[gns].info.startDir;

/*
	Function called to load the application's core resources.
	The resources are loaded from the ljswitchboard-static_files/static
	directory.
*/
var coreResourcesLoaded = false;
var loadCoreResources = function(resources) {
	global[gns].static_files.loadResources(document, resources)
	.then(function(res) {
		coreResourcesLoaded = true;
	}, function(err) {
		console.error('Error Loading resources', err);
	});
};

/*
	Function called to load the application's local resources.
	The resources are loaded starting from the directory of the
	index.html/index.js file aka the cwd of the window.
*/
var localResourcesLoaded = false;
var loadLocalResources = function(resources) {
	global[gns].static_files.loadResources(document, resources, true)
	.then(function(res) {
		localResourcesLoaded = true;
	}, function(err) {
		console.error('Error Loading resources', err);
	});
};

var loadResources = function(resources, isLocal) {
	var defered = q.defer();
	global[gns].static_files.loadResources(document, resources, isLocal)
	.then(function(res) {
		defered.resolve();
	}, function(err) {
		console.error('Error Loading resources', err);
		defered.reject(err);
	});
	return defered.promise;
};

var saveGlobalSubprocessReference = function(bundle) {
	var defered = q.defer();
	GLOBAL_SUBPROCESS_REFERENCE = io_manager.io_interface().mp.masterProcess.getSubprocess();
	// console.log('subprocess pid', GLOBAL_SUBPROCESS_REFERENCE.pid);
	defered.resolve(bundle);
	return defered.promise;
};

var ioManagerMonitor = function(data) {
	if(GLOBAL_ALLOW_SUBPROCESS_TO_RESTART) {
		console.log('io_manager Close Event detected, restarting', data);
		var errorString = '
';
		errorString += 'Kipling\'s sub-process was closed or has crashed and ';
		errorString += 'is being restarted.';
		errorString += '
';
		errorString += '
';
		errorString += 'Current time is: ' + (new Date()).toString();
		errorString += '
';

		showCriticalAlert(errorString);
		console.log('Critical alert errorString', errorString);
		if(MODULE_LOADER) {
			MODULE_LOADER.loadModuleByName('crash_module');
		}
		global[gns].ljm.io_interface.initialize()
		.then(saveGlobalSubprocessReference)
		.then(MODULE_CHROME.reloadModuleChrome);
	} else {
		console.log('subprocess exited and not restarting');
	}
};

// Add monitors to the other error events.
// io_interface.on(io_interface.eventList.PROCESS_ERROR, getIOManagerListener('PROCESS_ERROR'));
// io_interface.on(io_interface.eventList.PROCESS_EXIT, getIOManagerListener('PROCESS_EXIT'));
// io_interface.on(io_interface.eventList.PROCESS_DISCONNECT, getIOManagerListener('PROCESS_DISCONNECT'));

function getIOManagerListener(eventName) {
	return function ioInterfaceProcessMonitor(data) {
		console.log('Recieved event from io_interface:', eventName, data, (new Date()).toString());
	};
}

var startIOManager = function(){
	var defered = q.defer();
	var io_interface = global[gns].io_manager.io_interface();
	global[gns].ljm = {};
	global[gns].ljm.io_interface = io_interface;

	var reportIOInitializationError = function(data) {
		console.error('io_interface.initialize error:', data);

		var remainingMessage = '';

		if(data.code === 'EPERM') {
			remainingMessage += ', Permissions';
		} else {
			console.log(typeof(data.code), data.code);
			remainingMessage += ', Subprocess Failed';
		}
		global[gns].splash_screen.update('Failed to initialize IO Manager' + remainingMessage);
	};
	// Attach monitor
	GLOBAL_ALLOW_SUBPROCESS_TO_RESTART = true;
	io_interface.on(io_interface.eventList.PROCESS_CLOSE, ioManagerMonitor);

	// Add monitors to the other error events.
	io_interface.on(io_interface.eventList.PROCESS_ERROR, getIOManagerListener('PROCESS_ERROR'));
	io_interface.on(io_interface.eventList.PROCESS_EXIT, getIOManagerListener('PROCESS_EXIT'));
	io_interface.on(io_interface.eventList.PROCESS_DISCONNECT, getIOManagerListener('PROCESS_DISCONNECT'));

	io_interface.initialize()
	.then(saveGlobalSubprocessReference,reportIOInitializationError)
	.then(defered.resolve, defered.reject);
	return defered.promise;
};

var performRemainingInitializationRoutines = function() {
	var defered = q.defer();

	var managers = {
		'keyboard': KEYBOARD_EVENT_HANDLER,
		'mouse': MOUSE_EVENT_HANDLER,
		'zoom': WINDOW_ZOOM_MANAGER,
	};

	function finalize() {
		defered.resolve();
	}

	KEYBOARD_EVENT_HANDLER.init(managers)
	.then(WINDOW_ZOOM_MANAGER.init)
	.then(MOUSE_EVENT_HANDLER.init)
	.then(finalize, defered.reject);

	return defered.promise;
};

var showKiplingWindow = function() {
	var defered = q.defer();
	global[gns].splash_screen.update('Finished');
	global[gns].window_manager.hideWindow('core');
	// global[gns].window_manager.showWindow('core');
	global[gns].window_manager.hideWindow('main');
	global[gns].window_manager.showWindow('kipling');

	// Try and execute tests
	var isKiplingTester = false;
	var windows = global[gns].window_manager.getWindows();
	windows.forEach(function(win) {
		if(win === 'kipling_tester') {
			isKiplingTester = true;
		}
	});
	if(isKiplingTester) {
		global[gns].window_manager.showWindow('kipling_tester');
		var testerWin = global[gns].window_manager.windowManager.managedWindows.kipling_tester;
		testerWin = testerWin.win;
		testerWin.focus();
		var testerWindow = testerWin.window;
		testerWindow.runTests();
	}
	defered.resolve();
	return defered.promise;
};

var getHandleError = function(msg) {
	var handleError = function(err) {
		var reportError = true;
		if(err) {
			if(err.loadError) {
				reportError = false;
			}
		}

		if(reportError) {
			var defered = q.defer();
			console.error('Error on step', msg);
			defered.reject({
				'loadError': true,
				'message': 'Error on step: ' + msg.toString(),
				'errorInfo': err,
			});
		} else {
			defered.reject(reportError);
		}
		return defered.promise;
	};
	return handleError;
};
var numLoadDelay = 0;
var startCoreApp = function() {
	if(coreResourcesLoaded && localResourcesLoaded) {
		// win.showDevTools();
		// Start the application
		global[gns].splash_screen.update('Starting IO Manager');

		// Start the  IO Manager
		startIOManager()

		// Perform other initialization routines
		.then(performRemainingInitializationRoutines, getHandleError('startIOManager'))

		// Render the module chrome window
		.then(MODULE_CHROME.loadModuleChrome, getHandleError('performRemainingInitializationRoutines'))

		// Initialize the file browser utility
		.then(FILE_BROWSER.initialize, getHandleError('MODULE_CHROME.loadModuleChrome'))

		// Hide the splash screen & core windows & display the kipling window
		.then(showKiplingWindow, getHandleError('FILE_BROWSER.initialize'))

		// Load Kipling background tasks
		.then(TASK_LOADER.loadTasks, getHandleError('showKiplingWindow'))

		// Report remaining errors
		.then(function(){}, getHandleError('TASK_LOADER.loadTasks'));

	} else {
		numLoadDelay += 1;
		if(numLoadDelay > 10) {
			if(numLoadDelay > 2000) {
				win.showDevTools();
			}
			console.log('numLoadDelay', numLoadDelay);
			setTimeout(startCoreApp, 100);
		} else {
			setTimeout(startCoreApp, 10);
		}
	}
};

/*
	When the window finishes loading start the core application.

	The application is started in a timeout-loop because some of the resources
	are asynchronously loaded upon start.  The application attempts to start
	every 10ms until those resources are loaded.
*/
window.onload = function(e) {
	setTimeout(startCoreApp, 10);
};

// gui.App.sharedData.appWindows.core.show();
// gui.App.sharedData.appWindows.core.showDevTools();<commit_msg>Decreased shut-down wait time.<commit_after>console.log("ljswitchboard-kipling index.js");

var gui = require('nw.gui');
var path = require('path');
var q = require('q');
var win = gui.Window.get();

var package_loader = require('ljswitchboard-package_loader');
var gns = package_loader.getNameSpace();
var window_manager = require('ljswitchboard-window_manager');
var GLOBAL_SUBPROCESS_REFERENCE = undefined;
var GLOBAL_ALLOW_SUBPROCESS_TO_RESTART = true;

var K3_ON_APPLICATION_EXIT_LISTENER = function() {
	GLOBAL_ALLOW_SUBPROCESS_TO_RESTART = false;

	io_interface.off(io_interface.eventList.PROCESS_CLOSE);
	// console.log(JSON.stringify(['Quitting Application', GLOBAL_ALLOW_SUBPROCESS_TO_RESTART, GLOBAL_SUBPROCESS_REFERENCE]));
	try {
		if(GLOBAL_SUBPROCESS_REFERENCE) {
			GLOBAL_SUBPROCESS_REFERENCE.kill('SIGHUP');
		}
	} catch(err) {
		console.log('Error quitting subprocess', err);
	}
	console.log('Quit sub-process');
};
window_manager.on(
	window_manager.eventList.QUITTING_APPLICATION,
	K3_ON_APPLICATION_EXIT_LISTENER
);

// Prevent application from auto-closing so that we can have an asynchronous hook
// aka close app manually.
window_manager.windowManager.managedWindows.kipling.runInBackground = true;

/*
SCRATCH PAD:
// Prevent app from closing
window_manager.windowManager.managedWindows.kipling.runInBackground = true;

// quit app.
window_manager.windowManager.managedWindows.kipling.win.close(true)
*/
var K3_EXIT_LISTENERS = {};
function ADD_K3_EXIT_LISTENER(name, func) {
	K3_EXIT_LISTENERS[name] = func;
}
function DELETE_K3_EXIT_LISTENER(name) {
	delete(K3_EXIT_LISTENERS[name]);
}
function GET_ALL_K3_EXIT_LISTENERS() {
	var listeners = [];
	var keys = Object.keys(K3_EXIT_LISTENERS);
	keys.forEach(function(key) {
		listeners.push(K3_EXIT_LISTENERS[key]);
	});
	return listeners;
}
function K3_ON_APPLICATION_EXIT_WINDOW_LISTENER() {

	var asyncProcesses = GET_ALL_K3_EXIT_LISTENERS();
	async.eachSeries(
		asyncProcesses,
		function closeAppAsyncProcess(process, cb) {
			try {
				process().then(function(res) {
					cb();
				}, function(err) {
					cb();
				}).catch(function(err) {
					cb();
				});
			} catch(err) {
				// Error...
				cb();
			}
		},
		function finishedClosingAsyncProcesses(err) {
			// Close app.
			// K3_ON_APPLICATION_EXIT_LISTENER();
			// window_manager.windowManager.managedWindows.kipling.win.close(true);
			closeApp();
		});

	function closeApp() {
		var interval;
		var numWaited = 0;
		var numToWait = 2;
		function waitToClose() {
			if(numWaited < numToWait) {
				numWaited += 1;
				console.log('Waiting to close.....', numWaited);
			} else {
				// Close app.
				try {
					K3_ON_APPLICATION_EXIT_LISTENER();
				} catch(err) {
					console.error('Error exiting things...', err);
				}
				window_manager.windowManager.managedWindows.kipling.win.close(true);
			}
		}
		interval = setInterval(waitToClose, 500);
	}
}
window_manager.on(
	window_manager.eventList.PREVENTING_WINDOW_FROM_CLOSING,
	K3_ON_APPLICATION_EXIT_WINDOW_LISTENER
);
var startDir = global[gns].info.startDir;

/*
	Function called to load the application's core resources.
	The resources are loaded from the ljswitchboard-static_files/static
	directory.
*/
var coreResourcesLoaded = false;
var loadCoreResources = function(resources) {
	global[gns].static_files.loadResources(document, resources)
	.then(function(res) {
		coreResourcesLoaded = true;
	}, function(err) {
		console.error('Error Loading resources', err);
	});
};

/*
	Function called to load the application's local resources.
	The resources are loaded starting from the directory of the
	index.html/index.js file aka the cwd of the window.
*/
var localResourcesLoaded = false;
var loadLocalResources = function(resources) {
	global[gns].static_files.loadResources(document, resources, true)
	.then(function(res) {
		localResourcesLoaded = true;
	}, function(err) {
		console.error('Error Loading resources', err);
	});
};

var loadResources = function(resources, isLocal) {
	var defered = q.defer();
	global[gns].static_files.loadResources(document, resources, isLocal)
	.then(function(res) {
		defered.resolve();
	}, function(err) {
		console.error('Error Loading resources', err);
		defered.reject(err);
	});
	return defered.promise;
};

var saveGlobalSubprocessReference = function(bundle) {
	var defered = q.defer();
	GLOBAL_SUBPROCESS_REFERENCE = io_manager.io_interface().mp.masterProcess.getSubprocess();
	// console.log('subprocess pid', GLOBAL_SUBPROCESS_REFERENCE.pid);
	defered.resolve(bundle);
	return defered.promise;
};

var ioManagerMonitor = function(data) {
	if(GLOBAL_ALLOW_SUBPROCESS_TO_RESTART) {
		console.log('io_manager Close Event detected, restarting', data);
		var errorString = '
';
		errorString += 'Kipling\'s sub-process was closed or has crashed and ';
		errorString += 'is being restarted.';
		errorString += '
';
		errorString += '
';
		errorString += 'Current time is: ' + (new Date()).toString();
		errorString += '
';

		showCriticalAlert(errorString);
		console.log('Critical alert errorString', errorString);
		if(MODULE_LOADER) {
			MODULE_LOADER.loadModuleByName('crash_module');
		}
		global[gns].ljm.io_interface.initialize()
		.then(saveGlobalSubprocessReference)
		.then(MODULE_CHROME.reloadModuleChrome);
	} else {
		console.log('subprocess exited and not restarting');
	}
};

// Add monitors to the other error events.
// io_interface.on(io_interface.eventList.PROCESS_ERROR, getIOManagerListener('PROCESS_ERROR'));
// io_interface.on(io_interface.eventList.PROCESS_EXIT, getIOManagerListener('PROCESS_EXIT'));
// io_interface.on(io_interface.eventList.PROCESS_DISCONNECT, getIOManagerListener('PROCESS_DISCONNECT'));

function getIOManagerListener(eventName) {
	return function ioInterfaceProcessMonitor(data) {
		console.log('Recieved event from io_interface:', eventName, data, (new Date()).toString());
	};
}

var startIOManager = function(){
	var defered = q.defer();
	var io_interface = global[gns].io_manager.io_interface();
	global[gns].ljm = {};
	global[gns].ljm.io_interface = io_interface;

	var reportIOInitializationError = function(data) {
		console.error('io_interface.initialize error:', data);

		var remainingMessage = '';

		if(data.code === 'EPERM') {
			remainingMessage += ', Permissions';
		} else {
			console.log(typeof(data.code), data.code);
			remainingMessage += ', Subprocess Failed';
		}
		global[gns].splash_screen.update('Failed to initialize IO Manager' + remainingMessage);
	};
	// Attach monitor
	GLOBAL_ALLOW_SUBPROCESS_TO_RESTART = true;
	io_interface.on(io_interface.eventList.PROCESS_CLOSE, ioManagerMonitor);

	// Add monitors to the other error events.
	io_interface.on(io_interface.eventList.PROCESS_ERROR, getIOManagerListener('PROCESS_ERROR'));
	io_interface.on(io_interface.eventList.PROCESS_EXIT, getIOManagerListener('PROCESS_EXIT'));
	io_interface.on(io_interface.eventList.PROCESS_DISCONNECT, getIOManagerListener('PROCESS_DISCONNECT'));

	io_interface.initialize()
	.then(saveGlobalSubprocessReference,reportIOInitializationError)
	.then(defered.resolve, defered.reject);
	return defered.promise;
};

var performRemainingInitializationRoutines = function() {
	var defered = q.defer();

	var managers = {
		'keyboard': KEYBOARD_EVENT_HANDLER,
		'mouse': MOUSE_EVENT_HANDLER,
		'zoom': WINDOW_ZOOM_MANAGER,
	};

	function finalize() {
		defered.resolve();
	}

	KEYBOARD_EVENT_HANDLER.init(managers)
	.then(WINDOW_ZOOM_MANAGER.init)
	.then(MOUSE_EVENT_HANDLER.init)
	.then(finalize, defered.reject);

	return defered.promise;
};

var showKiplingWindow = function() {
	var defered = q.defer();
	global[gns].splash_screen.update('Finished');
	global[gns].window_manager.hideWindow('core');
	// global[gns].window_manager.showWindow('core');
	global[gns].window_manager.hideWindow('main');
	global[gns].window_manager.showWindow('kipling');

	// Try and execute tests
	var isKiplingTester = false;
	var windows = global[gns].window_manager.getWindows();
	windows.forEach(function(win) {
		if(win === 'kipling_tester') {
			isKiplingTester = true;
		}
	});
	if(isKiplingTester) {
		global[gns].window_manager.showWindow('kipling_tester');
		var testerWin = global[gns].window_manager.windowManager.managedWindows.kipling_tester;
		testerWin = testerWin.win;
		testerWin.focus();
		var testerWindow = testerWin.window;
		testerWindow.runTests();
	}
	defered.resolve();
	return defered.promise;
};

var getHandleError = function(msg) {
	var handleError = function(err) {
		var reportError = true;
		if(err) {
			if(err.loadError) {
				reportError = false;
			}
		}

		if(reportError) {
			var defered = q.defer();
			console.error('Error on step', msg);
			defered.reject({
				'loadError': true,
				'message': 'Error on step: ' + msg.toString(),
				'errorInfo': err,
			});
		} else {
			defered.reject(reportError);
		}
		return defered.promise;
	};
	return handleError;
};
var numLoadDelay = 0;
var startCoreApp = function() {
	if(coreResourcesLoaded && localResourcesLoaded) {
		// win.showDevTools();
		// Start the application
		global[gns].splash_screen.update('Starting IO Manager');

		// Start the  IO Manager
		startIOManager()

		// Perform other initialization routines
		.then(performRemainingInitializationRoutines, getHandleError('startIOManager'))

		// Render the module chrome window
		.then(MODULE_CHROME.loadModuleChrome, getHandleError('performRemainingInitializationRoutines'))

		// Initialize the file browser utility
		.then(FILE_BROWSER.initialize, getHandleError('MODULE_CHROME.loadModuleChrome'))

		// Hide the splash screen & core windows & display the kipling window
		.then(showKiplingWindow, getHandleError('FILE_BROWSER.initialize'))

		// Load Kipling background tasks
		.then(TASK_LOADER.loadTasks, getHandleError('showKiplingWindow'))

		// Report remaining errors
		.then(function(){}, getHandleError('TASK_LOADER.loadTasks'));

	} else {
		numLoadDelay += 1;
		if(numLoadDelay > 10) {
			if(numLoadDelay > 2000) {
				win.showDevTools();
			}
			console.log('numLoadDelay', numLoadDelay);
			setTimeout(startCoreApp, 100);
		} else {
			setTimeout(startCoreApp, 10);
		}
	}
};

/*
	When the window finishes loading start the core application.

	The application is started in a timeout-loop because some of the resources
	are asynchronously loaded upon start.  The application attempts to start
	every 10ms until those resources are loaded.
*/
window.onload = function(e) {
	setTimeout(startCoreApp, 10);
};

// gui.App.sharedData.appWindows.core.show();
// gui.App.sharedData.appWindows.core.showDevTools();<|endoftext|>


<commit_before>/* global analytics */
/* eslint no-console:0, no-unused-vars:0, no-extra-parens:0 */

'use strict';

var integration = require('analytics.js-integration');
var request = require('visionmedia/superagent');
var prefix = require('johntron/superagent-prefix');
var async = require('caolan/async');
window._astq = window._astq || [];

/**
 * Expose `Astronomer` integration.
 */
var Astronomer = module.exports = exports = integration('astronomer')
  .global('_astq')
  .option('appId', null)
  .option('credentialServer', 'https://app.astronomer.io:443')
  .option('credentialsExpiration', 900)
  .option('trackAllPages', false)
  .option('trackNamedPages', true)
  .option('trackCategorizedPages', true)
  .tag('library', '<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.33.min.js">');

/**
 * Initialize astronomer.
 * @param {Facade} page The page object
 */
Astronomer.prototype.initialize = function() {
  var self = this;
  self.props = {};
  self.kinesis = null;
  self.kinesisQueue = async.queue(self.putRecord.bind(self), 1);

  console.log('Authenticating with ' + self.options.credentialServer);

  self.load('library', self.ready);

  // Load lib, auth, config, ready, dequeue
  // async.waterfall([
  //   self.loadAwsLib.bind(self),
  //   self.auth.bind(self)
  // ],
  // function(err, response) {
  //   self.configAws(response.body);
  //   self.setCredentialToken(response.body.credentials.Token);
  //   self.ready();
  //   self.dequeue();
  // });
};

Astronomer.prototype.expired = function() {
  var expireTime = (((self.kinesis || {}).config || {}).credentials || {}).expireTime;
  return ((!expireTime || expireTime.getTime() <= Date.now()) && !self.authing);
};

/**
 * Load the aws library from CDN
 * @param {Function} callback Callback
 */
// Astronomer.prototype.loadAwsLib = function(callback) {
//   this.load('library', callback);
// };

/**
 * Authenticate with our server
 * @param {Function} callback Callback
 */
Astronomer.prototype.ensureKinesisConfig = function(callback) {
  var self = this;

  if (!self.expired()) {
    return callback(self.config, self.kinesis);
  }

  // Request fresh config (token)
  self.requestCredentials(function(err, response) {
    console.log('authed', err, response);
    // Update global config object
    self.config = response.body;

    // Assign kinesis service object to new one with fresh config
    self.kinesis = new Window.AWS.Kinesis({
      region: self.config.region,
      credentials: new window.AWS.WebIdentityCredentials({
        RoleArn: self.config.roleArn,
        WebIdentityToken: self.config.credentials.Token,
        DurationSeconds: self.options.credentialsExpiration
      })
    });

    callback(self.config, self.kinesis);
  });
};

Astronomer.prototype.requestCredentials = function(callback) {
  request.get('/api/v1/applications/credentials/' + this.options.appId)
    .use(prefix(this.options.credentialServer))
    .end(callback);
};

/**
 * Assign our kinesis object with a new one configured with new credentials
 * @param {Object} config Config object from our server
 */
// Astronomer.prototype.configAws = function(config) {
//   this.config = config;
//   this.kinesis = new window.AWS.Kinesis({
//     region: this.config.region,
//     credentials: new window.AWS.WebIdentityCredentials({
//       RoleArn: this.config.roleArn,
//       DurationSeconds: this.options.credentialsExpiration
//     })
//   });
// };

/**
 * Invalidate credentials and set new token
 * @param {String} token The new token
 */
// Astronomer.prototype.setCredentialToken = function(token) {
//   this.kinesis.config.credentials.expired = true;
//   this.kinesis.config.credentials.params.WebIdentityToken = token;
// };

/**
 * Replay the queue
 */
Astronomer.prototype.dequeue = function() {
  while (window._astq.length > 0) {
    var item = window._astq.shift();
    var method = item.shift();
    if (analytics[method]) analytics[method].apply(analytics, item);
  }
};

/**
 * Has the astronomer library been loaded yet?
 * @return {Boolean}
 */
Astronomer.prototype.loaded = function() {
  return !!((((window.AWS) || {}).config || {}).credentials || {}).accessKeyId;
};

/**
 * Trigger a page view.
 * @param {Facade} page A page object
 */
Astronomer.prototype.page = function(page) {
  var category = page.category();
  var props = page.properties();
  var name = page.fullName();
  var opts = this.options;

  // all pages
  if (opts.trackAllPages) {
    this.track(page.track());
  }

  // named pages
  if (name && opts.trackNamedPages) {
    this.track(page.track(name));
  }

  // categorized pages
  // if (category && opts.trackCategorizedPages) {
  //   this.track(page.track(category));
  // }
};

/**
 * Identify a user.
 * @param {Facade} identify An identify object
 */
Astronomer.prototype.identify = function(identify) {
  var id = identify.userId();
  var traits = identify.traits();
  this.props.userId = id;
  this.props.userProperties = traits;
};

/**
 * Associate the current user with a group of users.
 * @param {Facade} group A group object
 */
Astronomer.prototype.group = function(group) {
  var id = group.groupId();
  var traits = group.traits();
  this.props.groupId = id;
  this.props.groupProperties = traits;
};

/**
 * Track an event.
 * @param {Facade} track A track object
 */
Astronomer.prototype.track = function(track) {
  var self = this;

  var record = JSON.stringify({
    event: track.event(),
    properties: track.properties(),
    anonymousId: analytics.user().anonymousId(),
    userId: self.props.userId,
    traits: self.props.userProperties
  });

  self.kinesisQueue.push(record);
};

Astronomer.prototype.putRecord = function(record, callback) {
  console.log('putting record');

  var self = this;
  self.ensureKinesisConfig(function(config, kinesis) {
    var params = {
      Data: record,
      StreamName: config.streamName,
      PartitionKey: self.options.appId
    };

    kinesis.putRecord(params, function(err, data) {
      console.log(err, data);
      callback();
    });
  });
};
<commit_msg>SAVEPOINT<commit_after>/* global analytics */
/* eslint no-console:0, no-unused-vars:0, no-extra-parens:0 */

'use strict';

var integration = require('analytics.js-integration');
var request = require('visionmedia/superagent');
var prefix = require('johntron/superagent-prefix');
var async = require('caolan/async');
window._astq = window._astq || [];

/**
 * Expose `Astronomer` integration.
 */
var Astronomer = module.exports = exports = integration('astronomer')
  .global('_astq')
  .option('appId', null)
  .option('credentialServer', 'https://app.astronomer.io:443')
  .option('credentialsExpiration', 900)
  .option('trackAllPages', false)
  .option('trackNamedPages', true)
  .option('trackCategorizedPages', true)
  .tag('library', '<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.33.min.js">');

/**
 * Initialize astronomer.
 * @param {Facade} page The page object
 */
Astronomer.prototype.initialize = function() {
  var self = this;
  self.props = {};
  self.kinesis = null;
  self.kinesisQueue = async.queue(self.putRecord.bind(self), 1);

  console.log('Authenticating with ' + self.options.credentialServer);

  self.load('library', self.ready);

  // Load lib, auth, config, ready, dequeue
  // async.waterfall([
  //   self.loadAwsLib.bind(self),
  //   self.auth.bind(self)
  // ],
  // function(err, response) {
  //   self.configAws(response.body);
  //   self.setCredentialToken(response.body.credentials.Token);
  //   self.ready();
  //   self.dequeue();
  // });
};

Astronomer.prototype.expired = function() {
  var expireTime = (((self.kinesis || {}).config || {}).credentials || {}).expireTime;
  return ((!expireTime || expireTime.getTime() <= Date.now()) && !self.authing);
};

/**
 * Load the aws library from CDN
 * @param {Function} callback Callback
 */
// Astronomer.prototype.loadAwsLib = function(callback) {
//   this.load('library', callback);
// };

/**
 * Authenticate with our server
 * @param {Function} callback Callback
 */
Astronomer.prototype.ensureKinesisConfig = function(callback) {
  var self = this;

  if (!self.expired()) {
    return callback(self.config, self.kinesis);
  }

  // Request fresh config (token)
  self.requestCredentials(function(err, response) {
    console.log('authed', err, response);
    // Update global config object
    self.config = response.body;

    // Assign kinesis service object to new one with fresh config
    self.kinesis = new window.AWS.Kinesis({
      region: self.config.region,
      credentials: new window.AWS.WebIdentityCredentials({
        RoleArn: self.config.roleArn,
        WebIdentityToken: self.config.credentials.Token,
        DurationSeconds: self.options.credentialsExpiration
      })
    });

    callback(self.config, self.kinesis);
  });
};

Astronomer.prototype.requestCredentials = function(callback) {
  request.get('/api/v1/applications/credentials/' + this.options.appId)
    .use(prefix(this.options.credentialServer))
    .end(callback);
};

/**
 * Assign our kinesis object with a new one configured with new credentials
 * @param {Object} config Config object from our server
 */
// Astronomer.prototype.configAws = function(config) {
//   this.config = config;
//   this.kinesis = new window.AWS.Kinesis({
//     region: this.config.region,
//     credentials: new window.AWS.WebIdentityCredentials({
//       RoleArn: this.config.roleArn,
//       DurationSeconds: this.options.credentialsExpiration
//     })
//   });
// };

/**
 * Invalidate credentials and set new token
 * @param {String} token The new token
 */
// Astronomer.prototype.setCredentialToken = function(token) {
//   this.kinesis.config.credentials.expired = true;
//   this.kinesis.config.credentials.params.WebIdentityToken = token;
// };

/**
 * Replay the queue
 */
Astronomer.prototype.dequeue = function() {
  while (window._astq.length > 0) {
    var item = window._astq.shift();
    var method = item.shift();
    if (analytics[method]) analytics[method].apply(analytics, item);
  }
};

/**
 * Has the astronomer library been loaded yet?
 * @return {Boolean}
 */
Astronomer.prototype.loaded = function() {
  return !!((((window.AWS) || {}).config || {}).credentials || {}).accessKeyId;
};

/**
 * Trigger a page view.
 * @param {Facade} page A page object
 */
Astronomer.prototype.page = function(page) {
  var category = page.category();
  var props = page.properties();
  var name = page.fullName();
  var opts = this.options;

  // all pages
  if (opts.trackAllPages) {
    this.track(page.track());
  }

  // named pages
  if (name && opts.trackNamedPages) {
    this.track(page.track(name));
  }

  // categorized pages
  // if (category && opts.trackCategorizedPages) {
  //   this.track(page.track(category));
  // }
};

/**
 * Identify a user.
 * @param {Facade} identify An identify object
 */
Astronomer.prototype.identify = function(identify) {
  var id = identify.userId();
  var traits = identify.traits();
  this.props.userId = id;
  this.props.userProperties = traits;
};

/**
 * Associate the current user with a group of users.
 * @param {Facade} group A group object
 */
Astronomer.prototype.group = function(group) {
  var id = group.groupId();
  var traits = group.traits();
  this.props.groupId = id;
  this.props.groupProperties = traits;
};

/**
 * Track an event.
 * @param {Facade} track A track object
 */
Astronomer.prototype.track = function(track) {
  var self = this;

  var record = JSON.stringify({
    event: track.event(),
    properties: track.properties(),
    anonymousId: analytics.user().anonymousId(),
    userId: self.props.userId,
    traits: self.props.userProperties
  });

  self.kinesisQueue.push(record);
};

Astronomer.prototype.putRecord = function(record, callback) {
  console.log('putting record');

  var self = this;
  self.ensureKinesisConfig(function(config, kinesis) {
    var params = {
      Data: record,
      StreamName: config.streamName,
      PartitionKey: self.options.appId
    };

    kinesis.putRecord(params, function(err, data) {
      console.log(err, data);
      callback();
    });
  });
};
<|endoftext|>