<commit_before>/*
 * Jake JavaScript build tool
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

var api = new (function () {
  /**
    @name task
    @static
    @function
    @description Creates a Jake Task
    `
    @param {String} name The name of the Task
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to perform for this task
    @param {Object} [opts]
      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.

    @example
    desc('This is the default task.');
    task('default', function (params) {
      console.log('This is the default task.');
    });

    desc('This task has prerequisites.');
    task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) {
      console.log('Ran some prereqs first.');
    });

    desc('This is an asynchronous task.');
    task('asyncTask', function () {
      setTimeout(complete, 1000);
    }, {async: true});
   */
  this.task = function (name, prereqs, action, opts) {
    var args = Array.prototype.slice.call(arguments);
       var createdTask;
    args.unshift('task');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name rule
    @static
    @function
    @description Creates a Jake Suffix Rule
    `
    @param {String} pattern The suffix name of the objective
    @param {String} source The suffix name of the objective
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to perform for this task
    @param {Object} [opts]
      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.
    @example
    desc('This is a rule, which does not support namespace or pattern.');
    rule('.o', '.c', {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This rule has prerequisites.');
    rule('.o', '.c', ['util.h'], {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is a rule with patterns.');
    rule('%.o', '%.c', {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is another rule with patterns.');
    rule('obj/%.o', 'src/%.c', {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is an example with chain rules.');
    rule('%.pdf', '%.dvi', {async: true}, function () {
      var cmd = util.format('dvipdfm %s',this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    rule('%.dvi', '%.tex', {async: true}, function () {
      var cmd = util.format('latex %s',this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This rule has a namespace.');
    task('default', ['debug:obj/main.o]);

    namespace('debug', {async: true}, function() {
      rule('obj/%.o', 'src/%.c', function () {
        // ...
      });
    }
   */
  this.rule = function () {
    var args = Array.prototype.slice.call(arguments);
       var arg;
       var pattern = args.shift();
       var source = args.shift();
       var prereqs = [];
       var action = function () {};
       var opts = {};
       var key = pattern.toString(); // May be a RegExp

    while ((arg = args.shift())) {
      if (typeof arg == 'function') {
        action = arg;
      }
      else if (Array.isArray(arg)) {
        prereqs = arg;
      }
      else {
        opts = arg;
      }
    }

    jake.currentNamespace.rules[key] = new jake.Rule({
      pattern: pattern,
     source: source,
     prereqs: prereqs,
     action: action,
     opts: opts,
     desc: jake.currentTaskDescription,
     ns: jake.currentNamespace
    });
    jake.currentTaskDescription = null;
  };

  /**
    @name directory
    @static
    @function
    @description Creates a Jake DirectoryTask. Can be used as a prerequisite
    for FileTasks, or for simply ensuring a directory exists for use with a
    Task's action.
    `
    @param {String} name The name of the DiretoryTask

    @example

    // Creates the package directory for distribution
    directory('pkg');
   */
  this.directory = function (name) {
    var args = Array.prototype.slice.call(arguments);
       var createdTask;
    args.unshift('directory');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name file
    @static
    @function
    @description Creates a Jake FileTask.
    `
    @param {String} name The name of the FileTask
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to create this file, if it doesn't
    exist already.
    @param {Object} [opts]
      @param {Array} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.

   */
  this.file = function (name, prereqs, action, opts) {
    var args = Array.prototype.slice.call(arguments);
       var createdTask;
    args.unshift('file');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name desc
    @static
    @function
    @description Creates a description for a Jake Task (or FileTask,
    DirectoryTask). When invoked, the description that iscreated will
    be associated with whatever Task is created next.
    `
    @param {String} description The description for the Task
   */
  this.desc = function (description) {
    jake.currentTaskDescription = description;
  };

  /**
    @name namespace
    @static
    @function
    @description Creates a namespace which allows logical grouping
    of tasks, and prevents name-collisions with task-names. Namespaces
    can be nested inside of other namespaces.
    `
    @param {String} name The name of the namespace
    @param {Function} scope The enclosing scope for the namespaced tasks

    @example
    namespace('doc', function () {
      task('generate', ['doc:clobber'], function () {
        // Generate some docs
      });

      task('clobber', function () {
        // Clobber the doc directory first
      });
    });
   */
  this.namespace = function (name, closure) {
    var curr = jake.currentNamespace;
       var ns = curr.childNamespaces[name] || new jake.Namespace(name, curr);
    curr.childNamespaces[name] = ns;
    jake.currentNamespace = ns;
    closure();
    jake.currentNamespace = curr;
    jake.currentTaskDescription = null;
    return ns;
  };

  /**
    @name complete
    @static
    @function
    @description Completes an asynchronous task, allowing Jake's
    execution to proceed to the next task. Calling complete globally or without
    arguments completes the last task on the invocationChain. If you use parallel
    execution of prereqs this will probably complete a wrong task. You should call this
    function with this task as the first argument, before the optional return value.
    Alternatively you can call task.complete()
    `
    @example
    task('generate', ['doc:clobber'], function () {
      exec('./generate_docs.sh', function (err, stdout, stderr) {
        if (err || stderr) {
          fail(err || stderr);
        }
        else {
          console.log(stdout);
          complete();
        }
      });
    }, {async: true});
   */
  this.complete = function (task, val) {
    //this should detect if the first arg is a task, but I guess it should be more thorough
    if(task && task. _currentPrereqIndex >=0 ) {
      task.complete(val);
    }
 else {
      val = task;
      if(jake._invocationChain.length > 0) {
        jake._invocationChain[jake._invocationChain.length-1].complete(val);
      }
    }
  };

  /**
    @name fail
    @static
    @function
    @description Causes Jake execution to abort with an error.
    Allows passing an optional error code, which will be used to
    set the exit-code of exiting process.
    `
    @param {Error|String} err The error to thow when aborting execution.
    If this argument is an Error object, it will simply be thrown. If
    a String, it will be used as the error-message. (If it is a multi-line
    String, the first line will be used as the Error message, and the
    remaining lines will be used as the error-stack.)

    @example
    task('createTests, function () {
      if (!fs.existsSync('./tests')) {
        fail('Test directory does not exist.');
      }
      else {
        // Do some testing stuff ...
      }
    });
   */
  this.fail = function (err, code) {
    var msg;
       var errObj;
    if (code) {
      jake.errorCode = code;
    }
    if (err) {
      if (typeof err == 'string') {
        // Use the initial or only line of the error as the error-message
        // If there was a multi-line error, use the rest as the stack
        msg = err.split('\n');
        errObj = new Error(msg.shift());
        if (msg.length) {
          errObj.stack = msg.join('\n');
        }
        throw errObj;
      }
      else if (err instanceof Error) {
        throw err;
      }
      else {
        throw new Error(err.toString());
      }
    }
    else {
      throw new Error();
    }
  };

  this.packageTask = function (name, version, prereqs, definition) {
    return new jake.PackageTask(name, version, prereqs, definition);
  };

  this.publishTask = function (name, prereqs, opts, definition) {
    return new jake.PublishTask(name, prereqs, opts, definition);
  };

  // Backward-compat
  this.npmPublishTask = function (name, prereqs, opts, definition) {
    return new jake.PublishTask(name, prereqs, opts, definition);
  };

  this.watchTask = function (name, taskNames, definition) {
    return new jake.WatchTask(name, taskNames, definition);
  };

  this.testTask = function () {
    var ctor = function () {};
       var t;
    ctor.prototype = jake.TestTask.prototype;
    t = new ctor();
    jake.TestTask.apply(t, arguments);
    return t;
  };

  this.setTaskTimeout = function (t) {
    this._taskTimeout = t;
  };

  this.setSeriesAutoPrefix = function (prefix) {
    this._seriesAutoPrefix = prefix;
  };

  this.series = function (...args) {
    let prereqs = args.map((arg) => {
      let name = (this._seriesAutoPrefix || '') + arg.name;
      jake.task(name, arg);
      return name;
    });
    let seriesName = utils.string.uuid();
    let seriesTask = jake.task(seriesName, prereqs);
    seriesTask._internal = true;
    let res = function () {
      return new Promise((resolve) => {
        seriesTask.invoke();
        seriesTask.on('complete', (val) => {
          resolve(val);
        });
      });
    };
    Object.defineProperty(res, 'name', {value: utils.string.uuid(),
          writable: false});
    return res;
  };

})();

module.exports = api;
<commit_msg>Import utils lib<commit_after>/*
 * Jake JavaScript build tool
 * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/
let utils = require('./utils');

var api = new (function () {
  /**
    @name task
    @static
    @function
    @description Creates a Jake Task
    `
    @param {String} name The name of the Task
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to perform for this task
    @param {Object} [opts]
      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.

    @example
    desc('This is the default task.');
    task('default', function (params) {
      console.log('This is the default task.');
    });

    desc('This task has prerequisites.');
    task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) {
      console.log('Ran some prereqs first.');
    });

    desc('This is an asynchronous task.');
    task('asyncTask', function () {
      setTimeout(complete, 1000);
    }, {async: true});
   */
  this.task = function (name, prereqs, action, opts) {
    var args = Array.prototype.slice.call(arguments);
       var createdTask;
    args.unshift('task');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name rule
    @static
    @function
    @description Creates a Jake Suffix Rule
    `
    @param {String} pattern The suffix name of the objective
    @param {String} source The suffix name of the objective
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to perform for this task
    @param {Object} [opts]
      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.
    @example
    desc('This is a rule, which does not support namespace or pattern.');
    rule('.o', '.c', {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This rule has prerequisites.');
    rule('.o', '.c', ['util.h'], {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is a rule with patterns.');
    rule('%.o', '%.c', {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is another rule with patterns.');
    rule('obj/%.o', 'src/%.c', {async: true}, function () {
      var cmd = util.format('gcc -o %s %s', this.name, this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This is an example with chain rules.');
    rule('%.pdf', '%.dvi', {async: true}, function () {
      var cmd = util.format('dvipdfm %s',this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    rule('%.dvi', '%.tex', {async: true}, function () {
      var cmd = util.format('latex %s',this.source);
      jake.exec([cmd], function () {
        complete();
      }, {printStdout: true});
    });

    desc('This rule has a namespace.');
    task('default', ['debug:obj/main.o]);

    namespace('debug', {async: true}, function() {
      rule('obj/%.o', 'src/%.c', function () {
        // ...
      });
    }
   */
  this.rule = function () {
    var args = Array.prototype.slice.call(arguments);
       var arg;
       var pattern = args.shift();
       var source = args.shift();
       var prereqs = [];
       var action = function () {};
       var opts = {};
       var key = pattern.toString(); // May be a RegExp

    while ((arg = args.shift())) {
      if (typeof arg == 'function') {
        action = arg;
      }
      else if (Array.isArray(arg)) {
        prereqs = arg;
      }
      else {
        opts = arg;
      }
    }

    jake.currentNamespace.rules[key] = new jake.Rule({
      pattern: pattern,
     source: source,
     prereqs: prereqs,
     action: action,
     opts: opts,
     desc: jake.currentTaskDescription,
     ns: jake.currentNamespace
    });
    jake.currentTaskDescription = null;
  };

  /**
    @name directory
    @static
    @function
    @description Creates a Jake DirectoryTask. Can be used as a prerequisite
    for FileTasks, or for simply ensuring a directory exists for use with a
    Task's action.
    `
    @param {String} name The name of the DiretoryTask

    @example

    // Creates the package directory for distribution
    directory('pkg');
   */
  this.directory = function (name) {
    var args = Array.prototype.slice.call(arguments);
       var createdTask;
    args.unshift('directory');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name file
    @static
    @function
    @description Creates a Jake FileTask.
    `
    @param {String} name The name of the FileTask
    @param {Array} [prereqs] Prerequisites to be run before this task
    @param {Function} [action] The action to create this file, if it doesn't
    exist already.
    @param {Object} [opts]
      @param {Array} [opts.asyc=false] Perform this task asynchronously.
      If you flag a task with this option, you must call the global
      `complete` method inside the task's action, for execution to proceed
      to the next task.

   */
  this.file = function (name, prereqs, action, opts) {
    var args = Array.prototype.slice.call(arguments);
       var createdTask;
    args.unshift('file');
    createdTask = jake.createTask.apply(global, args);
    jake.currentTaskDescription = null;
    return createdTask;
  };

  /**
    @name desc
    @static
    @function
    @description Creates a description for a Jake Task (or FileTask,
    DirectoryTask). When invoked, the description that iscreated will
    be associated with whatever Task is created next.
    `
    @param {String} description The description for the Task
   */
  this.desc = function (description) {
    jake.currentTaskDescription = description;
  };

  /**
    @name namespace
    @static
    @function
    @description Creates a namespace which allows logical grouping
    of tasks, and prevents name-collisions with task-names. Namespaces
    can be nested inside of other namespaces.
    `
    @param {String} name The name of the namespace
    @param {Function} scope The enclosing scope for the namespaced tasks

    @example
    namespace('doc', function () {
      task('generate', ['doc:clobber'], function () {
        // Generate some docs
      });

      task('clobber', function () {
        // Clobber the doc directory first
      });
    });
   */
  this.namespace = function (name, closure) {
    var curr = jake.currentNamespace;
       var ns = curr.childNamespaces[name] || new jake.Namespace(name, curr);
    curr.childNamespaces[name] = ns;
    jake.currentNamespace = ns;
    closure();
    jake.currentNamespace = curr;
    jake.currentTaskDescription = null;
    return ns;
  };

  /**
    @name complete
    @static
    @function
    @description Completes an asynchronous task, allowing Jake's
    execution to proceed to the next task. Calling complete globally or without
    arguments completes the last task on the invocationChain. If you use parallel
    execution of prereqs this will probably complete a wrong task. You should call this
    function with this task as the first argument, before the optional return value.
    Alternatively you can call task.complete()
    `
    @example
    task('generate', ['doc:clobber'], function () {
      exec('./generate_docs.sh', function (err, stdout, stderr) {
        if (err || stderr) {
          fail(err || stderr);
        }
        else {
          console.log(stdout);
          complete();
        }
      });
    }, {async: true});
   */
  this.complete = function (task, val) {
    //this should detect if the first arg is a task, but I guess it should be more thorough
    if(task && task. _currentPrereqIndex >=0 ) {
      task.complete(val);
    }
 else {
      val = task;
      if(jake._invocationChain.length > 0) {
        jake._invocationChain[jake._invocationChain.length-1].complete(val);
      }
    }
  };

  /**
    @name fail
    @static
    @function
    @description Causes Jake execution to abort with an error.
    Allows passing an optional error code, which will be used to
    set the exit-code of exiting process.
    `
    @param {Error|String} err The error to thow when aborting execution.
    If this argument is an Error object, it will simply be thrown. If
    a String, it will be used as the error-message. (If it is a multi-line
    String, the first line will be used as the Error message, and the
    remaining lines will be used as the error-stack.)

    @example
    task('createTests, function () {
      if (!fs.existsSync('./tests')) {
        fail('Test directory does not exist.');
      }
      else {
        // Do some testing stuff ...
      }
    });
   */
  this.fail = function (err, code) {
    var msg;
       var errObj;
    if (code) {
      jake.errorCode = code;
    }
    if (err) {
      if (typeof err == 'string') {
        // Use the initial or only line of the error as the error-message
        // If there was a multi-line error, use the rest as the stack
        msg = err.split('\n');
        errObj = new Error(msg.shift());
        if (msg.length) {
          errObj.stack = msg.join('\n');
        }
        throw errObj;
      }
      else if (err instanceof Error) {
        throw err;
      }
      else {
        throw new Error(err.toString());
      }
    }
    else {
      throw new Error();
    }
  };

  this.packageTask = function (name, version, prereqs, definition) {
    return new jake.PackageTask(name, version, prereqs, definition);
  };

  this.publishTask = function (name, prereqs, opts, definition) {
    return new jake.PublishTask(name, prereqs, opts, definition);
  };

  // Backward-compat
  this.npmPublishTask = function (name, prereqs, opts, definition) {
    return new jake.PublishTask(name, prereqs, opts, definition);
  };

  this.watchTask = function (name, taskNames, definition) {
    return new jake.WatchTask(name, taskNames, definition);
  };

  this.testTask = function () {
    var ctor = function () {};
       var t;
    ctor.prototype = jake.TestTask.prototype;
    t = new ctor();
    jake.TestTask.apply(t, arguments);
    return t;
  };

  this.setTaskTimeout = function (t) {
    this._taskTimeout = t;
  };

  this.setSeriesAutoPrefix = function (prefix) {
    this._seriesAutoPrefix = prefix;
  };

  this.series = function (...args) {
    let prereqs = args.map((arg) => {
      let name = (this._seriesAutoPrefix || '') + arg.name;
      jake.task(name, arg);
      return name;
    });
    let seriesName = utils.string.uuid();
    let seriesTask = jake.task(seriesName, prereqs);
    seriesTask._internal = true;
    let res = function () {
      return new Promise((resolve) => {
        seriesTask.invoke();
        seriesTask.on('complete', (val) => {
          resolve(val);
        });
      });
    };
    Object.defineProperty(res, 'name', {value: utils.string.uuid(),
          writable: false});
    return res;
  };

})();

module.exports = api;
<|endoftext|>


<commit_before>Package.describe({
  name: 'okgrow:analytics',
  version: '1.0.6',
  summary: 'Complete Google Analytics, Mixpanel, KISSmetrics (and more) integration for Meteor',
  git: 'https://github.com/okgrow/analytics',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0.3.1');
  api.use('mongo');
  api.use('accounts-base', ['client', 'server'], {weak: true});
  api.use('browser-policy-content', 'server', {weak: true});

  //weak dependencies indicate we will load after the following packages
  // and constrain their versions IF another package, or app brings them in
  api.use('iron:router@1.0.7', 'client', {weak: true});
  api.use('meteorhacks:flow-router@1.17.2', 'client', {weak: true});
  api.use('kadira:flow-router@2.6.0', 'client', {weak: true});

  api.addFiles([
    'server/browser-policy.js',
    'server/publications.js'
  ], 'server');
  api.addFiles([
    'vendor/analytics.min.js',
    'client/collections.js',
    'client/meteor-analytics.js',
  ], 'client');
});
<commit_msg>Bumped version number to 1.0.8<commit_after>Package.describe({
  name: 'okgrow:analytics',
  version: '1.0.8',
  summary: 'Complete Google Analytics, Mixpanel, KISSmetrics (and more) integration for Meteor',
  git: 'https://github.com/okgrow/analytics',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0.3.1');
  api.use('mongo');
  api.use('accounts-base', ['client', 'server'], {weak: true});
  api.use('browser-policy-content', 'server', {weak: true});

  //weak dependencies indicate we will load after the following packages
  // and constrain their versions IF another package, or app brings them in
  api.use('iron:router@1.0.7', 'client', {weak: true});
  api.use('meteorhacks:flow-router@1.17.2', 'client', {weak: true});
  api.use('kadira:flow-router@2.6.0', 'client', {weak: true});

  api.addFiles([
    'server/browser-policy.js',
    'server/publications.js'
  ], 'server');
  api.addFiles([
    'vendor/analytics.min.js',
    'client/collections.js',
    'client/meteor-analytics.js',
  ], 'client');
});
<|endoftext|>


<commit_before>var validate = require("./validate").validate;
var utils = require("./utils");
var createError = require("./utils").createError;
var stacks = require("./stacks");
var respond = utils.respond;

function ElasticBeanstalk (config) {
  this._applications = [];
  this._environments = [];
  this._versions = [];
  this._s3 = {};
}
module.exports = ElasticBeanstalk;

ElasticBeanstalk.prototype.createApplication = function createApplication (params, fn) {
  var eb = this;
  var error = validate("createApplication", params, function () {
    if (utils.doesApplicationExist(eb, params.ApplicationName)) {
      return createError(new Error("Application " + params.ApplicationName + " already exists."), { code: "InvalidParameterValue" });
    }
  });

  if (error) {
    return respond(fn, error, null);
  }

  var app = {
    ApplicationName: (params || {}).ApplicationName,
    Description: (params || {}).Description,
    DateCreated: new Date(),
    DateUpdated: new Date(),
    Versions: [],
    ConfigurationTemplates: []
  };

  this._applications.push(app);

  respond(fn, null, { Application: app });
};

ElasticBeanstalk.prototype.updateApplication = function updateApplication (params, fn) {
  var eb = this;
  var error = validate("createApplication", params, function () {
    if (!utils.doesApplicationExist(eb, params.ApplicationName)) {
      return createError(new Error("No Application named \'" + params.ApplicationName + "\' found."), { code: "InvalidParameterValue" });
    }
  });

  if (error) {
    return respond(fn, error, null);
  }

  var apps = this._applications;
  for (var i = 0; i < apps.length; i++) {
    if (apps[i].ApplicationName === params.ApplicationName) {
      apps[i].Description = params.Description;
      apps[i].DateUpdated = new Date();
      return respond(fn, null, { Application: apps[i] });
    }
  }
};

ElasticBeanstalk.prototype.deleteApplication = function deleteApplication (params, fn) {
  var error = validate("deleteApplication", params);

  if (error) {
    return respond(fn, error, null);
  }

  var apps = this._applications;
  for (var i = 0; i < apps.length; i++) {
    if (apps[i].ApplicationName === params.ApplicationName) {
      apps.splice(i, 1);
      return respond(fn, null, {});
    }
  }
  respond(fn, null, {});
};

ElasticBeanstalk.prototype.describeApplications = function describeApplications (params, fn) {
  params = params || {};
  var error = validate("describeApplications", params);

  if (error) {
    return respond(fn, error, null);
  }

  var apps = params.ApplicationNames ? this._applications.filter(function (app) {
    return !!~params.ApplicationNames.indexOf(app.ApplicationName);
  }) : this._applications;

  respond(fn, null, { Applications: apps });
};

ElasticBeanstalk.prototype.createEnvironment = function createEnvironment (params, fn) {
  var eb = this;
  var error = validate("createEnvironment", params, function () {
    // Check application exists
    if (!utils.doesApplicationExist(eb, params.ApplicationName)) {
      return createError(new Error("No Application " + params.ApplicationName + " found."), { code: "InvalidParameterValue" });
    }

    // Check version exists
    if (params.VersionLabel && !utils.doesVersionExist(eb, params.ApplicationName, params.VersionLabel)) {
      return createError(new Error("No VersionLabel for " + params.VersionLabel + " with Application " + params.ApplicationName + "."), { code: "InvalidParameterValue" });
    }
  });

  if (error) {
    return respond(fn, error, null);
  }

  var env = utils.copy(params);
  env.EnvironmentId = utils.createEnvironmentId();
  env.DateCreated = new Date();
  env.DateUpdated = new Date();
  env.Status = "Launching";
  env.Health = "Grey";
  env.Tier = env.Tier || { Name: "WebSever", Type: "Standard", Version: "1.0" };

  this._environments.push(env);
  respond(fn, null, env);
};

/**
 * Does not support options:
 * - `IncludeDeleted`
 * - `IncludedDeletedBackTo`
 */
ElasticBeanstalk.prototype.describeEnvironments = function describeEnvironments (params, fn) {
  var error = validate("describeEnvironments", params);

  if (error) {
    return respond(fn, error, null);
  }

  var envs = this._environments.filter(function (env) {
    var valid = true;
    if (params.EnvironmentIds) {
      if (!~params.EnvironmentIds.indexOf(env.EnvironmentId)) valid = false;
    }
    if (params.EnvironmentNames) {
      if (!~params.EnvironmentNames.indexOf(env.EnvironmentName)) valid = false;
    }
    if (params.VersionLabel && env.VersionLabel !== params.VersionLabel) {
      valid = false;
    }
    if (params.ApplicationName && env.ApplicationName !== params.ApplicationName) {
      valid = false;
    }
    return valid;
  });

  respond(fn, null, { Environments: envs });
};

ElasticBeanstalk.prototype.updateEnvironment = function updateEnvironment (params, fn) {
  var eb = this;
  var error = validate("updateEnvironment", params, function () {
    if (!utils.doesEnvironmentExist(eb, params)) {
      if (params.EnvironmentId)
        return createError(new Error("No environment with EnvironmentId \'" + params.EnvironmentId + "\' found."), { code: "InvalidParameterValue" });
      else
        return createError(new Error("No environment with EnvironmentName \'" + params.EnvironmentName + "\' found."), { code: "InvalidParameterValue" });
    }
  });

  if (error) {
    return respond(fn, error, null);
  }

  var env = utils.findWhere(eb._environments, { EnvironmentId: params.EnvironmentId }) ||
            utils.findWhere(eb._environments, { EnvironmentName: params.EnvironmentName });
  utils.update(env, params);
  env.DateUpdated = new Date();

  respond(fn, null, env);
};

/**
 * Swaps two environments' CNAMES by name
 *
 * @param {Object}
 * - {String} DestinationEnvironmentName
 * - {String} SourceEnvironmentName
 */

ElasticBeanstalk.prototype.swapEnvironmentCNAMEs = function swapEnvironmentCNAMEs (params) {
  return this.eb.swapEnvironmentCNAMEs(params || {});
};

/**
 * Does not check for the existence of S3 bucket items.
 */

ElasticBeanstalk.prototype.createApplicationVersion = function createApplicationVersion (params) {
  var error = validate("createApplicationVersion", params);

  if (error) {
    return respond(fn, error, null);
  }

  var version = utils.copy(params);

  if (!version.SourceBundle) {
    version.SourceBundle = {};
  }

  version.DateCreated = new Date(),
  version.DateUpdated = new Date()

  this._versions.push(version);
  var app = utils.findWhere(this._applications, { ApplicationName: params.ApplicationName });
  app.Versions.push(version.VersionLabel);

  respond(fn, null, version);
};

/**
 * S3 operations on the EB instance to interface with `addVersion`
 */

ElasticBeanstalk.prototype.createBucket = function createBucket (params, fn) {
  this._s3[params.Bucket] = {};
  respond(fn, null, {});
};

ElasticBeanstalk.prototype.putObject = function putObject (params, fn) {
  if (!this._s3[params.Bucket]) {
    // TODO figure out real error
    return respond(fn, createError(new Error("No bucket '" + params.Bucket + "' currently exists.")), null);
  }

  var bucket = this._s3[params.Bucket];
  bucket[params.Key] = params.Body;
  respond(fn, null, {});
};
<commit_msg>Add callback to createApplicationVersion<commit_after>var validate = require("./validate").validate;
var utils = require("./utils");
var createError = require("./utils").createError;
var stacks = require("./stacks");
var respond = utils.respond;

function ElasticBeanstalk (config) {
  this._applications = [];
  this._environments = [];
  this._versions = [];
  this._s3 = {};
}
module.exports = ElasticBeanstalk;

ElasticBeanstalk.prototype.createApplication = function createApplication (params, fn) {
  var eb = this;
  var error = validate("createApplication", params, function () {
    if (utils.doesApplicationExist(eb, params.ApplicationName)) {
      return createError(new Error("Application " + params.ApplicationName + " already exists."), { code: "InvalidParameterValue" });
    }
  });

  if (error) {
    return respond(fn, error, null);
  }

  var app = {
    ApplicationName: (params || {}).ApplicationName,
    Description: (params || {}).Description,
    DateCreated: new Date(),
    DateUpdated: new Date(),
    Versions: [],
    ConfigurationTemplates: []
  };

  this._applications.push(app);

  respond(fn, null, { Application: app });
};

ElasticBeanstalk.prototype.updateApplication = function updateApplication (params, fn) {
  var eb = this;
  var error = validate("createApplication", params, function () {
    if (!utils.doesApplicationExist(eb, params.ApplicationName)) {
      return createError(new Error("No Application named \'" + params.ApplicationName + "\' found."), { code: "InvalidParameterValue" });
    }
  });

  if (error) {
    return respond(fn, error, null);
  }

  var apps = this._applications;
  for (var i = 0; i < apps.length; i++) {
    if (apps[i].ApplicationName === params.ApplicationName) {
      apps[i].Description = params.Description;
      apps[i].DateUpdated = new Date();
      return respond(fn, null, { Application: apps[i] });
    }
  }
};

ElasticBeanstalk.prototype.deleteApplication = function deleteApplication (params, fn) {
  var error = validate("deleteApplication", params);

  if (error) {
    return respond(fn, error, null);
  }

  var apps = this._applications;
  for (var i = 0; i < apps.length; i++) {
    if (apps[i].ApplicationName === params.ApplicationName) {
      apps.splice(i, 1);
      return respond(fn, null, {});
    }
  }
  respond(fn, null, {});
};

ElasticBeanstalk.prototype.describeApplications = function describeApplications (params, fn) {
  params = params || {};
  var error = validate("describeApplications", params);

  if (error) {
    return respond(fn, error, null);
  }

  var apps = params.ApplicationNames ? this._applications.filter(function (app) {
    return !!~params.ApplicationNames.indexOf(app.ApplicationName);
  }) : this._applications;

  respond(fn, null, { Applications: apps });
};

ElasticBeanstalk.prototype.createEnvironment = function createEnvironment (params, fn) {
  var eb = this;
  var error = validate("createEnvironment", params, function () {
    // Check application exists
    if (!utils.doesApplicationExist(eb, params.ApplicationName)) {
      return createError(new Error("No Application " + params.ApplicationName + " found."), { code: "InvalidParameterValue" });
    }

    // Check version exists
    if (params.VersionLabel && !utils.doesVersionExist(eb, params.ApplicationName, params.VersionLabel)) {
      return createError(new Error("No VersionLabel for " + params.VersionLabel + " with Application " + params.ApplicationName + "."), { code: "InvalidParameterValue" });
    }
  });

  if (error) {
    return respond(fn, error, null);
  }

  var env = utils.copy(params);
  env.EnvironmentId = utils.createEnvironmentId();
  env.DateCreated = new Date();
  env.DateUpdated = new Date();
  env.Status = "Launching";
  env.Health = "Grey";
  env.Tier = env.Tier || { Name: "WebSever", Type: "Standard", Version: "1.0" };

  this._environments.push(env);
  respond(fn, null, env);
};

/**
 * Does not support options:
 * - `IncludeDeleted`
 * - `IncludedDeletedBackTo`
 */
ElasticBeanstalk.prototype.describeEnvironments = function describeEnvironments (params, fn) {
  var error = validate("describeEnvironments", params);

  if (error) {
    return respond(fn, error, null);
  }

  var envs = this._environments.filter(function (env) {
    var valid = true;
    if (params.EnvironmentIds) {
      if (!~params.EnvironmentIds.indexOf(env.EnvironmentId)) valid = false;
    }
    if (params.EnvironmentNames) {
      if (!~params.EnvironmentNames.indexOf(env.EnvironmentName)) valid = false;
    }
    if (params.VersionLabel && env.VersionLabel !== params.VersionLabel) {
      valid = false;
    }
    if (params.ApplicationName && env.ApplicationName !== params.ApplicationName) {
      valid = false;
    }
    return valid;
  });

  respond(fn, null, { Environments: envs });
};

ElasticBeanstalk.prototype.updateEnvironment = function updateEnvironment (params, fn) {
  var eb = this;
  var error = validate("updateEnvironment", params, function () {
    if (!utils.doesEnvironmentExist(eb, params)) {
      if (params.EnvironmentId)
        return createError(new Error("No environment with EnvironmentId \'" + params.EnvironmentId + "\' found."), { code: "InvalidParameterValue" });
      else
        return createError(new Error("No environment with EnvironmentName \'" + params.EnvironmentName + "\' found."), { code: "InvalidParameterValue" });
    }
  });

  if (error) {
    return respond(fn, error, null);
  }

  var env = utils.findWhere(eb._environments, { EnvironmentId: params.EnvironmentId }) ||
            utils.findWhere(eb._environments, { EnvironmentName: params.EnvironmentName });
  utils.update(env, params);
  env.DateUpdated = new Date();

  respond(fn, null, env);
};

/**
 * Swaps two environments' CNAMES by name
 *
 * @param {Object}
 * - {String} DestinationEnvironmentName
 * - {String} SourceEnvironmentName
 */

ElasticBeanstalk.prototype.swapEnvironmentCNAMEs = function swapEnvironmentCNAMEs (params) {
  return this.eb.swapEnvironmentCNAMEs(params || {});
};

/**
 * Does not check for the existence of S3 bucket items.
 */

ElasticBeanstalk.prototype.createApplicationVersion = function createApplicationVersion (params, fn) {
  var error = validate("createApplicationVersion", params);

  if (error) {
    return respond(fn, error, null);
  }

  var version = utils.copy(params);

  if (!version.SourceBundle) {
    version.SourceBundle = {};
  }

  version.DateCreated = new Date(),
  version.DateUpdated = new Date()

  this._versions.push(version);
  var app = utils.findWhere(this._applications, { ApplicationName: params.ApplicationName });
  app.Versions.push(version.VersionLabel);

  respond(fn, null, version);
};

/**
 * S3 operations on the EB instance to interface with `addVersion`
 */

ElasticBeanstalk.prototype.createBucket = function createBucket (params, fn) {
  this._s3[params.Bucket] = {};
  respond(fn, null, {});
};

ElasticBeanstalk.prototype.putObject = function putObject (params, fn) {
  if (!this._s3[params.Bucket]) {
    // TODO figure out real error
    return respond(fn, createError(new Error("No bucket '" + params.Bucket + "' currently exists.")), null);
  }

  var bucket = this._s3[params.Bucket];
  bucket[params.Key] = params.Body;
  respond(fn, null, {});
};
<|endoftext|>


<commit_before>Package.describe({
  summary: 'Model layer for Meteor',
  version: '1.0.0-rc.6',
  name: 'jagi:astronomy',
  git: 'https://github.com/jagi/meteor-astronomy.git'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use('mongo');
  api.use('minimongo');
  api.use('underscore');
  api.use('ejson');
  api.use('check');

  api.imply('mongo');
  api.imply('underscore');
  api.imply('ejson');
  api.imply('check');

  api.addFiles([
    'lib/modules/core/global.js',
    'lib/modules/core/config.js',
    'lib/modules/core/utils.js',
    'lib/modules/core/events.js',
    'lib/modules/core/event.js',
    'lib/modules/core/event_manager.js',
    'lib/modules/core/base_class.js',
    'lib/modules/core/schema.js',
    'lib/modules/core/classes.js'
  ], ['client', 'server']);

  // Behaviors module.
  api.addFiles([
    'lib/modules/behaviors/global.js',
    'lib/modules/behaviors/behavior.js',
    'lib/modules/behaviors/class_behavior.js',
    'lib/modules/behaviors/create_behavior.js',
    'lib/modules/behaviors/init_definition.js',
    'lib/modules/behaviors/init_schema.js',
    'lib/modules/behaviors/init_class.js'
  ], ['client', 'server']);

  // Events module.
  api.addFiles([
    'lib/modules/events/init_definition.js',
    'lib/modules/events/init_schema.js',
    'lib/modules/events/init_class.js'
  ], ['client', 'server']);

  // Indexes module.
  api.addFiles([
    'lib/modules/indexes/init_definition.js',
    'lib/modules/indexes/init_schema.js',
    'lib/modules/indexes/init_class.js'
  ], 'server');

  // EJSON module.
  api.addFiles('lib/modules/ejson/init_module.js', ['client', 'server']);

  // Methods module.
  api.addFiles([
    'lib/modules/methods/init_definition.js',
    'lib/modules/methods/init_schema.js',
    'lib/modules/methods/init_class.js'
  ], ['client', 'server']);

  // Fields module.
  api.addFiles([
    'lib/modules/fields/global.js',
    'lib/modules/fields/create_type.js',
    'lib/modules/fields/base_field.js',
    'lib/modules/fields/types/null_field.js',
    'lib/modules/fields/types/string_field.js',
    'lib/modules/fields/types/number_field.js',
    'lib/modules/fields/types/boolean_field.js',
    'lib/modules/fields/types/date_field.js',
    'lib/modules/fields/types/object_field.js',
    'lib/modules/fields/types/array_field.js',
    'lib/modules/fields/utils.js',
    'lib/modules/fields/modifiers.js',
    'lib/modules/fields/set_default.js',
    'lib/modules/fields/set.js',
    'lib/modules/fields/get.js',
    'lib/modules/fields/push.js',
    'lib/modules/fields/pop.js',
    'lib/modules/fields/inc.js',
    'lib/modules/fields/modified.js',
    'lib/modules/fields/ejson.js',
    'lib/modules/fields/init_definition.js',
    'lib/modules/fields/init_schema.js',
    'lib/modules/fields/init_class.js'
  ], ['client', 'server']);

  // Storage module.
  api.addFiles([
    'lib/modules/storage/init_schema.js',
    'lib/modules/storage/init_class.js'
  ], ['client', 'server']);

  api.export(['Astro', 'Astronomy'], ['client', 'server']);
});

Package.onTest(function(api) {
  api.use([
    'tinytest',
    'insecure',
    'jagi:astronomy',
    'jagi:astronomy-timestamp-behavior',
    'jagi:astronomy-slug-behavior',
    'jagi:astronomy-softremove-behavior',
    'jagi:astronomy-validators',
    'jagi:astronomy-simple-validators'
  ]);

  api.addFiles('test/utils.js', ['client', 'server']);
  // Core.
  api.addFiles([
    'test/core/core_transform.js',
    'test/core/core_inheritance.js',
    'test/core/core_extend.js',
    'test/core/core_state.js'
  ], ['client', 'server']);
  // Storage
  api.addFiles([
    'test/storage/storage_init.js',
    'test/storage/storage_insert.js',
    'test/storage/storage_update.js',
    'test/storage/storage_remove.js',
    'test/storage/storage_reload.js',
    'test/storage/storage_cloning.js',
    'test/storage/storage_direct_insert.js',
    'test/storage/storage_direct_update.js',
    'test/storage/storage_direct_upsert.js',
    'test/storage/storage_direct_remove.js'
  ], ['client', 'server']);
  // EJSON.
  api.addFiles([
    'test/ejson/ejson_parsing.js'
  ], ['client', 'server']);
  // Events.
  api.addFiles([
    'test/events/events_order.js',
    'test/events/events_propagation.js',
    'test/events/events_prevent_default.js'
  ], ['client', 'server']);
  // Fields.
  api.addFiles([
    'test/fields/fields_definition.js',
    'test/fields/fields_default.js',
    'test/fields/fields_casting.js',
    'test/fields/fields_set.js',
    'test/fields/fields_get.js',
    'test/fields/fields_push.js',
    'test/fields/fields_pop.js',
    'test/fields/fields_inc.js',
    'test/fields/fields_modified.js',
    'test/fields/fields_immutable.js',
    'test/fields/fields_transient.js'
  ], ['client', 'server']);
  // Indexes.
  api.addFiles([
    'test/indexes/indexes_definition.js'
  ], 'server');
  // Methods.
  api.addFiles([
    'test/methods/methods_definition.js'
  ], ['client', 'server']);
  // Modules.
  api.addFiles([
    // Validators
    'test/modules/validators_validate_single.js',
    'test/modules/validators_validate_multiple.js',
    'test/modules/validators_order.js',
    // Simple Validators.
    'test/modules/simple_validators_parser.js'
  ], ['client', 'server']);
  // Behaviors.
  api.addFiles([
    'test/behaviors/behaviors_timestamp.js',
    'test/behaviors/behaviors_slug.js',
    'test/behaviors/behaviors_softremove.js'
  ], ['client', 'server']);
});
<commit_msg>Bump version to 1.0.0<commit_after>Package.describe({
  summary: 'Model layer for Meteor',
  version: '1.0.0',
  name: 'jagi:astronomy',
  git: 'https://github.com/jagi/meteor-astronomy.git'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use('mongo');
  api.use('minimongo');
  api.use('underscore');
  api.use('ejson');
  api.use('check');

  api.imply('mongo');
  api.imply('underscore');
  api.imply('ejson');
  api.imply('check');

  api.addFiles([
    'lib/modules/core/global.js',
    'lib/modules/core/config.js',
    'lib/modules/core/utils.js',
    'lib/modules/core/events.js',
    'lib/modules/core/event.js',
    'lib/modules/core/event_manager.js',
    'lib/modules/core/base_class.js',
    'lib/modules/core/schema.js',
    'lib/modules/core/classes.js'
  ], ['client', 'server']);

  // Behaviors module.
  api.addFiles([
    'lib/modules/behaviors/global.js',
    'lib/modules/behaviors/behavior.js',
    'lib/modules/behaviors/class_behavior.js',
    'lib/modules/behaviors/create_behavior.js',
    'lib/modules/behaviors/init_definition.js',
    'lib/modules/behaviors/init_schema.js',
    'lib/modules/behaviors/init_class.js'
  ], ['client', 'server']);

  // Events module.
  api.addFiles([
    'lib/modules/events/init_definition.js',
    'lib/modules/events/init_schema.js',
    'lib/modules/events/init_class.js'
  ], ['client', 'server']);

  // Indexes module.
  api.addFiles([
    'lib/modules/indexes/init_definition.js',
    'lib/modules/indexes/init_schema.js',
    'lib/modules/indexes/init_class.js'
  ], 'server');

  // EJSON module.
  api.addFiles('lib/modules/ejson/init_module.js', ['client', 'server']);

  // Methods module.
  api.addFiles([
    'lib/modules/methods/init_definition.js',
    'lib/modules/methods/init_schema.js',
    'lib/modules/methods/init_class.js'
  ], ['client', 'server']);

  // Fields module.
  api.addFiles([
    'lib/modules/fields/global.js',
    'lib/modules/fields/create_type.js',
    'lib/modules/fields/base_field.js',
    'lib/modules/fields/types/null_field.js',
    'lib/modules/fields/types/string_field.js',
    'lib/modules/fields/types/number_field.js',
    'lib/modules/fields/types/boolean_field.js',
    'lib/modules/fields/types/date_field.js',
    'lib/modules/fields/types/object_field.js',
    'lib/modules/fields/types/array_field.js',
    'lib/modules/fields/utils.js',
    'lib/modules/fields/modifiers.js',
    'lib/modules/fields/set_default.js',
    'lib/modules/fields/set.js',
    'lib/modules/fields/get.js',
    'lib/modules/fields/push.js',
    'lib/modules/fields/pop.js',
    'lib/modules/fields/inc.js',
    'lib/modules/fields/modified.js',
    'lib/modules/fields/ejson.js',
    'lib/modules/fields/init_definition.js',
    'lib/modules/fields/init_schema.js',
    'lib/modules/fields/init_class.js'
  ], ['client', 'server']);

  // Storage module.
  api.addFiles([
    'lib/modules/storage/init_schema.js',
    'lib/modules/storage/init_class.js'
  ], ['client', 'server']);

  api.export(['Astro', 'Astronomy'], ['client', 'server']);
});

Package.onTest(function(api) {
  api.use([
    'tinytest',
    'insecure',
    'jagi:astronomy',
    'jagi:astronomy-timestamp-behavior',
    'jagi:astronomy-slug-behavior',
    'jagi:astronomy-softremove-behavior',
    'jagi:astronomy-validators',
    'jagi:astronomy-simple-validators'
  ]);

  api.addFiles('test/utils.js', ['client', 'server']);
  // Core.
  api.addFiles([
    'test/core/core_transform.js',
    'test/core/core_inheritance.js',
    'test/core/core_extend.js',
    'test/core/core_state.js'
  ], ['client', 'server']);
  // Storage
  api.addFiles([
    'test/storage/storage_init.js',
    'test/storage/storage_insert.js',
    'test/storage/storage_update.js',
    'test/storage/storage_remove.js',
    'test/storage/storage_reload.js',
    'test/storage/storage_cloning.js',
    'test/storage/storage_direct_insert.js',
    'test/storage/storage_direct_update.js',
    'test/storage/storage_direct_upsert.js',
    'test/storage/storage_direct_remove.js'
  ], ['client', 'server']);
  // EJSON.
  api.addFiles([
    'test/ejson/ejson_parsing.js'
  ], ['client', 'server']);
  // Events.
  api.addFiles([
    'test/events/events_order.js',
    'test/events/events_propagation.js',
    'test/events/events_prevent_default.js'
  ], ['client', 'server']);
  // Fields.
  api.addFiles([
    'test/fields/fields_definition.js',
    'test/fields/fields_default.js',
    'test/fields/fields_casting.js',
    'test/fields/fields_set.js',
    'test/fields/fields_get.js',
    'test/fields/fields_push.js',
    'test/fields/fields_pop.js',
    'test/fields/fields_inc.js',
    'test/fields/fields_modified.js',
    'test/fields/fields_immutable.js',
    'test/fields/fields_transient.js'
  ], ['client', 'server']);
  // Indexes.
  api.addFiles([
    'test/indexes/indexes_definition.js'
  ], 'server');
  // Methods.
  api.addFiles([
    'test/methods/methods_definition.js'
  ], ['client', 'server']);
  // Modules.
  api.addFiles([
    // Validators
    'test/modules/validators_validate_single.js',
    'test/modules/validators_validate_multiple.js',
    'test/modules/validators_order.js',
    // Simple Validators.
    'test/modules/simple_validators_parser.js'
  ], ['client', 'server']);
  // Behaviors.
  api.addFiles([
    'test/behaviors/behaviors_timestamp.js',
    'test/behaviors/behaviors_slug.js',
    'test/behaviors/behaviors_softremove.js'
  ], ['client', 'server']);
});
<|endoftext|>


<commit_before>/*
 * benc2json
 * https://github.com/pwmckenna/benc2json
 *
 * Copyright (c) 2013 Patrick Williams
 * Licensed under the MIT license.
 */
var express = require('express');
var Firebase = require('./firebase-node');
var http = require('http');
var URL = require('url');
var q = require('q');
var request = require('request');
var URL = require('url');

var MAGNET_LINK_IDENTIFIER = 'magnet:?xt=urn:btih:';
var firebase = new Firebase('https://todium.firebaseio.com/');

var addFirebaseTracker = function(firebase, id, info_hash, src) {
    console.log('addFirebaseTracker', id, info_hash, src);

    var campaignTracker = firebase.child('campaigns').child(id).child('trackers').push();
    var globalTracker = firebase.child('trackers').push();
    globalTracker.set({
        campaign: id,
        info_hash: info_hash,
        stats: {
            completed: 0,
            transferred: 0,
        },
        src: src,
        time: new Date().getTime()
    });
    campaignTracker.set(globalTracker.name());
    return globalTracker;
}

var addFirebaseTorrent = function(firebase, id, tracker, torrent) {
    var file = URL.parse(torrent).pathname;
    file = file.substring(file.lastIndexOf('/'));
    var shortened = firebase.child('torrent').push({
        tracker: tracker,
        torrent: torrent,
        campaign: id
    });
    return 'http://torrent.todium.com/' + shortened.name() + '.torrent';
}

var addLinkRequest = function(firebase, id, src) {
    console.log('addLinkRequest', id, src);

    var ret = new q.defer();
    if(src.match(/[0-9A-Fa-f]{40}/)) {
        var info_hash = src;
        var tracker = addFirebaseTracker(firebase, id, info_hash, MAGNET_LINK_IDENTIFIER + info_hash);
        var url = 'http://tracker.todium.com/' + tracker.name() + '/announce';
        var trackable = MAGNET_LINK_IDENTIFIER + info_hash + '&tr=' + url;
        tracker.child('trackable').set(trackable);
        ret.resolve(url);
    } else if(src.indexOf(MAGNET_LINK_IDENTIFIER) === 0) {
        console.log('replacing magnet link');
        var info_hash = src.substr(MAGNET_LINK_IDENTIFIER.length, 40);
        var tracker = addFirebaseTracker(firebase, id, info_hash, src);
        var url = 'http://tracker.todium.com/' + tracker.name() + '/announce';
        var trackable = src + '&tr=' + url;
        tracker.child('trackable').set(trackable);
        ret.resolve(trackable);
    } else {
        console.log('replacing torrent file', src);
        request.get({
            url: 'http://hasher.todium.com',
            qs: {
                torrent: src
            },
            json: true
        }, function (error, response, info_hash) {
            console.log(error, response.statusCode, info_hash);
            if(error || typeof info_hash !== 'string' || info_hash.length !== 40) {
                ret.reject(error);
                return;
            } else {
                var tracker = addFirebaseTracker(firebase, id, info_hash, src);
                var url = 'http://tracker.todium.com/' + tracker.name() + '/announce';
                var trackable = addFirebaseTorrent(firebase, id, url, src);
                tracker.child('trackable').set(trackable);
                ret.resolve(trackable);
            }
        });
    }
    return ret.promise;
};

var authenticationRequest = function(id, secret) {
    console.log('authenticationRequest', id, secret);
    var ret = new q.defer();
    firebase.child('campaigns').child(id).child('secret').once('value', function(secretSnapshot) {
        if(secretSnapshot.val() !== secret) {
            var error = 'invalid campaign secret';
            console.error(error);
            return ret.reject(error);
        } else {
            return ret.resolve();
        }
    });
    return ret.promise;
};

var port = process.env.PORT || 5051;
console.log('port', port);
var app = express();
app.use(express.bodyParser());
var handlePost = function(req, res) {
    var abort = function(err) {
        res.send(400, err);
    };

    // if we don't have a url argument, then lets bail
    if(!req.body.hasOwnProperty('id') ||
        !req.body.hasOwnProperty('secret') ||
        !req.body.hasOwnProperty('src')
    ) {
        abort('src/id/secret mandatory');
        return;
    }
    var id = req.body['id'];
    var secret = req.body['secret'];
    var src = req.body['src'];

    console.log('id', id);
    console.log('secret', secret);
    console.log('src', src);

    authenticationRequest(id, secret).then(function() {
        addLinkRequest(firebase, id, src).then(function(link) {
            res.send(200, link);
        }, abort);
    }, abort);
};
app.post('/', handlePost).post('/tracker', handlePost).listen(port, function() {
    console.log('Listening on ' + port);
});<commit_msg>re-enabling cors<commit_after>/*
 * benc2json
 * https://github.com/pwmckenna/benc2json
 *
 * Copyright (c) 2013 Patrick Williams
 * Licensed under the MIT license.
 */
var express = require('express');
var Firebase = require('./firebase-node');
var http = require('http');
var URL = require('url');
var q = require('q');
var request = require('request');
var URL = require('url');

var MAGNET_LINK_IDENTIFIER = 'magnet:?xt=urn:btih:';
var firebase = new Firebase('https://todium.firebaseio.com/');

var addFirebaseTracker = function(firebase, id, info_hash, src) {
    console.log('addFirebaseTracker', id, info_hash, src);

    var campaignTracker = firebase.child('campaigns').child(id).child('trackers').push();
    var globalTracker = firebase.child('trackers').push();
    globalTracker.set({
        campaign: id,
        info_hash: info_hash,
        stats: {
            completed: 0,
            transferred: 0,
        },
        src: src,
        time: new Date().getTime()
    });
    campaignTracker.set(globalTracker.name());
    return globalTracker;
}

var addFirebaseTorrent = function(firebase, id, tracker, torrent) {
    var file = URL.parse(torrent).pathname;
    file = file.substring(file.lastIndexOf('/'));
    var shortened = firebase.child('torrent').push({
        tracker: tracker,
        torrent: torrent,
        campaign: id
    });
    return 'http://torrent.todium.com/' + shortened.name() + '.torrent';
}

var addLinkRequest = function(firebase, id, src) {
    console.log('addLinkRequest', id, src);

    var ret = new q.defer();
    if(src.match(/[0-9A-Fa-f]{40}/)) {
        var info_hash = src;
        var tracker = addFirebaseTracker(firebase, id, info_hash, MAGNET_LINK_IDENTIFIER + info_hash);
        var url = 'http://tracker.todium.com/' + tracker.name() + '/announce';
        var trackable = MAGNET_LINK_IDENTIFIER + info_hash + '&tr=' + url;
        tracker.child('trackable').set(trackable);
        ret.resolve(url);
    } else if(src.indexOf(MAGNET_LINK_IDENTIFIER) === 0) {
        console.log('replacing magnet link');
        var info_hash = src.substr(MAGNET_LINK_IDENTIFIER.length, 40);
        var tracker = addFirebaseTracker(firebase, id, info_hash, src);
        var url = 'http://tracker.todium.com/' + tracker.name() + '/announce';
        var trackable = src + '&tr=' + url;
        tracker.child('trackable').set(trackable);
        ret.resolve(trackable);
    } else {
        console.log('replacing torrent file', src);
        request.get({
            url: 'http://hasher.todium.com',
            qs: {
                torrent: src
            },
            json: true
        }, function (error, response, info_hash) {
            console.log(error, response.statusCode, info_hash);
            if(error || typeof info_hash !== 'string' || info_hash.length !== 40) {
                ret.reject(error);
                return;
            } else {
                var tracker = addFirebaseTracker(firebase, id, info_hash, src);
                var url = 'http://tracker.todium.com/' + tracker.name() + '/announce';
                var trackable = addFirebaseTorrent(firebase, id, url, src);
                tracker.child('trackable').set(trackable);
                ret.resolve(trackable);
            }
        });
    }
    return ret.promise;
};

var authenticationRequest = function(id, secret) {
    console.log('authenticationRequest', id, secret);
    var ret = new q.defer();
    firebase.child('campaigns').child(id).child('secret').once('value', function(secretSnapshot) {
        if(secretSnapshot.val() !== secret) {
            var error = 'invalid campaign secret';
            console.error(error);
            return ret.reject(error);
        } else {
            return ret.resolve();
        }
    });
    return ret.promise;
};

var port = process.env.PORT || 5051;
console.log('port', port);
var app = express();
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
      res.send(200);
    }
    else {
      next();
    }
});
app.use(express.bodyParser());
var handlePost = function(req, res) {
    var abort = function(err) {
        res.send(400, err);
    };

    // if we don't have a url argument, then lets bail
    if(!req.body.hasOwnProperty('id') ||
        !req.body.hasOwnProperty('secret') ||
        !req.body.hasOwnProperty('src')
    ) {
        abort('src/id/secret mandatory');
        return;
    }
    var id = req.body['id'];
    var secret = req.body['secret'];
    var src = req.body['src'];

    console.log('id', id);
    console.log('secret', secret);
    console.log('src', src);

    authenticationRequest(id, secret).then(function() {
        addLinkRequest(firebase, id, src).then(function(link) {
            res.send(200, link);
        }, abort);
    }, abort);
};
app.post('/', handlePost).post('/tracker', handlePost).listen(port, function() {
    console.log('Listening on ' + port);
});<|endoftext|>


<commit_before>Package.describe({
	name: 'jkuester:meteor-collection-factory',
	version: '0.1.5',
	// Brief, one-line summary of the package.
	summary: 'Factory for creating Mongo.Collection instances.',
	// URL to the Git repository containing the source code for this package.
	git: 'https://github.com/jankapunkt/meteor-collection-factory.git',
	// By default, Meteor will default to using README.md for documentation.
	// To avoid submitting documentation, set this field to null.
	documentation: 'README.md'
});

Package.onUse(function (api) {
	api.versionsFrom('1.5');
	api.use('ecmascript');
	api.use('mongo');
	api.use('dburles:collection-helpers@1.1.0');
	api.use('aldeed:collection2-core@2.0.1');
	api.use("tmeasday:check-npm-versions@0.3.1");
	api.use('dburles:mongo-collection-instances@0.3.5');
	api.mainModule('meteor-collection-factory.js');
});

<commit_msg>version 0.1.6<commit_after>Package.describe({
	name: 'jkuester:meteor-collection-factory',
	version: '0.1.6',
	// Brief, one-line summary of the package.
	summary: 'Factory for creating Mongo.Collection instances.',
	// URL to the Git repository containing the source code for this package.
	git: 'https://github.com/jankapunkt/meteor-collection-factory.git',
	// By default, Meteor will default to using README.md for documentation.
	// To avoid submitting documentation, set this field to null.
	documentation: 'README.md'
});

Package.onUse(function (api) {
	api.versionsFrom('1.5');
	api.use('ecmascript');
	api.use('mongo');
	api.use('dburles:collection-helpers@1.1.0');
	api.use('aldeed:collection2-core@2.0.1');
	api.use("tmeasday:check-npm-versions@0.3.1");
	api.use('dburles:mongo-collection-instances@0.3.5');
	api.mainModule('meteor-collection-factory.js');
});

<|endoftext|>


<commit_before>'use strict';
var _ = require('lodash');
const h = require('highland');
var minimist = require('minimist');
var File = require('vinyl');
var streamFromRecipe = require('./streamFromRecipe');
var server = require('./server');

var createDest = function(res) {
  var dest = function(glob, opt) {
    opt = opt || {};

    return h()
    .doto(_file => {

      /**
       * Gulp is using an older version of Vinyl so wrap our file object
       * with the latest version:
       *
       * (The File object doesn't copy custom properties so we need to
       * do it.)
       */

      var file = new File(_file);

      file.meta = _file.meta;

      /**
       * Combine any options passed here with options on the file itself,
       * giving priority to the options passed in:
       */

      _.merge({}, file.meta, opt);

      /**
       * If we can get a content type from the file name then use that,
       * otherwise see if one is set in the meta property:
       */

      /**
       * [TODO] The sequence should probably be:
       *
       *  - use opt first;
       *  - then use the file's name;
       *  - and then finally use the file's meta.
       */

      if (file.path && file.extname) {
        res.type(file.extname);
      } else if (opt['content-type']) {
        res.set('Content-Type', opt['content-type']);
      }
      res.send(file.contents);
    });
  };

  return dest;
}

var createApi = function(recipes, connections, codecs, channels) {

  /**
   * We need the parameter so that Gulp knows that the task is not finished:
   */

  return function(cb) {

    /**
     * Grab any command-line arguments and launch a server:
     */

    var knownOptions = {
      string: 'port',
      boolean: 'cors.enabled',
      boolean: 'cors.origin',
      boolean: 'cors.credentials',
      default: {
        port: process.env.PORT || 3000,
        'cors.enabled': process.env.CORS_ENABLED === 'true',
        'cors.origin': process.env.CORS_ORIGIN === 'true' || process.env.CORS_ORIGIN,
        'cors.credentials': process.env.CORS_CREDENTIALS === 'true'
      }
    };
    var options = minimist(process.argv.slice(2), knownOptions);
    var api = server(options);

    /**
     * Create endpoints that correspond to each of the recipes:
     */

    recipes.forEach(function(recipe) {
      var r = _.cloneDeep(recipe);

      /**
       * Only turn the task into an endpoint if it's not scheduled:
       */

      if (!r.input.schedule) {
        r.output.channel = 'api';
      }

      /**
       * Run the recipe, passing in the request query parameters as input
       * options:
       */

      var handleTask = function(req, res) {
        channels.api = {dest: createDest(res)};

        return streamFromRecipe(r, connections, codecs, channels, req.query);
      };

      var taskName = recipe.name;

      api.app.get('/' + (taskName === 'default' ? '' : taskName), handleTask);
      api.app.post('/' + (taskName === 'default' ? '' : taskName), handleTask);
    });
    return api;
  };
};

module.exports = createApi;
<commit_msg>ensure check for schedule parameter doesn't cause fail<commit_after>'use strict';
var _ = require('lodash');
const h = require('highland');
var minimist = require('minimist');
var File = require('vinyl');
var streamFromRecipe = require('./streamFromRecipe');
var server = require('./server');

var createDest = function(res) {
  var dest = function(glob, opt) {
    opt = opt || {};

    return h()
    .doto(_file => {

      /**
       * Gulp is using an older version of Vinyl so wrap our file object
       * with the latest version:
       *
       * (The File object doesn't copy custom properties so we need to
       * do it.)
       */

      var file = new File(_file);

      file.meta = _file.meta;

      /**
       * Combine any options passed here with options on the file itself,
       * giving priority to the options passed in:
       */

      _.merge({}, file.meta, opt);

      /**
       * If we can get a content type from the file name then use that,
       * otherwise see if one is set in the meta property:
       */

      /**
       * [TODO] The sequence should probably be:
       *
       *  - use opt first;
       *  - then use the file's name;
       *  - and then finally use the file's meta.
       */

      if (file.path && file.extname) {
        res.type(file.extname);
      } else if (opt['content-type']) {
        res.set('Content-Type', opt['content-type']);
      }
      res.send(file.contents);
    });
  };

  return dest;
}

var createApi = function(recipes, connections, codecs, channels) {

  /**
   * We need the parameter so that Gulp knows that the task is not finished:
   */

  return function(cb) {

    /**
     * Grab any command-line arguments and launch a server:
     */

    var knownOptions = {
      string: 'port',
      boolean: 'cors.enabled',
      boolean: 'cors.origin',
      boolean: 'cors.credentials',
      default: {
        port: process.env.PORT || 3000,
        'cors.enabled': process.env.CORS_ENABLED === 'true',
        'cors.origin': process.env.CORS_ORIGIN === 'true' || process.env.CORS_ORIGIN,
        'cors.credentials': process.env.CORS_CREDENTIALS === 'true'
      }
    };
    var options = minimist(process.argv.slice(2), knownOptions);
    var api = server(options);

    /**
     * Create endpoints that correspond to each of the recipes:
     */

    recipes.forEach(function(recipe) {
      var r = _.cloneDeep(recipe);

      /**
       * Only turn the task into an endpoint if it's not scheduled:
       */

      if (!(r.input && r.input.schedule)) {
        r.output.channel = 'api';
      }

      /**
       * Run the recipe, passing in the request query parameters as input
       * options:
       */

      var handleTask = function(req, res) {
        channels.api = {dest: createDest(res)};

        return streamFromRecipe(r, connections, codecs, channels, req.query);
      };

      var taskName = recipe.name;

      api.app.get('/' + (taskName === 'default' ? '' : taskName), handleTask);
      api.app.post('/' + (taskName === 'default' ? '' : taskName), handleTask);
    });
    return api;
  };
};

module.exports = createApi;
<|endoftext|>


<commit_before>Package.describe({
  name: 'remcoder:chronos',
  summary: 'A reactive timer and wrapper for momentjs to write time-dependent updates in a Meteoric way. ',
  version: '0.2.1',
  git: 'https://github.com/remcoder/chronos'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0');
  api.use('reactive-var');
  api.export('Chronos');
  api.addFiles('remcoder:chronos.js');
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('reactive-var');
  api.export('Chronos');
  api.addFiles('remcoder:chronos.js');
  api.addFiles('unittests.js');
});
<commit_msg>bump version<commit_after>Package.describe({
  name: 'remcoder:chronos',
  summary: 'A reactive timer and wrapper for momentjs to write time-dependent updates in a Meteoric way. ',
  version: '0.2.2',
  git: 'https://github.com/remcoder/chronos'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0');
  api.use('reactive-var');
  api.export('Chronos');
  api.addFiles('remcoder:chronos.js');
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('reactive-var');
  api.export('Chronos');
  api.addFiles('remcoder:chronos.js');
  api.addFiles('unittests.js');
});
<|endoftext|>


<commit_before>function Api (app) {
  this.app = app
}

Api.prototype.initialize = function () {
  var self = this
  return this.load(self.app).then(function (api) {
    self.api = api
    self.addRenderProcessApis(api.render)
    self.addMainProcessApis(api.main)
    self.addBrowserWindowApis(api.browserWindow)
    self.addWebContentsApis(api.webContents)
    self.addProcessApis(api.process)
    self.addClientProperties()
  })
}

Api.prototype.load = function (app) {
  return app.client.execute(function () {
    var electron = require('electron')

    var api = {
      browserWindow: {},
      main: {},
      process: {},
      render: {},
      webContents: {}
    }

    function ignoreModule (moduleName) {
      switch (moduleName) {
        case 'CallbacksRegistry':
        case 'deprecate':
        case 'deprecations':
        case 'hideInternalModules':
          return true
      }
      return false
    }

    function ignoreApi (apiName) {
      switch (apiName) {
        case 'prototype':
          return true
        default:
          return apiName[0] === '_'
      }
    }

    function addModule (parent, parentName, name, api) {
      api[name] = {}
      Object.getOwnPropertyNames(parent[name]).forEach(function (key) {
        if (ignoreApi(key)) return
        var value = parent[name][key]
        api[name][key] = parentName + '.' + name + '.' + key
      })
    }

    function addRenderProcessModules () {
      Object.getOwnPropertyNames(electron).forEach(function (key) {
        if (ignoreModule(key)) return
        if (key === 'remote') return
        addModule(electron, 'electron', key, api.render)
      })
    }

    function addMainProcessModules () {
      Object.getOwnPropertyNames(electron.remote).forEach(function (key) {
        if (ignoreModule(key)) return
        addModule(electron.remote, 'electron.remote', key, api.main)
      })
      addModule(electron.remote, 'electron.remote', 'process', api.main)
    }

    function addBrowserWindow () {
      var currentWindow = electron.remote.getCurrentWindow()
      for (var name in currentWindow) {
        var value = currentWindow[name]
        if (typeof value === 'function') {
          api.browserWindow[name] = 'browserWindow.' + name
        }
      }
    }

    function addWebContents () {
      var webContents = electron.remote.getCurrentWebContents()
      for (var name in webContents) {
        var value = webContents[name]
        if (typeof value === 'function') {
          api.webContents[name] = 'webContents.' + name
        }
      }
    }

    function addProcess () {
      for (var name in process) {
        if (ignoreApi(name)) continue
        api.process[name] = 'process.' + name
      }
    }

    addRenderProcessModules()
    addMainProcessModules()
    addBrowserWindow()
    addWebContents()
    addProcess()

    return api
  }).then(getResponseValue)
}

Api.prototype.addClientProperty = function (name) {
  var self = this
  var clientPrototype = Object.getPrototypeOf(self.app.client)

  Object.defineProperty(clientPrototype, name, {
    get: function () {
      var api = {}
      var client = this
      Object.keys(self.app[name]).forEach(function (key) {
        api[key] = client[self.api[name][key]].bind(client)
      })
      return api
    }
  })
}

Api.prototype.addClientProperties = function () {
  Object.getPrototypeOf(this.app.client).electron = this.app.electron
  this.addClientProperty('browserWindow')
  this.addClientProperty('webContents')
  this.addClientProperty('process')

}

Api.prototype.addRenderProcessApis = function (api) {
  var app = this.app
  var electron = {}
  app.electron = electron

  Object.keys(api).forEach(function (moduleName) {
    electron[moduleName] = {}
    var moduleApi = api[moduleName]

    Object.keys(moduleApi).forEach(function (key) {
      var commandName = moduleApi[key]

      app.client.addCommand(commandName, function () {
        var args = Array.prototype.slice.call(arguments)
        return this.execute(callRenderApi, moduleName, key, args).then(getResponseValue)
      })

      electron[moduleName][key] = function () {
        return app.client[commandName].apply(app.client, arguments)
      }
    })
  })
}

Api.prototype.addMainProcessApis = function (api) {
  var app = this.app
  var remote = {}
  app.electron.remote = remote

  Object.keys(api).forEach(function (moduleName) {
    remote[moduleName] = {}
    var moduleApi = api[moduleName]

    Object.keys(moduleApi).forEach(function (key) {
      var commandName = moduleApi[key]

      app.client.addCommand(commandName, function () {
        var args = Array.prototype.slice.call(arguments)
        return this.execute(callMainApi, moduleName, key, args).then(getResponseValue)
      })

      remote[moduleName][key] = function () {
        return app.client[commandName].apply(app.client, arguments)
      }
    })
  })
}

Api.prototype.addBrowserWindowApis = function (api) {
  var app = this.app
  app.browserWindow = {}

  Object.keys(api).forEach(function (name) {
    var commandName = api[name]

    app.client.addCommand(commandName, function () {
      var args = Array.prototype.slice.call(arguments)
      return this.execute(callBrowserWindowApi, name, args).then(getResponseValue)
    })

    app.browserWindow[name] = function () {
      return app.client[commandName].apply(app.client, arguments)
    }
  })
}

Api.prototype.addWebContentsApis = function (api) {
  var app = this.app
  app.webContents = {}

  Object.keys(api).forEach(function (name) {
    var commandName = api[name]

    app.client.addCommand(commandName, function () {
      var args = Array.prototype.slice.call(arguments)
      return this.execute(callWebContentsApi, name, args).then(getResponseValue)
    })

    app.webContents[name] = function () {
      return app.client[commandName].apply(app.client, arguments)
    }
  })
}

Api.prototype.addProcessApis = function (api) {
  var app = this.app
  app.process = {}

  Object.keys(api).forEach(function (name) {
    var commandName = api[name]

    app.client.addCommand(commandName, function () {
      var args = Array.prototype.slice.call(arguments)
      return this.execute(callProcessApi, name, args).then(getResponseValue)
    })

    app.process[name] = function () {
      return app.client[commandName].apply(app.client, arguments)
    }
  })
}

Api.prototype.transferPromiseness = function (target, promise) {
  this.app.client.transferPromiseness(target, promise)

  var addProperties = function (source, target, moduleName) {
    var api = source[moduleName]
    target[moduleName] = {}
    Object.keys(api).forEach(function (name) {
      target[moduleName][name] = api[name].bind(source)
    })
  }

  addProperties(promise, target, 'webContents')
  addProperties(promise, target, 'browserWindow')

  target.electron = {}
  Object.keys(promise.electron).forEach(function (moduleName) {
    if (moduleName === 'remote') return
    addProperties(promise.electron, target.electron, moduleName)
  })

  target.electron.remote = {}
  Object.keys(promise.electron.remote).forEach(function (moduleName) {
    addProperties(promise.electron.remote, target.electron.remote, moduleName)
  })
}

function callRenderApi (moduleName, api, args) {
  var module = require('electron')[moduleName]
  if (typeof module[api] === 'function') {
    return module[api].apply(module, args)
  } else {
    return module[api]
  }
}

function callMainApi (moduleName, api, args) {
  var module = require('electron').remote[moduleName]
  if (typeof module[api] === 'function') {
    return module[api].apply(module, args)
  } else {
    return module[api]
  }
}

function callWebContentsApi (name, args) {
  var webContents = require('electron').remote.getCurrentWebContents()
  return webContents[name].apply(webContents, args)
}

function callBrowserWindowApi (name, args) {
  var window = require('electron').remote.getCurrentWindow()
  return window[name].apply(window, args)
}

function callProcessApi (name, args) {
  if (typeof process[name] === 'function') {
    return process[name].apply(process, args)
  } else {
    return process[name]
  }
}

function getResponseValue (response) {
  return response.value
}

module.exports = Api
<commit_msg>:art:<commit_after>function Api (app) {
  this.app = app
}

Api.prototype.initialize = function () {
  var self = this
  return this.load(self.app).then(function (api) {
    self.api = api
    self.addRenderProcessApis(api.render)
    self.addMainProcessApis(api.main)
    self.addBrowserWindowApis(api.browserWindow)
    self.addWebContentsApis(api.webContents)
    self.addProcessApis(api.process)
    self.addClientProperties()
  })
}

Api.prototype.load = function (app) {
  return app.client.execute(function () {
    var electron = require('electron')

    var api = {
      browserWindow: {},
      main: {},
      process: {},
      render: {},
      webContents: {}
    }

    function ignoreModule (moduleName) {
      switch (moduleName) {
        case 'CallbacksRegistry':
        case 'deprecate':
        case 'deprecations':
        case 'hideInternalModules':
          return true
      }
      return false
    }

    function ignoreApi (apiName) {
      switch (apiName) {
        case 'prototype':
          return true
        default:
          return apiName[0] === '_'
      }
    }

    function addModule (parent, parentName, name, api) {
      api[name] = {}
      Object.getOwnPropertyNames(parent[name]).forEach(function (key) {
        if (ignoreApi(key)) return
        var value = parent[name][key]
        api[name][key] = parentName + '.' + name + '.' + key
      })
    }

    function addRenderProcessModules () {
      Object.getOwnPropertyNames(electron).forEach(function (key) {
        if (ignoreModule(key)) return
        if (key === 'remote') return
        addModule(electron, 'electron', key, api.render)
      })
    }

    function addMainProcessModules () {
      Object.getOwnPropertyNames(electron.remote).forEach(function (key) {
        if (ignoreModule(key)) return
        addModule(electron.remote, 'electron.remote', key, api.main)
      })
      addModule(electron.remote, 'electron.remote', 'process', api.main)
    }

    function addBrowserWindow () {
      var currentWindow = electron.remote.getCurrentWindow()
      for (var name in currentWindow) {
        var value = currentWindow[name]
        if (typeof value === 'function') {
          api.browserWindow[name] = 'browserWindow.' + name
        }
      }
    }

    function addWebContents () {
      var webContents = electron.remote.getCurrentWebContents()
      for (var name in webContents) {
        var value = webContents[name]
        if (typeof value === 'function') {
          api.webContents[name] = 'webContents.' + name
        }
      }
    }

    function addProcess () {
      for (var name in process) {
        if (ignoreApi(name)) continue
        api.process[name] = 'process.' + name
      }
    }

    addRenderProcessModules()
    addMainProcessModules()
    addBrowserWindow()
    addWebContents()
    addProcess()

    return api
  }).then(getResponseValue)
}

Api.prototype.addClientProperty = function (name) {
  var self = this
  var clientPrototype = Object.getPrototypeOf(self.app.client)

  Object.defineProperty(clientPrototype, name, {
    get: function () {
      var api = {}
      var client = this
      Object.keys(self.app[name]).forEach(function (key) {
        api[key] = client[self.api[name][key]].bind(client)
      })
      return api
    }
  })
}

Api.prototype.addClientProperties = function () {
  Object.getPrototypeOf(this.app.client).electron = this.app.electron
  this.addClientProperty('browserWindow')
  this.addClientProperty('webContents')
  this.addClientProperty('process')
}

Api.prototype.addRenderProcessApis = function (api) {
  var app = this.app
  var electron = {}
  app.electron = electron

  Object.keys(api).forEach(function (moduleName) {
    electron[moduleName] = {}
    var moduleApi = api[moduleName]

    Object.keys(moduleApi).forEach(function (key) {
      var commandName = moduleApi[key]

      app.client.addCommand(commandName, function () {
        var args = Array.prototype.slice.call(arguments)
        return this.execute(callRenderApi, moduleName, key, args).then(getResponseValue)
      })

      electron[moduleName][key] = function () {
        return app.client[commandName].apply(app.client, arguments)
      }
    })
  })
}

Api.prototype.addMainProcessApis = function (api) {
  var app = this.app
  var remote = {}
  app.electron.remote = remote

  Object.keys(api).forEach(function (moduleName) {
    remote[moduleName] = {}
    var moduleApi = api[moduleName]

    Object.keys(moduleApi).forEach(function (key) {
      var commandName = moduleApi[key]

      app.client.addCommand(commandName, function () {
        var args = Array.prototype.slice.call(arguments)
        return this.execute(callMainApi, moduleName, key, args).then(getResponseValue)
      })

      remote[moduleName][key] = function () {
        return app.client[commandName].apply(app.client, arguments)
      }
    })
  })
}

Api.prototype.addBrowserWindowApis = function (api) {
  var app = this.app
  app.browserWindow = {}

  Object.keys(api).forEach(function (name) {
    var commandName = api[name]

    app.client.addCommand(commandName, function () {
      var args = Array.prototype.slice.call(arguments)
      return this.execute(callBrowserWindowApi, name, args).then(getResponseValue)
    })

    app.browserWindow[name] = function () {
      return app.client[commandName].apply(app.client, arguments)
    }
  })
}

Api.prototype.addWebContentsApis = function (api) {
  var app = this.app
  app.webContents = {}

  Object.keys(api).forEach(function (name) {
    var commandName = api[name]

    app.client.addCommand(commandName, function () {
      var args = Array.prototype.slice.call(arguments)
      return this.execute(callWebContentsApi, name, args).then(getResponseValue)
    })

    app.webContents[name] = function () {
      return app.client[commandName].apply(app.client, arguments)
    }
  })
}

Api.prototype.addProcessApis = function (api) {
  var app = this.app
  app.process = {}

  Object.keys(api).forEach(function (name) {
    var commandName = api[name]

    app.client.addCommand(commandName, function () {
      var args = Array.prototype.slice.call(arguments)
      return this.execute(callProcessApi, name, args).then(getResponseValue)
    })

    app.process[name] = function () {
      return app.client[commandName].apply(app.client, arguments)
    }
  })
}

Api.prototype.transferPromiseness = function (target, promise) {
  this.app.client.transferPromiseness(target, promise)

  var addProperties = function (source, target, moduleName) {
    var api = source[moduleName]
    target[moduleName] = {}
    Object.keys(api).forEach(function (name) {
      target[moduleName][name] = api[name].bind(source)
    })
  }

  addProperties(promise, target, 'webContents')
  addProperties(promise, target, 'browserWindow')

  target.electron = {}
  Object.keys(promise.electron).forEach(function (moduleName) {
    if (moduleName === 'remote') return
    addProperties(promise.electron, target.electron, moduleName)
  })

  target.electron.remote = {}
  Object.keys(promise.electron.remote).forEach(function (moduleName) {
    addProperties(promise.electron.remote, target.electron.remote, moduleName)
  })
}

function callRenderApi (moduleName, api, args) {
  var module = require('electron')[moduleName]
  if (typeof module[api] === 'function') {
    return module[api].apply(module, args)
  } else {
    return module[api]
  }
}

function callMainApi (moduleName, api, args) {
  var module = require('electron').remote[moduleName]
  if (typeof module[api] === 'function') {
    return module[api].apply(module, args)
  } else {
    return module[api]
  }
}

function callWebContentsApi (name, args) {
  var webContents = require('electron').remote.getCurrentWebContents()
  return webContents[name].apply(webContents, args)
}

function callBrowserWindowApi (name, args) {
  var window = require('electron').remote.getCurrentWindow()
  return window[name].apply(window, args)
}

function callProcessApi (name, args) {
  if (typeof process[name] === 'function') {
    return process[name].apply(process, args)
  } else {
    return process[name]
  }
}

function getResponseValue (response) {
  return response.value
}

module.exports = Api
<|endoftext|>


<commit_before>Package.describe({
  name: 'arkham:comments-ui',
  summary: 'Simple templates for disqus-like comment functionality',
  version: '0.2.13',
  git: 'https://github.com/ARKHAM-Enterprises/meteor-comments-ui.git'
});

Package.onUse(function(api) {
  // Meteor Version
  api.versionsFrom('METEOR@1.0.1');

  // Meteor Core Dependencies
  api.use(['accounts-password@1.0.1'], { weak: true });
  api.use([
    'underscore', 'mongo-livedata', 'templating', 'jquery', 'check', 'less@2.5.0_2', 'tracker', 'check', 'session', 'random', 'markdown'
  ]);

  // Atmosphere Package Dependencies
  api.use([
    'aldeed:collection2@2.5.0', 'aldeed:simple-schema@1.3.3', 'dburles:collection-helpers@1.0.3',
    'momentjs:moment@2.10.6', 'rzymek:moment-locales@2.9.0', 'utilities:avatar@0.9.1', 'reywood:publish-composite@1.4.2',
    'aldeed:template-extension@3.4.3'
  ]);

  // Package specific globals and files
  api.addFiles('lib/model.js');
  api.addFiles(['lib/templates.html', 'lib/templates/commentsBox.less']);
  api.addFiles(['lib/ui.js', 'lib/templates/commentsBox.js'], 'client');
  api.export('Comments');
});

Package.onTest(function(api) {
  api.use(['tinytest', 'accounts-password']);
  api.use('arkham:comments-ui');

  api.addFiles('tests/api-tests.js');
  api.addFiles('tests/ui-tests.js', 'client');
});
<commit_msg>Update to v0.2.14 with markdown functionality<commit_after>Package.describe({
  name: 'arkham:comments-ui',
  summary: 'Simple templates for disqus-like comment functionality',
  version: '0.2.14',
  git: 'https://github.com/ARKHAM-Enterprises/meteor-comments-ui.git'
});

Package.onUse(function(api) {
  // Meteor Version
  api.versionsFrom('METEOR@1.0.1');

  // Meteor Core Dependencies
  api.use(['accounts-password@1.0.1'], { weak: true });
  api.use([
    'underscore', 'mongo-livedata', 'templating', 'jquery', 'check', 'less@2.5.0_2', 'tracker', 'check', 'session', 'random', 'markdown'
  ]);

  // Atmosphere Package Dependencies
  api.use([
    'aldeed:collection2@2.5.0', 'aldeed:simple-schema@1.3.3', 'dburles:collection-helpers@1.0.3',
    'momentjs:moment@2.10.6', 'rzymek:moment-locales@2.9.0', 'utilities:avatar@0.9.1', 'reywood:publish-composite@1.4.2',
    'aldeed:template-extension@3.4.3'
  ]);

  // Package specific globals and files
  api.addFiles('lib/model.js');
  api.addFiles(['lib/templates.html', 'lib/templates/commentsBox.less']);
  api.addFiles(['lib/ui.js', 'lib/templates/commentsBox.js'], 'client');
  api.export('Comments');
});

Package.onTest(function(api) {
  api.use(['tinytest', 'accounts-password']);
  api.use('arkham:comments-ui');

  api.addFiles('tests/api-tests.js');
  api.addFiles('tests/ui-tests.js', 'client');
});
<|endoftext|>