<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */
/**
 * Module bk.helper
 * The bkHelper should be a subset of bkCore utilities that are exposed for
 * usages external to Beaker.
 */
(function() {
  'use strict';
  var module = angular.module('bk.helper', ['bk.utils', 'bk.core', 'bk.share', 'bk.debug']);
  /**
   * bkHelper
   * - should be the only thing plugins depend on to interact with general beaker stuffs (other than
   * conforming to the API spec)
   * - except plugins, nothing should depends on bkHelper
   * - we've made this global. We should revisit this decision and figure out the best way to load
   *   plugins dynamically
   * - it mostly should just be a subset of bkUtil
   */
  module.factory('bkHelper', function(bkUtils, bkCoreManager, bkShare, bkDebug) {
    var getCurrentApp = function() {
      return bkCoreManager.getBkApp();
    };
    var getBkNotebookWidget = function() {
      if (getCurrentApp().getBkNotebookWidget) {
        return getCurrentApp().getBkNotebookWidget();
      } else {
        console.error("Current app doesn't support getBkNotebookWidget");
      }
    };

    var bkHelper = {
      // enable debug
      debug: function() {
        window.bkDebug = bkDebug;
      },

      // beaker (root)
      gotoControlPanel: function() {
        return bkCoreManager.gotoControlPanel();
      },
      openNotebook: function(notebookUri, uriType, readOnly, format) {
        return bkCoreManager.openNotebook(notebookUri, uriType, readOnly, format);
      },
      // Empty true means truly empty new session.
      // otherwise use the default notebook.
      newSession: function(empty) {
        return bkCoreManager.newSession(empty);
      },

      // current app
      getCurrentAppName: function() {
        if (!_.isEmpty(getCurrentApp().name)) {
          return getCurrentApp().name;
        }
        return "Unknown App";
      },
      hasSessionId: function() {
        if (getCurrentApp().getSessionId) {
          return true;
        }
        return false;
      },
      getSessionId: function() {
        if (getCurrentApp().getSessionId) {
          return getCurrentApp().getSessionId();
        } else {
          console.error("Current app doesn't support getSessionId");
        }
      },
      getNotebookModel: function() {
        if (getCurrentApp().getNotebookModel) {
          return getCurrentApp().getNotebookModel();
        } else {
          console.error("Current app doesn't support getNotebookModel");
        }
      },
      closeNotebook: function() {
        if (getCurrentApp().closeNotebook) {
          return getCurrentApp().closeNotebook();
        } else {
          console.error("Current app doesn't support closeNotebook");
        }
      },
      saveNotebook: function() {
        if (getCurrentApp().saveNotebook) {
          return getCurrentApp().saveNotebook();
        } else {
          console.error("Current app doesn't support saveNotebook");
        }
      },
      saveNotebookAs: function(notebookUri, uriType) {
        if (getCurrentApp().saveNotebookAs) {
          return getCurrentApp().saveNotebookAs(notebookUri, uriType);
        } else {
          console.error("Current app doesn't support saveNotebookAs");
        }
      },
      evaluate: function(toEval) {
        if (getCurrentApp().evaluate) {
          return getCurrentApp().evaluate(toEval);
        } else {
          console.error("Current app doesn't support evaluate");
        }
      },
      evaluateCode: function(evaluator, code) {
        if (getCurrentApp().evaluateCode) {
          return getCurrentApp().evaluateCode(evaluator, code);
        } else {
          console.error("Current app doesn't support evaluateCode");
        }
      },
      getEvaluatorMenuItems: function() {
        if (getCurrentApp().getEvaluatorMenuItems) {
          return getCurrentApp().getEvaluatorMenuItems();
        } else {
          console.error("Current app doesn't support getEvaluatorMenuItems");
        }
      },
      toggleNotebookLocked: function() {
        if (getCurrentApp().toggleNotebookLocked) {
          return getCurrentApp().toggleNotebookLocked();
        } else {
          console.error("Current app doesn't support toggleNotebookLocked");
        }
      },
      isNotebookLocked: function() {
        if (getCurrentApp().isNotebookLocked) {
          return getCurrentApp().isNotebookLocked();
        } else {
          console.error("Current app doesn't support isNotebookLocked");
        }
      },
      showAnonymousTrackingDialog: function() {
        if (getCurrentApp().showAnonymousTrackingDialog) {
          return getCurrentApp().showAnonymousTrackingDialog();
        } else {
          console.error("Current app doesn't support showAnonymousTrackingDialog");
        }
      },

      // bk-notebook
      shareNotebook: function() {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.shareAndOpenPublished();
        }
      },
      deleteAllOutputCells: function() {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.deleteAllOutputCells();
        }
      },
      getBkNotebookViewModel: function() {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.getViewModel();
        }
      },
      setInputCellKeyMapMode: function(keyMapMode) {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.setCMKeyMapMode(keyMapMode);
        }
      },
      getInputCellKeyMapMode: function() {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.getCMKeyMapMode();
        }
      },

      // low level utils (bkUtils)
      refreshRootScope: function() {
        return bkUtils.refreshRootScope();
      },
      loadJS: function(url, success) {
        return bkUtils.loadJS(url, success);
      },
      loadCSS: function(url) {
        return bkUtils.loadCSS(url);
      },
      loadList: function(url, success, failure) {
        return bkUtils.loadList(url, success, failure);
      },
      findTable: function(elem) {
        return bkUtils.findTable(elem);
      },
      generateId: function(length) {
        return bkUtils.generateId(length);
      },
      httpGet: function(url, data) {
        return bkUtils.httpGet(url, data);
      },
      httpPost: function(url, data) {
        return bkUtils.httpPost(url, data);
      },
      newDeferred: function() {
        return bkUtils.newDeferred();
      },
      newPromise: function(value) {
        return bkUtils.newPromise(value);
      },
      all: function(promises) {
        return bkUtils.all(promises);
      },
      fcall: function(func) {
        return bkUtils.fcall(func);
      },
      getHomeDirectory: function() {
        return bkUtils.getHomeDirectory();
      },

      // utils (bkCore)
      setNotebookImporter: function(format, importer) {
        return bkCoreManager.setNotebookImporter(format, importer);
      },
      setFileLoader: function(uriType, fileLoader) {
        return bkCoreManager.setFileLoader(uriType, fileLoader);
      },
      setFileSaver: function(uriType, fileSaver) {
        return bkCoreManager.setFileSaver(uriType, fileSaver);
      },
      showDefaultSavingFileChooser: function() {
        return bkCoreManager.showDefaultSavingFileChooser();
      },
      getRecentMenuItems: function() {
        return bkCoreManager.getRecentMenuItems();
      },
      showModalDialog: function(callback, template, strategy) {
        return bkCoreManager.showModalDialog(callback, template, strategy);
      },
      show1ButtonModal: function(msgBody, msgHeader, callback) {
        return bkCoreManager.show1ButtonModal(msgBody, msgHeader, callback);
      },
      show2ButtonModal: function(msgBody, msgHeader, okCB, cancelCB, okBtnTxt, cancelBtnTxt) {
        return bkCoreManager.show2ButtonModal(
            msgBody, msgHeader, okCB, cancelCB, okBtnTxt, cancelBtnTxt);
      },
      show3ButtonModal: function(
          msgBody, msgHeader, yesCB, noCB, cancelCB, yesBtnTxt, noBtnTxt, cancelBtnTxt) {
        return bkCoreManager.show3ButtonModal(
            msgBody, msgHeader, yesCB, noCB, cancelCB, yesBtnTxt, noBtnTxt, cancelBtnTxt);
      },
      getFileSystemFileChooserStrategy: function() {
        return bkCoreManager.getFileSystemFileChooserStrategy();
      },

      // eval utils
      locatePluginService: function(id, locator) {
        return bkUtils.httpGet("../beaker/rest/plugin-services/" + id,
            locator);
      },
      getEvaluatorFactory: function(shellConstructorPromise) {
        return shellConstructorPromise.then(function(Shell) {
          return {
            create: function(settings) {
              return bkUtils.newPromise(new Shell(settings));
            }
          };
        });
      },

      // other JS utils
      updateDocumentModelFromDOM: function(id) {
          // 1) find the cell that contains elem
          var elem = $("#" + id).closest("bk-cell");
          if (elem === undefined) {
            console.log("ERROR: cannot find referenced cell.");
            return;
          }
          var cellid = elem[0].getAttribute("cellid");
          if (cellid === undefined) {
            console.log("ERROR: cannot find referenced cell.");
            return;
          }
          var body = elem.find( "bk-output-display[type='Html'] div div" );
          if (body === undefined) {
            console.log("ERROR: cannot find referenced cell.");
            return;
          }

          // 2) convert that part of the DOM to a string
          var newOutput = body[0].innerHTML;

          // 3) set the result.object to that string.
          var cell = bkCoreManager.getNotebookCellManager().getCell(cellid);
          if (cell === undefined) {
            console.log("ERROR: cannot find referenced cell.");
            return;
          }

          var res = cell.output.result;
          if (res.innertype === "Html") {
            res.object = newOutput;
          } else {
            console.log("ERROR: the referenced cell type must be HTML.")
          }
      },

      // bkShare
      share: bkShare
    };

    return bkHelper;
  });
})();
<commit_msg>Changed error text<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */
/**
 * Module bk.helper
 * The bkHelper should be a subset of bkCore utilities that are exposed for
 * usages external to Beaker.
 */
(function() {
  'use strict';
  var module = angular.module('bk.helper', ['bk.utils', 'bk.core', 'bk.share', 'bk.debug']);
  /**
   * bkHelper
   * - should be the only thing plugins depend on to interact with general beaker stuffs (other than
   * conforming to the API spec)
   * - except plugins, nothing should depends on bkHelper
   * - we've made this global. We should revisit this decision and figure out the best way to load
   *   plugins dynamically
   * - it mostly should just be a subset of bkUtil
   */
  module.factory('bkHelper', function(bkUtils, bkCoreManager, bkShare, bkDebug) {
    var getCurrentApp = function() {
      return bkCoreManager.getBkApp();
    };
    var getBkNotebookWidget = function() {
      if (getCurrentApp().getBkNotebookWidget) {
        return getCurrentApp().getBkNotebookWidget();
      } else {
        console.error("Current app doesn't support getBkNotebookWidget");
      }
    };

    var bkHelper = {
      // enable debug
      debug: function() {
        window.bkDebug = bkDebug;
      },

      // beaker (root)
      gotoControlPanel: function() {
        return bkCoreManager.gotoControlPanel();
      },
      openNotebook: function(notebookUri, uriType, readOnly, format) {
        return bkCoreManager.openNotebook(notebookUri, uriType, readOnly, format);
      },
      // Empty true means truly empty new session.
      // otherwise use the default notebook.
      newSession: function(empty) {
        return bkCoreManager.newSession(empty);
      },

      // current app
      getCurrentAppName: function() {
        if (!_.isEmpty(getCurrentApp().name)) {
          return getCurrentApp().name;
        }
        return "Unknown App";
      },
      hasSessionId: function() {
        if (getCurrentApp().getSessionId) {
          return true;
        }
        return false;
      },
      getSessionId: function() {
        if (getCurrentApp().getSessionId) {
          return getCurrentApp().getSessionId();
        } else {
          console.error("Current app doesn't support getSessionId");
        }
      },
      getNotebookModel: function() {
        if (getCurrentApp().getNotebookModel) {
          return getCurrentApp().getNotebookModel();
        } else {
          console.error("Current app doesn't support getNotebookModel");
        }
      },
      closeNotebook: function() {
        if (getCurrentApp().closeNotebook) {
          return getCurrentApp().closeNotebook();
        } else {
          console.error("Current app doesn't support closeNotebook");
        }
      },
      saveNotebook: function() {
        if (getCurrentApp().saveNotebook) {
          return getCurrentApp().saveNotebook();
        } else {
          console.error("Current app doesn't support saveNotebook");
        }
      },
      saveNotebookAs: function(notebookUri, uriType) {
        if (getCurrentApp().saveNotebookAs) {
          return getCurrentApp().saveNotebookAs(notebookUri, uriType);
        } else {
          console.error("Current app doesn't support saveNotebookAs");
        }
      },
      evaluate: function(toEval) {
        if (getCurrentApp().evaluate) {
          return getCurrentApp().evaluate(toEval);
        } else {
          console.error("Current app doesn't support evaluate");
        }
      },
      evaluateCode: function(evaluator, code) {
        if (getCurrentApp().evaluateCode) {
          return getCurrentApp().evaluateCode(evaluator, code);
        } else {
          console.error("Current app doesn't support evaluateCode");
        }
      },
      getEvaluatorMenuItems: function() {
        if (getCurrentApp().getEvaluatorMenuItems) {
          return getCurrentApp().getEvaluatorMenuItems();
        } else {
          console.error("Current app doesn't support getEvaluatorMenuItems");
        }
      },
      toggleNotebookLocked: function() {
        if (getCurrentApp().toggleNotebookLocked) {
          return getCurrentApp().toggleNotebookLocked();
        } else {
          console.error("Current app doesn't support toggleNotebookLocked");
        }
      },
      isNotebookLocked: function() {
        if (getCurrentApp().isNotebookLocked) {
          return getCurrentApp().isNotebookLocked();
        } else {
          console.error("Current app doesn't support isNotebookLocked");
        }
      },
      showAnonymousTrackingDialog: function() {
        if (getCurrentApp().showAnonymousTrackingDialog) {
          return getCurrentApp().showAnonymousTrackingDialog();
        } else {
          console.error("Current app doesn't support showAnonymousTrackingDialog");
        }
      },

      // bk-notebook
      shareNotebook: function() {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.shareAndOpenPublished();
        }
      },
      deleteAllOutputCells: function() {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.deleteAllOutputCells();
        }
      },
      getBkNotebookViewModel: function() {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.getViewModel();
        }
      },
      setInputCellKeyMapMode: function(keyMapMode) {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.setCMKeyMapMode(keyMapMode);
        }
      },
      getInputCellKeyMapMode: function() {
        var bkNotebook = getBkNotebookWidget();
        if (bkNotebook) {
          return bkNotebook.getCMKeyMapMode();
        }
      },

      // low level utils (bkUtils)
      refreshRootScope: function() {
        return bkUtils.refreshRootScope();
      },
      loadJS: function(url, success) {
        return bkUtils.loadJS(url, success);
      },
      loadCSS: function(url) {
        return bkUtils.loadCSS(url);
      },
      loadList: function(url, success, failure) {
        return bkUtils.loadList(url, success, failure);
      },
      findTable: function(elem) {
        return bkUtils.findTable(elem);
      },
      generateId: function(length) {
        return bkUtils.generateId(length);
      },
      httpGet: function(url, data) {
        return bkUtils.httpGet(url, data);
      },
      httpPost: function(url, data) {
        return bkUtils.httpPost(url, data);
      },
      newDeferred: function() {
        return bkUtils.newDeferred();
      },
      newPromise: function(value) {
        return bkUtils.newPromise(value);
      },
      all: function(promises) {
        return bkUtils.all(promises);
      },
      fcall: function(func) {
        return bkUtils.fcall(func);
      },
      getHomeDirectory: function() {
        return bkUtils.getHomeDirectory();
      },

      // utils (bkCore)
      setNotebookImporter: function(format, importer) {
        return bkCoreManager.setNotebookImporter(format, importer);
      },
      setFileLoader: function(uriType, fileLoader) {
        return bkCoreManager.setFileLoader(uriType, fileLoader);
      },
      setFileSaver: function(uriType, fileSaver) {
        return bkCoreManager.setFileSaver(uriType, fileSaver);
      },
      showDefaultSavingFileChooser: function() {
        return bkCoreManager.showDefaultSavingFileChooser();
      },
      getRecentMenuItems: function() {
        return bkCoreManager.getRecentMenuItems();
      },
      showModalDialog: function(callback, template, strategy) {
        return bkCoreManager.showModalDialog(callback, template, strategy);
      },
      show1ButtonModal: function(msgBody, msgHeader, callback) {
        return bkCoreManager.show1ButtonModal(msgBody, msgHeader, callback);
      },
      show2ButtonModal: function(msgBody, msgHeader, okCB, cancelCB, okBtnTxt, cancelBtnTxt) {
        return bkCoreManager.show2ButtonModal(
            msgBody, msgHeader, okCB, cancelCB, okBtnTxt, cancelBtnTxt);
      },
      show3ButtonModal: function(
          msgBody, msgHeader, yesCB, noCB, cancelCB, yesBtnTxt, noBtnTxt, cancelBtnTxt) {
        return bkCoreManager.show3ButtonModal(
            msgBody, msgHeader, yesCB, noCB, cancelCB, yesBtnTxt, noBtnTxt, cancelBtnTxt);
      },
      getFileSystemFileChooserStrategy: function() {
        return bkCoreManager.getFileSystemFileChooserStrategy();
      },

      // eval utils
      locatePluginService: function(id, locator) {
        return bkUtils.httpGet("../beaker/rest/plugin-services/" + id,
            locator);
      },
      getEvaluatorFactory: function(shellConstructorPromise) {
        return shellConstructorPromise.then(function(Shell) {
          return {
            create: function(settings) {
              return bkUtils.newPromise(new Shell(settings));
            }
          };
        });
      },

      // other JS utils
      updateDocumentModelFromDOM: function(id) {
          // 1) find the cell that contains elem
          var elem = $("#" + id).closest("bk-cell");
          if (elem === undefined) {
            console.log("ERROR: cannot find an Html cell containing the element"+id+".");
            return;
          }
          var cellid = elem[0].getAttribute("cellid");
          if (cellid === undefined) {
            console.log("ERROR: cannot find an Html cell containing the element"+id+".");
            return;
          }
          var body = elem.find( "bk-output-display[type='Html'] div div" );
          if (body === undefined) {
            console.log("ERROR: cannot find an Html cell containing the element"+id+".");
            return;
          }

          // 2) convert that part of the DOM to a string
          var newOutput = body[0].innerHTML;

          // 3) set the result.object to that string.
          var cell = bkCoreManager.getNotebookCellManager().getCell(cellid);
          if (cell === undefined) {
            console.log("ERROR: cannot find an Html cell containing the element"+id+".");
            return;
          }

          var res = cell.output.result;
          if (res.innertype === "Html") {
            res.object = newOutput;
          } else {
            console.log("ERROR: cannot find an Html cell containing the element"+id+".");
          }
      },

      // bkShare
      share: bkShare
    };

    return bkHelper;
  });
})();
<|endoftext|>


<commit_before>// `client` section processor
//
//      .
//      |- /client/
//      |   |- <package>.js
//      |   `- ...
//      `- ...
//

'use strict';

/*global N*/

// stdlib
var fs    = require('fs');
var path  = require('path');

// 3rd-party
var _             = require('underscore');
var apiTree       = require('nlib').ApiTree;
var async         = require('nlib').Vendor.Async;
var fstools       = require('nlib').Vendor.FsTools;
var safePropName  = require('nlib').Support.safePropName;
var findRequires  = require('find-requires');

// internal
var findPaths = require('./utils').findPaths;

////////////////////////////////////////////////////////////////////////////////

function Requisite(root) {
  this.requires = {};
  this.idx      = 1;
  this.root     = String(root || '').replace(/\/*$/, '/');
}

Requisite.prototype.process = function (source, pathname) {
  var
  self  = this,
  base  = path.dirname(pathname.toString()),
  files = findRequires(source, { raw: true }),
  o, p;

  while (files.length) {
    o = files.shift();

    if (!o.value) {
      return new Error("Cannot handle non-string required path: " + o.raw);
    }

    try {
      // replace @ with root
      p = String(o.value).replace(/^@\/*/, this.root);
      // try to resolve path relatively to pathname
      p = require.resolve(path.resolve(base, p));
    } catch (err) {
      throw new Error(err.message +
                      ' (require: ' + o.value + ') (in: ' + pathname + ')');
    }

    if (undefined === this.requires[p]) {
      this.requires[p] = { idx: this.idx++, api: pathname.api, source: null };
      // prevent from "cyclic" loops
      this.requires[p].source = this.process(fs.readFileSync(p, 'utf8'), p);
    }

    source = source.replace(o.value, this.requires[p].idx);
  }

  return source;
};

Requisite.prototype.bundle = function () {
  var parts = [];

  parts.push(
    '(function () {',
      'var modules = {};',
      'function define(name, api, init) {',
        'modules[name] = { api: api, init: init };',
      '}',
      'function require(name) {',
        'if (!modules[name]) { throw new Error("Unknown module " + name); }',
        'if (!modules[name].module) {',
          'function t(phrase, params) {',
            'if (0 === phrase.indexOf(".")) {',
              'phrase = phrase.substr(1);',
            '} else {',
              'phrase = modules[name].api + "." + phrase;',
            '}',
            'return N.runtime.t(phrase, params);',
          '}',
          'modules[name].module = { exports: {} };',
          'modules[name].init.call(modules[name].module.exports, ',
            'modules[name].module.exports, modules[name].module, ',
            'require, t);',
        '}',
        'return modules[name].module.exports;',
      '}'
  );

  _.each(this.requires, function (dep, pathname) {
    parts.push(
      'define(' + dep.idx + ', ' + JSON.stringify(dep.api) + ', function (exports, module, require, t, define, modules) {',
      dep.source,
      '});'
    );
  });

  parts.push(
      'return require;',
    '}())'
  );

  return parts.join('\n');
};

function browserifyClient(outfile, config, callback) {
  var chunks = [];

  async.forEachSeries(config.lookup, function (options, next) {
    findPaths(options, function (err, pathnames) {
      var
      heads       = [],
      bodies      = [],
      exportsList = [],
      requisite   = new Requisite(options.appRoot);

      if (err) {
        next(err);
        return;
      }

      async.forEachSeries(pathnames, function (pathname, nextPath) {
        pathname.read(function (err, source) {
          var // [ '["foo"]', '["bar"]', '["baz"]' ]
          apiPathParts = pathname.api.split('.').map(safePropName);

          if (err) {
            nextPath(err);
            return;
          }

          // feed all parents of apiPath into heads array
          apiPathParts.reduce(function (prev, curr) {
            if (-1 === heads.indexOf(prev)) {
              heads.push(prev);
            }

            return prev + curr;
          });

          try {
            source = requisite.process(source, pathname);
          } catch (err) {
            nextPath(err);
            return;
          }

          bodies.push(
            ('this' + apiPathParts.join('') + ' = (function (require) {'),
              ('(function (exports, module) {'),
              source,
              ('}.call(this.exports, this.exports, this));'),
              ('return this.exports;'),
            ('}.call({ exports: {} }, require));')
          );

          exportsList.push('this' + apiPathParts.join(''));

          nextPath();
        });
      }, function (err) {
        if (err) {
          next(err);
          return;
        }

        chunks.push([
          '(function () {',
          'var require = ' + requisite.bundle() + ';\n\n',
          _.uniq(heads.sort(), true).map(function (api) {
            return 'this' + api + ' = {};';
          }).join('\n') + '\n\n' + bodies.join('\n') + '\n\n',
          '_.map([' + exportsList.sort().join(',') + '], function (api) {',
          'if (api && _.isFunction(api.init)) { api.init(window, N); }',
          '});',
          '}.call(N.client));'
        ].join('\n'));

        next();
      });
    });
  }, function (err) {
    if (err) {
      callback(err);
      return;
    }

    fs.writeFile(outfile, chunks.join('\n\n'), 'utf8', callback);
  });
}

////////////////////////////////////////////////////////////////////////////////

module.exports = function (tmpdir, config, callback) {
  async.forEachSeries(_.keys(config.packages), function (pkgName, next) {
    var
    clientConfig   = config.packages[pkgName].client,
    clientOutfile  = path.join(tmpdir, 'client', pkgName + '.js');

    if (!clientConfig) {
      next();
      return;
    }

    fstools.mkdir(path.dirname(clientOutfile), function (err) {
      if (err) {
        next(err);
        return;
      }

      browserifyClient(clientOutfile, clientConfig, next);
    });
  }, callback);
};
<commit_msg>Fix client bundles init<commit_after>// `client` section processor
//
//      .
//      |- /client/
//      |   |- <package>.js
//      |   `- ...
//      `- ...
//

'use strict';

/*global N*/

// stdlib
var fs    = require('fs');
var path  = require('path');

// 3rd-party
var _             = require('underscore');
var apiTree       = require('nlib').ApiTree;
var async         = require('nlib').Vendor.Async;
var fstools       = require('nlib').Vendor.FsTools;
var safePropName  = require('nlib').Support.safePropName;
var findRequires  = require('find-requires');

// internal
var findPaths = require('./utils').findPaths;

////////////////////////////////////////////////////////////////////////////////

function Requisite(root) {
  this.requires = {};
  this.idx      = 1;
  this.root     = String(root || '').replace(/\/*$/, '/');
}

Requisite.prototype.process = function (source, pathname) {
  var
  self  = this,
  base  = path.dirname(pathname.toString()),
  files = findRequires(source, { raw: true }),
  o, p;

  while (files.length) {
    o = files.shift();

    if (!o.value) {
      return new Error("Cannot handle non-string required path: " + o.raw);
    }

    try {
      // replace @ with root
      p = String(o.value).replace(/^@\/*/, this.root);
      // try to resolve path relatively to pathname
      p = require.resolve(path.resolve(base, p));
    } catch (err) {
      throw new Error(err.message +
                      ' (require: ' + o.value + ') (in: ' + pathname + ')');
    }

    if (undefined === this.requires[p]) {
      this.requires[p] = { idx: this.idx++, api: pathname.api, source: null };
      // prevent from "cyclic" loops
      this.requires[p].source = this.process(fs.readFileSync(p, 'utf8'), p);
    }

    source = source.replace(o.value, this.requires[p].idx);
  }

  return source;
};

Requisite.prototype.bundle = function () {
  var parts = [];

  parts.push(
    '(function () {',
      'var modules = {};',
      'function define(name, api, init) {',
        'modules[name] = { api: api, init: init };',
      '}',
      'function require(name) {',
        'if (!modules[name]) { throw new Error("Unknown module " + name); }',
        'if (!modules[name].module) {',
          'function t(phrase, params) {',
            'if (0 === phrase.indexOf(".")) {',
              'phrase = phrase.substr(1);',
            '} else {',
              'phrase = modules[name].api + "." + phrase;',
            '}',
            'return N.runtime.t(phrase, params);',
          '}',
          'modules[name].module = { exports: {} };',
          'modules[name].init.call(modules[name].module.exports, ',
            'modules[name].module.exports, modules[name].module, ',
            'require, t);',
        '}',
        'return modules[name].module.exports;',
      '}'
  );

  _.each(this.requires, function (dep, pathname) {
    parts.push(
      'define(' + dep.idx + ', ' + JSON.stringify(dep.api) + ', function (exports, module, require, t, define, modules) {',
      dep.source,
      '});'
    );
  });

  parts.push(
      'return require;',
    '}())'
  );

  return parts.join('\n');
};

function browserifyClient(outfile, config, callback) {
  var chunks = [];

  async.forEachSeries(config.lookup, function (options, next) {
    findPaths(options, function (err, pathnames) {
      var
      heads       = [],
      bodies      = [],
      exportsList = [],
      requisite   = new Requisite(options.appRoot);

      if (err) {
        next(err);
        return;
      }

      async.forEachSeries(pathnames, function (pathname, nextPath) {
        pathname.read(function (err, source) {
          var // [ '["foo"]', '["bar"]', '["baz"]' ]
          apiPathParts = pathname.api.split('.').map(safePropName);

          if (err) {
            nextPath(err);
            return;
          }

          // feed all parents of apiPath into heads array
          apiPathParts.reduce(function (prev, curr) {
            if (-1 === heads.indexOf(prev)) {
              heads.push(prev);
            }

            return prev + curr;
          });

          try {
            source = requisite.process(source, pathname);
          } catch (err) {
            nextPath(err);
            return;
          }

          bodies.push(
            ('this' + apiPathParts.join('') + ' = (function (require) {'),
              ('function t(phrase, params) {'),
                ('if (0 === phrase.indexOf(".")) {'),
                  ('phrase = phrase.substr(1);'),
                ('} else {'),
                  ('phrase = ' + JSON.stringify(pathname.api) + ' + "." + phrase;'),
                ('}'),
                ('return N.runtime.t(phrase, params);'),
              ('}'),
              ('(function (exports, module, t) {'),
              source,
              ('}.call(this.exports, this.exports, this, t));'),
              ('return this.exports;'),
            ('}.call({ exports: {} }, require));')
          );

          exportsList.push('this' + apiPathParts.join(''));

          nextPath();
        });
      }, function (err) {
        if (err) {
          next(err);
          return;
        }

        chunks.push([
          '(function () {',
          'var require = ' + requisite.bundle() + ';\n\n',
          _.uniq(heads.sort(), true).map(function (api) {
            return 'this' + api + ' = {};';
          }).join('\n') + '\n\n' + bodies.join('\n') + '\n\n',
          '_.map([' + exportsList.sort().join(',') + '], function (api) {',
          'if (api && _.isFunction(api.init)) { api.init(window, N); }',
          '});',
          '}.call(N.client));'
        ].join('\n'));

        next();
      });
    });
  }, function (err) {
    if (err) {
      callback(err);
      return;
    }

    fs.writeFile(outfile, chunks.join('\n\n'), 'utf8', callback);
  });
}

////////////////////////////////////////////////////////////////////////////////

module.exports = function (tmpdir, config, callback) {
  async.forEachSeries(_.keys(config.packages), function (pkgName, next) {
    var
    clientConfig   = config.packages[pkgName].client,
    clientOutfile  = path.join(tmpdir, 'client', pkgName + '.js');

    if (!clientConfig) {
      next();
      return;
    }

    fstools.mkdir(path.dirname(clientOutfile), function (err) {
      if (err) {
        next(err);
        return;
      }

      browserifyClient(clientOutfile, clientConfig, next);
    });
  }, callback);
};
<|endoftext|>


<commit_before>const source = require('./source')
const prepareSource = require('./sourceDef/prepareSource')
const router = require('./router')
const actions = require('./actions')
const reduceToObject = require('../utils/reduceToObject')
const scheduleToAction = require('../utils/scheduleToAction')
const debug = require('debug')('great')

const version = '0.1'

const formatTypeVal = (val) => (typeof val === 'string') ? {type: val} : val
const reduceFormattedVal = (vals) => (obj, val) => Object.assign(obj, {[val]: formatTypeVal(vals[val])})
const prepareVals = (vals) => (vals) ? Object.keys(vals).reduce(reduceFormattedVal(vals), {}) : vals
const prepareType = (type) => Object.assign({}, type, {
  attributes: prepareVals(type.attributes),
  relationships: prepareVals(type.relationships)
})

/**
 * Return an integration object with a dispatch method.
 * Use the dispatch method for sending actions to sources, for retrieving typed
 * items and updating data.
 * @param {Array} sourceDefs - Array of source definitions
 * @param {Array} typeDefs - Array of type definitions
 * @param {Object} resources - Object with adapters, auths, mappers, filters, transforms, and workers
 * @returns {Object} Integration object with the dispatch method
 */
function integreat (sourceDefs, typeDefs, {
  adapters,
  auths,
  mappers,
  filters,
  transforms,
  workers
} = {}) {
  if (!sourceDefs || !typeDefs) {
    throw new TypeError('Call integreat with at least sources and types')
  }

  const types = typeDefs.map(prepareType).reduce(reduceToObject('id'), {})

  const mapSource = (def) => source(def.id, prepareSource(def, {
    types,
    adapters,
    auths,
    mappers,
    filters,
    transforms
  }))
  const sources = sourceDefs.map(mapSource).reduce(reduceToObject('id'), {})

  return {
    version,
    queue: null,

    /**
     * Function for dispatching actions to Integreat. All actions are directed
     * to a router, which sends the action to the right action handler or
     * pushes it to the queue, depending on the properties of the action.
     * @param {Object} action - The action to dispatch
     * @returns {Promise} Promise of returned data
     */
    async dispatch (action) {
      debug('Dispatch: %o', action)
      return router(action, {
        actions,
        sources,
        types,
        workers,
        dispatch: this.dispatch,
        queue: this.queue
      })
    },

    /**
     * Schedule actions from the given scheduleDef.
     * Actions are dispatched to Integreat with a timestamp, and are ran at the
     * set time with the worker given in the schedule definition.
     * @param {array} scheduleDef - An array of schedule definitions
     * @returns {array} Array of returned objects from dispatch
     */
    async schedule (scheduleDef) {
      debug('Schedule: %d schedules', scheduleDef.length)
      const rets = scheduleDef.map(scheduleToAction).map((action) => this.dispatch(action))
      return Promise.all(rets)
    }
  }
}

module.exports = integreat
<commit_msg>Bind dispatch to great<commit_after>const source = require('./source')
const prepareSource = require('./sourceDef/prepareSource')
const router = require('./router')
const actions = require('./actions')
const reduceToObject = require('../utils/reduceToObject')
const scheduleToAction = require('../utils/scheduleToAction')
const debug = require('debug')('great')

const version = '0.1'

const formatTypeVal = (val) => (typeof val === 'string') ? {type: val} : val
const reduceFormattedVal = (vals) => (obj, val) => Object.assign(obj, {[val]: formatTypeVal(vals[val])})
const prepareVals = (vals) => (vals) ? Object.keys(vals).reduce(reduceFormattedVal(vals), {}) : vals
const prepareType = (type) => Object.assign({}, type, {
  attributes: prepareVals(type.attributes),
  relationships: prepareVals(type.relationships)
})

/**
 * Return an integration object with a dispatch method.
 * Use the dispatch method for sending actions to sources, for retrieving typed
 * items and updating data.
 * @param {Array} sourceDefs - Array of source definitions
 * @param {Array} typeDefs - Array of type definitions
 * @param {Object} resources - Object with adapters, auths, mappers, filters, transforms, and workers
 * @returns {Object} Integration object with the dispatch method
 */
function integreat (sourceDefs, typeDefs, {
  adapters,
  auths,
  mappers,
  filters,
  transforms,
  workers
} = {}) {
  if (!sourceDefs || !typeDefs) {
    throw new TypeError('Call integreat with at least sources and types')
  }

  const types = typeDefs.map(prepareType).reduce(reduceToObject('id'), {})

  const mapSource = (def) => source(def.id, prepareSource(def, {
    types,
    adapters,
    auths,
    mappers,
    filters,
    transforms
  }))
  const sources = sourceDefs.map(mapSource).reduce(reduceToObject('id'), {})

  return {
    version,
    queue: null,

    /**
     * Function for dispatching actions to Integreat. All actions are directed
     * to a router, which sends the action to the right action handler or
     * pushes it to the queue, depending on the properties of the action.
     * @param {Object} action - The action to dispatch
     * @returns {Promise} Promise of returned data
     */
    async dispatch (action) {
      debug('Dispatch: %o', action)
      return router(action, {
        actions,
        sources,
        types,
        workers,
        dispatch: this.dispatch.bind(this),
        queue: this.queue
      })
    },

    /**
     * Schedule actions from the given scheduleDef.
     * Actions are dispatched to Integreat with a timestamp, and are ran at the
     * set time with the worker given in the schedule definition.
     * @param {array} scheduleDef - An array of schedule definitions
     * @returns {array} Array of returned objects from dispatch
     */
    async schedule (scheduleDef) {
      debug('Schedule: %d schedules', scheduleDef.length)
      const rets = scheduleDef.map(scheduleToAction).map((action) => this.dispatch(action))
      return Promise.all(rets)
    }
  }
}

module.exports = integreat
<|endoftext|>


<commit_before>/*
 * service.js: RESTful JSON-based web service for the drone module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var haibu = require('../../haibu');

//
// ### function createRouter (dron, logger)
// #### @drone {Drone} Instance of the Drone resource to use in this router.
//
// Creates the Journey router which represents the `haibu` Drone webservice.
//
exports.createRouter = function (drone) {
  //
  // TODO (indexzero): Setup token-based auth for Drone API servers
  //
  haibu.router.strict = false;

  //
  // ### Default Root
  // `GET /` responds with default JSON message
  //
  haibu.router.get('/', function () {
    haibu.sendResponse(this.res, 400, { message: 'No drones specified' });
  });

  //
  // ### Version Binding
  // `GET /version` returns the version string for this webservice
  //
  haibu.router.get(/\/version/, function () {
    haibu.sendResponse(this.res, 200, { version: 'haibu ' + haibu.version });
  });

  haibu.router.post(/\/deploy\/([\w\-\.]+)\/([\w\-\.]+)/, { stream: true }, function (userId, appId) {
    var res = this.res;

    drone.deploy(userId, appId, this.req, function (err, result) {
      if (err) {
        haibu.emit(['error', 'service'], 'error', err);
        return haibu.sendResponse(res, 500, { error: err });
      }

      haibu.sendResponse(res, 200, { drone: result });
    })
  });

  //
  // ### Drones Resource
  // Routes for RESTful access to the Drone resource.
  //
  haibu.router.path('/drones', function () {
    //
    // ### List Apps
    // `GET /drones` returns list of all drones managed by the
    // Drone associated with this router.
    //
    this.get(function () {
      var res = this.res,
          data = { drones: drone.list() };

      haibu.sendResponse(res, 200, data);
    });

    //
    // ### List Drone Processes
    // `GET /drones/running` returns with a list of formatted
    // drone processes.
    //
    this.get(/\/running/, function () {
      haibu.sendResponse(this.res, 200, drone.running());
    });

    //
    // ### Show App
    // `GET /drones/:id` shows details of a drone managed by the
    // Drone associated with this router.
    //
    this.get(/\/([\w\-\.]+)/, function (id) {
      var data = drone.show(id);
      if (typeof data === 'undefined') {
        haibu.sendResponse(this.res, 404, { message: 'No drone(s) found for application ' + id });
      }
      else {
        haibu.sendResponse(this.res, 200, data);
      }
    });

    //
    // ### Start Drone for App
    // `POST /drone/:id/start` starts a new drone for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/start/, function (id) {
      var res = this.res;

      drone.start(this.req.body.start, function (err, result) {
        if (err) {
          err = {
            name: err.name || undefined,
            message: err.message || '' + err,
            stack: err.stack || undefined,
            stdout: err.stdout || undefined,
            stderr: err.stderr || undefined
          }
          haibu.emit(['error', 'service'], 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { drone: result });
      });
    });

    //
    // ### Stop Drone for App
    // `POST /drone/:id/stop` stops all drones for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/stop/, function (id) {
      var res = this.res;

      drone.stop(this.req.body.stop.name, function (err, result) {
        if (err || !result) {
          err = err || new Error('Unknown error from drone.');
          err = {
            name: err.name || undefined,
            message: err.message || '' + err,
            stack: err.stack || undefined,
            stdout: err.stdout || undefined,
            stderr: err.stderr || undefined
          }
          haibu.emit('error:service', 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, {});
      });
    });

    //
    // ### Restart Drone for App
    // `POST /drone/:id/restart` restarts all drones for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/restart/, function (id) {
      var res = this.res;

      drone.restart(this.req.body.restart.name, function (err, drones) {
        if (err) {
          err = {
            name: err.name || undefined,
            message: err.message || '' + err,
            stack: err.stack || undefined,
            stdout: err.stdout || undefined,
            stderr: err.stderr || undefined
          }
          haibu.emit(['error', 'service'], 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { drones: drones });
      });
    });

    //
    // ### Clean Drone for App
    // `POST /drones/:id/clean` removes all of the dependencies and source files for
    // the app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/clean/, function (id) {
      var res = this.res;

      drone.clean(this.req.body, function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { clean: true });
      });
    });

    //
    // ### Update Drone for App
    // `POST /drones/:id/update` cleans and starts
    // the app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/update/, function (id) {
      var res = this.res;

      drone.update(this.req.body, function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { update: true });
      });
    });

    //
    // ### Clean All Drones
    // `POST /drones/cleanall` removes all of the dependencies and source files for
    // all apps on this server.
    //
    this.post(/\/cleanall/, function (response) {
      var res = this.res;

      drone.cleanAll(function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { clean: true });
      });
    });
  });
};
<commit_msg>[minor] No need to create proxy errors with patch to `Error.prototype.toJSON`<commit_after>/*
 * service.js: RESTful JSON-based web service for the drone module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var haibu = require('../../haibu');

//
// ### function createRouter (dron, logger)
// #### @drone {Drone} Instance of the Drone resource to use in this router.
//
// Creates the Journey router which represents the `haibu` Drone webservice.
//
exports.createRouter = function (drone) {
  //
  // TODO (indexzero): Setup token-based auth for Drone API servers
  //
  haibu.router.strict = false;

  //
  // ### Default Root
  // `GET /` responds with default JSON message
  //
  haibu.router.get('/', function () {
    haibu.sendResponse(this.res, 400, { message: 'No drones specified' });
  });

  //
  // ### Version Binding
  // `GET /version` returns the version string for this webservice
  //
  haibu.router.get(/\/version/, function () {
    haibu.sendResponse(this.res, 200, { version: 'haibu ' + haibu.version });
  });

  haibu.router.post(/\/deploy\/([\w\-\.]+)\/([\w\-\.]+)/, { stream: true }, function (userId, appId) {
    var res = this.res;

    drone.deploy(userId, appId, this.req, function (err, result) {
      if (err) {
        haibu.emit(['error', 'service'], 'error', err);
        return haibu.sendResponse(res, 500, { error: err });
      }

      haibu.sendResponse(res, 200, { drone: result });
    })
  });

  //
  // ### Drones Resource
  // Routes for RESTful access to the Drone resource.
  //
  haibu.router.path('/drones', function () {
    //
    // ### List Apps
    // `GET /drones` returns list of all drones managed by the
    // Drone associated with this router.
    //
    this.get(function () {
      var res = this.res,
          data = { drones: drone.list() };

      haibu.sendResponse(res, 200, data);
    });

    //
    // ### List Drone Processes
    // `GET /drones/running` returns with a list of formatted
    // drone processes.
    //
    this.get(/\/running/, function () {
      haibu.sendResponse(this.res, 200, drone.running());
    });

    //
    // ### Show App
    // `GET /drones/:id` shows details of a drone managed by the
    // Drone associated with this router.
    //
    this.get(/\/([\w\-\.]+)/, function (id) {
      var data = drone.show(id);
      if (typeof data === 'undefined') {
        haibu.sendResponse(this.res, 404, { message: 'No drone(s) found for application ' + id });
      }
      else {
        haibu.sendResponse(this.res, 200, data);
      }
    });

    //
    // ### Start Drone for App
    // `POST /drone/:id/start` starts a new drone for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/start/, function (id) {
      var res = this.res;

      drone.start(this.req.body.start, function (err, result) {
        if (err) {
          haibu.emit(['error', 'service'], 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { drone: result });
      });
    });

    //
    // ### Stop Drone for App
    // `POST /drone/:id/stop` stops all drones for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/stop/, function (id) {
      var res = this.res;

      drone.stop(this.req.body.stop.name, function (err, result) {
        if (err || !result) {
          err = err || new Error('Unknown error from drone.');
          haibu.emit('error:service', 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, {});
      });
    });

    //
    // ### Restart Drone for App
    // `POST /drone/:id/restart` restarts all drones for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/restart/, function (id) {
      var res = this.res;

      drone.restart(this.req.body.restart.name, function (err, drones) {
        if (err) {
          haibu.emit(['error', 'service'], 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { drones: drones });
      });
    });

    //
    // ### Clean Drone for App
    // `POST /drones/:id/clean` removes all of the dependencies and source files for
    // the app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/clean/, function (id) {
      var res = this.res;

      drone.clean(this.req.body, function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { clean: true });
      });
    });

    //
    // ### Update Drone for App
    // `POST /drones/:id/update` cleans and starts
    // the app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/update/, function (id) {
      var res = this.res;

      drone.update(this.req.body, function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { update: true });
      });
    });

    //
    // ### Clean All Drones
    // `POST /drones/cleanall` removes all of the dependencies and source files for
    // all apps on this server.
    //
    this.post(/\/cleanall/, function (response) {
      var res = this.res;

      drone.cleanAll(function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return haibu.sendResponse(res, 500, { error: err });
        }

        haibu.sendResponse(res, 200, { clean: true });
      });
    });
  });
};
<|endoftext|>


<commit_before>'use strict';

var modifyInfo = function(info) {
    var modified = false;
    if ('audio_ads' in info) {
        info['audio_ads']['day_limit'] = 0;
        info['audio_ads']['types_allowed'] = [];
        info['audio_ads']['sections'] = [];
        modified = true;
    }
    if (!('profiler_enabled' in info) || info['profiler_enabled']) {
        info['profiler_enabled'] = false;
        modified = true;
    }
    if ('music_intro' in info && info['music_intro']) {
        info['music_intro'] = false;
        modified = true;
    }
    if ('settings' in info) {
        var settings = info['settings'];
        for (var i = 0, len = settings.length; i < len; i++) {
            if (['audio_ads', 'audio_restrictions'].includes(settings[i]['name'])) {
                settings[i]['available'] = false;
                modified = true;
            }
        }
    }
    return modified;
}

module.exports.transform = function(response, req, res) {
    if (req.url == '/method/execute.getNewsfeedSmart') {
        var json = response.json;
        if ('response' in json && 'items' in json['response']) {
            var items = json['response']['items'];
            var initialLength = items.length;
            for (var i = 0, len = items.length; i < len; i++) {
                if (items[i]['type'] == 'ads' || (items[i]['type'] == 'post' && items[i]['marked_as_ads'] == 1)) {
                    items.splice(i, 1);
                    len--;
                }
            }
            if (initialLength != items.length)
                response.json = json;
        }
    } else if (req.url == '/method/execute.getCountersAndInfo') {
        let json = response.json;
        if ('response' in json) {
            let modified = modifyInfo(json['response']);
            if (modified)
                response.json = json;
        }
    } else if (req.url == '/method/execute.getUserInfo') {
        let json = response.json;
        if ('response' in json && 'info' in json['response']) {
            let modified = modifyInfo(json['response']['info']);
            if (modified)
                response.json = json;
        }
    }
};
<commit_msg>Этого не стоило делать<commit_after>'use strict';

var modifyInfo = function(info) {
    var modified = false;
    if ('audio_ads' in info) {
        info['audio_ads']['day_limit'] = 0;
        info['audio_ads']['types_allowed'] = [];
        info['audio_ads']['sections'] = [];
        modified = true;
    }
    if (!('profiler_enabled' in info) || info['profiler_enabled']) {
        info['profiler_enabled'] = false;
        modified = true;
    }
    if ('settings' in info) {
        var settings = info['settings'];
        for (var i = 0, len = settings.length; i < len; i++) {
            if (['audio_ads', 'audio_restrictions'].includes(settings[i]['name'])) {
                settings[i]['available'] = false;
                modified = true;
            }
        }
    }
    return modified;
}

module.exports.transform = function(response, req, res) {
    if (req.url == '/method/execute.getNewsfeedSmart') {
        var json = response.json;
        if ('response' in json && 'items' in json['response']) {
            var items = json['response']['items'];
            var initialLength = items.length;
            for (var i = 0, len = items.length; i < len; i++) {
                if (items[i]['type'] == 'ads' || (items[i]['type'] == 'post' && items[i]['marked_as_ads'] == 1)) {
                    items.splice(i, 1);
                    len--;
                }
            }
            if (initialLength != items.length)
                response.json = json;
        }
    } else if (req.url == '/method/execute.getCountersAndInfo') {
        let json = response.json;
        if ('response' in json) {
            let modified = modifyInfo(json['response']);
            if (modified)
                response.json = json;
        }
    } else if (req.url == '/method/execute.getUserInfo') {
        let json = response.json;
        if ('response' in json && 'info' in json['response']) {
            let modified = modifyInfo(json['response']['info']);
            if (modified)
                response.json = json;
        }
    }
};
<|endoftext|>


<commit_before>var Initializer = require("../initializer");
var raven       = require("raven");
var _           = require("lodash");
var domain      = require('domain');

Initializer.add('startup', 'stex.errors', ['stex.initialize-app'], function(stex) {

  /// catch 404 and forwarding to error handler
  stex.app.use(function(req, res, next) {
    res.send(404, {
      "status": "fail",
      "code":   "not_found"
    });
  });

  var sentryDsn = conf.get("sentryDsn");
  if(sentryDsn) {
    stex.app.use(raven.middleware.express(sentryDsn));
  }

  stex.app.use(logError);
  stex.app.use(renderErrorResponse);

  stex.reportError = function (err) {
    log.error(err);

    if (stex.sentry) {
      stex.sentry.captureError(err);
    }
  }
});

Initializer.add('startup', 'stex.request-domains', ['stex.express', 'stex.logging', 'stex.config'], function(stex) {
  var sentryDsn = conf.get("sentryDsn");
  var sentry = sentryDsn ? new raven.Client(sentryDsn) : null;

  stex.app.use(function (req, res, next) {
    var requestDomain = domain.create();
    var reportErrorDirectly = function(err) {
        stex.reportError;
    };

    requestDomain.on('error', function (err) {
        // if we have started sending a response when the error occurs
        // we can't go through the express error middlewares (since they
        // send a response).
        if(res.headersSent) {
            reportErrorDirectly(err);

            // force the response to be closed, such that we don't leave
            // orphan connections (i.e. headers have been sent, but an error
            // was then raised)
            res.end();
        } else {
            next(err);
        }
    });

    requestDomain.run(next);
  });
});

function logError(err, req, res, next) {
  var plainError = {};
  Object.getOwnPropertyNames(err).forEach(function(key) {
    plainError[key] = err[key];
  });

  plainError.className = err.constructor.name;
  cleanStack(plainError);

  log.error({
    type: "error",
    error: plainError
  });

  next(err);
}

function renderErrorResponse(err, req, res, next) {
  var response = {
    status:  'error',
    code:    err.status || 500,
    message: err.message
  };

  if(conf.get("showStackTraces") === true) {
    response.data = { stack: err.stack };
  }

  res.status(response.code).send(response);
}

function cleanStack(plainError) {
  if(typeof plainError.stack === "string") {
    var stackWithoutHeader = plainError.stack.split("\n").splice(1);
    var unindentedStack = _.map(stackWithoutHeader,function(line) {
      return line.substring(4);
    });

    plainError.stack = unindentedStack;
  } else {
    delete plainError.stack;
  }
}
<commit_msg>Update errors.js<commit_after>var Initializer = require("../initializer");
var raven       = require("raven");
var _           = require("lodash");
var domain      = require('domain');

Initializer.add('startup', 'stex.errors', ['stex.initialize-app'], function(stex) {

  /// catch 404 and forwarding to error handler
  stex.app.use(function(req, res, next) {
    res.send(404, {
      "status": "fail",
      "code":   "not_found"
    });
  });

  var sentryDsn = conf.get("sentryDsn");
  if(sentryDsn) {
    stex.app.use(raven.middleware.express(sentryDsn));
  }

  stex.app.use(logError);
  stex.app.use(renderErrorResponse);

  stex.reportError = function (err) {
    log.error(err);

    if (stex.sentry) {
      stex.sentry.captureError(err);
    }
  }
});

Initializer.add('startup', 'stex.request-domains', ['stex.express', 'stex.logging', 'stex.config'], function(stex) {
  var sentryDsn = conf.get("sentryDsn");
  var sentry = sentryDsn ? new raven.Client(sentryDsn) : null;

  stex.app.use(function (req, res, next) {
    var requestDomain = domain.create();
    var reportErrorDirectly = function(err) {
        stex.reportError(err);
    };

    requestDomain.on('error', function (err) {
        // if we have started sending a response when the error occurs
        // we can't go through the express error middlewares (since they
        // send a response).
        if(res.headersSent) {
            reportErrorDirectly(err);

            // force the response to be closed, such that we don't leave
            // orphan connections (i.e. headers have been sent, but an error
            // was then raised)
            res.end();
        } else {
            next(err);
        }
    });

    requestDomain.run(next);
  });
});

function logError(err, req, res, next) {
  var plainError = {};
  Object.getOwnPropertyNames(err).forEach(function(key) {
    plainError[key] = err[key];
  });

  plainError.className = err.constructor.name;
  cleanStack(plainError);

  log.error({
    type: "error",
    error: plainError
  });

  next(err);
}

function renderErrorResponse(err, req, res, next) {
  var response = {
    status:  'error',
    code:    err.status || 500,
    message: err.message
  };

  if(conf.get("showStackTraces") === true) {
    response.data = { stack: err.stack };
  }

  res.status(response.code).send(response);
}

function cleanStack(plainError) {
  if(typeof plainError.stack === "string") {
    var stackWithoutHeader = plainError.stack.split("\n").splice(1);
    var unindentedStack = _.map(stackWithoutHeader,function(line) {
      return line.substring(4);
    });

    plainError.stack = unindentedStack;
  } else {
    delete plainError.stack;
  }
}
<|endoftext|>


<commit_before>//var rp = require('request-promise');
var lrp = require('./system');

var InsightRestClient = module.exports = function(host, timeout_sec){
    this.host = host || 'https://insight.bitpay.com';
    this.timeout_sec = timeout_sec || 30;
}

InsightRestClient.prototype.status = function(q){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'status']), q ? {q:q} : void 0)
}

InsightRestClient.prototype.addr = function(btcaddress){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'addr', btcaddress]))
}

InsightRestClient.prototype.addrWithoutTx = function(btcaddress){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'addr', btcaddress]), { noTxList:1 })
}

InsightRestClient.prototype.block = function(blockhash){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'block', blockhash]))
}

InsightRestClient.prototype.blockIndex = function(height){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'block-index', height]))
}

InsightRestClient.prototype.transaction = function(txid){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'tx', txid]))
}

InsightRestClient.prototype.rawTransaction = function(txid){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'rawtx', txid]))
}

InsightRestClient.prototype.transactionsbyBlock = function(blockhash){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'txs', '']), { block : blockhash })
}

InsightRestClient.prototype.transactionsbyAddress = function(btcaddress){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'txs', '']), { address : btcaddress })
}

InsightRestClient.prototype.sendTransaction = function(rawtx){
    return postQuery(this.timeout_sec, makeApi(this.host, ['api', 'tx', 'send']), {rawtx : rawtx})
}

InsightRestClient.prototype.utxo = function(addresses){
    var addrs = (addresses instanceof Array) ? addresses.join(',') : addresses;
    return postQuery(this.timeout_sec, makeApi(this.host, ['api', 'addrs', 'utxo']), {addrs : addrs})
}

InsightRestClient.prototype.tx4addrs = function(addresses, opt){
    var addrs = (addresses instanceof Array) ? addresses.join(',') : addresses;
    opt = opt || {};
    return postQuery(this.timeout_sec, makeApi(this.host, ['api', 'addrs', 'txs']), {
        addrs : addrs,
        from : opt.from || 0,
        to : opt.to || 5,
    })
}

var makeApi = function(host, params){
    return [].concat([host], params).join('/');
}

var getQuery = function(timeout, uri, qs){
    var get = {
        method : 'GET',
        uri : uri,
        qs : qs || {},
        json : true,
        timeout : timeout * 1000,
    }
    return lrp.req(get)
}

var postQuery = function(timeout, uri, form){
    var post = {
        method : 'POST',
        uri : uri,
        form : form || {},
        json : true,
        timeout : timeout * 1000,
    }
    return lrp.req(post)
}
<commit_msg>Update insight-rest-client.js<commit_after>'use strict'
var lrp = require('./system');

var InsightRestClient = module.exports = function(host, timeout_sec){
    this.host = host || 'https://insight.bitpay.com';
    this.timeout_sec = timeout_sec || 30;
}

InsightRestClient.prototype.status = function(q){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'status']), q ? {q:q} : void 0)
}

InsightRestClient.prototype.addr = function(btcaddress){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'addr', btcaddress]))
}

InsightRestClient.prototype.addrWithoutTx = function(btcaddress){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'addr', btcaddress]), { noTxList:1 })
}

InsightRestClient.prototype.block = function(blockhash){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'block', blockhash]))
}

InsightRestClient.prototype.blockIndex = function(height){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'block-index', height]))
}

InsightRestClient.prototype.transaction = function(txid){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'tx', txid]))
}

InsightRestClient.prototype.rawTransaction = function(txid){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'rawtx', txid]))
}

InsightRestClient.prototype.transactionsbyBlock = function(blockhash){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'txs', '']), { block : blockhash })
}

InsightRestClient.prototype.transactionsbyAddress = function(btcaddress){
    return getQuery(this.timeout_sec, makeApi(this.host, ['api', 'txs', '']), { address : btcaddress })
}

InsightRestClient.prototype.sendTransaction = function(rawtx){
    return postQuery(this.timeout_sec, makeApi(this.host, ['api', 'tx', 'send']), {rawtx : rawtx})
}

InsightRestClient.prototype.utxo = function(addresses){
    var addrs = (addresses instanceof Array) ? addresses.join(',') : addresses;
    return postQuery(this.timeout_sec, makeApi(this.host, ['api', 'addrs', 'utxo']), {addrs : addrs})
}

InsightRestClient.prototype.tx4addrs = function(addresses, opt){
    var addrs = (addresses instanceof Array) ? addresses.join(',') : addresses;
    opt = opt || {};
    return postQuery(this.timeout_sec, makeApi(this.host, ['api', 'addrs', 'txs']), {
        addrs : addrs,
        from : opt.from || 0,
        to : opt.to || 5,
    })
}

var makeApi = function(host, params){
    return [].concat([host], params).join('/');
}

var getQuery = function(timeout, uri, qs){
    var get = {
        method : 'GET',
        uri : uri,
        qs : qs || {},
        json : true,
        timeout : timeout * 1000,
    }
    return lrp.req(get)
}

var postQuery = function(timeout, uri, form){
    var post = {
        method : 'POST',
        uri : uri,
        form : form || {},
        json : true,
        timeout : timeout * 1000,
    }
    return lrp.req(post)
}
<|endoftext|>


<commit_before>"use strict";

const IBase = require("./IBase");
const Utils = require("../core/Utils");
const Message = require("../models/Message");

const rest = require("../networking/rest");

/**
 * @interface
 * @model Message
 * @extends IBase
 */
class IMessage extends IBase {
  constructor(discordie, messageId) {
    super();
    Utils.definePrivate(this, {
      _discordie: discordie,
      _messageId: messageId
    });

    Object.freeze(this);
  }

  /**
   * Checks whether this message is cached.
   * @param {IMessage} message
   * @returns {boolean}
   * @readonly
   */
  get isCached() {
    return this.author != null;
  }

  /**
   * Checks whether this message was edited by the author.
   * Returns null if message does not exist in cache.
   * @returns {boolean|null}
   * @readonly
   */
  get isEdited() {
    return this.isCached ? this.edited_timestamp != null : null;
  }

  /**
   * Checks whether this message is from a private channel (direct message).
   * Returns null if message/channel does not exist in cache.
   * @returns {boolean|null}
   * @readonly
   */
  get isPrivate() {
    return this._discordie._channels.isPrivate(this.channel_id);
  }

  /**
   * Gets channel of this message.
   * Returns null if message does not exist in cache.
   * @returns {IChannel|IDirectMessageChannel|null}
   * @readonly
   */
  get channel() {
    if (this.isPrivate) {
      return this._discordie.DirectMessageChannels.get(this.channel_id);
    }
    return this._discordie.Channels.get(this.channel_id);
  }

  /**
   * Gets guild of this message.
   * Returns null if message does not exist in cache or from a private
   * channel (direct message).
   * @returns {IGuild|null}
   * @readonly
   */
  get guild() {
    if (this.isPrivate || !this.isCached) return null;
    return this.channel ? this.channel.guild : null;
  }

  /**
   * Gets member instance of author.
   * Returns null for private channels or if message does not exist in cache.
   * @returns {IGuildMember|null}
   * @readonly
   */
  get member() {
    if (this.isPrivate || !this.isCached) return null;
    return this._discordie.Users.getMember(this.guild.id, this.author.id);
  }

  /**
   * Creates an array of all known (cached) versions of this message (including
   * the latest).
   * Sorted from latest (first) to oldest (last).
   * Does not include embeds.
   * @returns {Array<Object>}
   * @readonly
   */
  get edits() {
    return this._discordie._messages.getEdits(this.id);
  }

  /**
   * Makes a request to edit this message.
   *
   * Editing of other users' messages is not allowed, server will send an
   * `Error` `Forbidden` and returned promise will be rejected if you attempt
   * to do so.
   *
   * See `IMessageCollection.editMessage` if you are looking for a method
   * that can operate on JSON or raw message id.
   * @param {String} content
   * @returns {Promise<IMessage, Error>}
   */
  edit(content) {
    return new Promise((rs, rj) => {
      rest(this._discordie)
        .channels.patchMessage(this.channel_id, this.id, content)
      .then(() => rs(this))
      .catch(rj);
    });
  }

  /**
   * Makes a request to delete this message.
   *
   * See `IMessageCollection.deleteMessage` if you are looking for a method
   * that can operate on JSON or raw message id.
   * @returns {Promise}
   */
  delete() {
    return rest(this._discordie)
      .channels.deleteMessage(this.channel_id, this.id);
  }

  /**
   * Makes a request to send a reply to channel the message was from, prefixing
   * content with author's mention in non-private channels.
   * @param {String} content
   * @param {IUser|IGuildMember|Array<IUser>|Array<IGuildMember>} [mentions]
   * @param {boolean} [tts]
   * @returns {Promise<IMessage, Error>}
   */
  reply(content, mentions, tts) {
    if (this.isPrivate) {
      return this.channel.sendMessage(content, mentions, tts);
    }
    return this.channel
      .sendMessage(`${this.author.mention}, ${content}`, mentions, tts);
  }
}

IMessage._inherit(Message, function modelPropertyGetter(key) {
  return this._discordie._messages.get(this._messageId)[key]
});

/**
 * @readonly
 * @instance
 * @memberOf IMessage
 * @name author
 * @returns {IUser}
 */
IMessage._setValueOverride("author", function(v) {
  return v ? this._discordie.Users.get(v.id) : null;
});

/**
 * @readonly
 * @instance
 * @memberOf IMessage
 * @name mentions
 * @returns {Array<IUser>}
 */
IMessage._setValueOverride("mentions", function(v) {
  return v ? v.map(u => this._discordie.Users.get(u.id)) : [];
});

IMessage._setSuppressErrors(true);

module.exports = IMessage;
<commit_msg>Use internal _valid for checking if message is in cache<commit_after>"use strict";

const IBase = require("./IBase");
const Utils = require("../core/Utils");
const Message = require("../models/Message");

const rest = require("../networking/rest");

/**
 * @interface
 * @model Message
 * @extends IBase
 */
class IMessage extends IBase {
  constructor(discordie, messageId) {
    super();
    Utils.definePrivate(this, {
      _discordie: discordie,
      _messageId: messageId
    });

    Object.freeze(this);
  }

  /**
   * Checks whether this message is cached.
   * @param {IMessage} message
   * @returns {boolean}
   * @readonly
   */
  get isCached() {
    return !!this._valid;
  }

  /**
   * Checks whether this message was edited by the author.
   * Returns null if message does not exist in cache.
   * @returns {boolean|null}
   * @readonly
   */
  get isEdited() {
    return this.isCached ? this.edited_timestamp != null : null;
  }

  /**
   * Checks whether this message is from a private channel (direct message).
   * Returns null if message/channel does not exist in cache.
   * @returns {boolean|null}
   * @readonly
   */
  get isPrivate() {
    return this._discordie._channels.isPrivate(this.channel_id);
  }

  /**
   * Gets channel of this message.
   * Returns null if message does not exist in cache.
   * @returns {IChannel|IDirectMessageChannel|null}
   * @readonly
   */
  get channel() {
    if (this.isPrivate) {
      return this._discordie.DirectMessageChannels.get(this.channel_id);
    }
    return this._discordie.Channels.get(this.channel_id);
  }

  /**
   * Gets guild of this message.
   * Returns null if message does not exist in cache or from a private
   * channel (direct message).
   * @returns {IGuild|null}
   * @readonly
   */
  get guild() {
    if (this.isPrivate || !this.isCached) return null;
    return this.channel ? this.channel.guild : null;
  }

  /**
   * Gets member instance of author.
   * Returns null for private channels or if message does not exist in cache.
   * @returns {IGuildMember|null}
   * @readonly
   */
  get member() {
    if (this.isPrivate || !this.isCached) return null;
    return this._discordie.Users.getMember(this.guild.id, this.author.id);
  }

  /**
   * Creates an array of all known (cached) versions of this message (including
   * the latest).
   * Sorted from latest (first) to oldest (last).
   * Does not include embeds.
   * @returns {Array<Object>}
   * @readonly
   */
  get edits() {
    return this._discordie._messages.getEdits(this.id);
  }

  /**
   * Makes a request to edit this message.
   *
   * Editing of other users' messages is not allowed, server will send an
   * `Error` `Forbidden` and returned promise will be rejected if you attempt
   * to do so.
   *
   * See `IMessageCollection.editMessage` if you are looking for a method
   * that can operate on JSON or raw message id.
   * @param {String} content
   * @returns {Promise<IMessage, Error>}
   */
  edit(content) {
    return new Promise((rs, rj) => {
      rest(this._discordie)
        .channels.patchMessage(this.channel_id, this.id, content)
      .then(() => rs(this))
      .catch(rj);
    });
  }

  /**
   * Makes a request to delete this message.
   *
   * See `IMessageCollection.deleteMessage` if you are looking for a method
   * that can operate on JSON or raw message id.
   * @returns {Promise}
   */
  delete() {
    return rest(this._discordie)
      .channels.deleteMessage(this.channel_id, this.id);
  }

  /**
   * Makes a request to send a reply to channel the message was from, prefixing
   * content with author's mention in non-private channels.
   * @param {String} content
   * @param {IUser|IGuildMember|Array<IUser>|Array<IGuildMember>} [mentions]
   * @param {boolean} [tts]
   * @returns {Promise<IMessage, Error>}
   */
  reply(content, mentions, tts) {
    if (this.isPrivate) {
      return this.channel.sendMessage(content, mentions, tts);
    }
    return this.channel
      .sendMessage(`${this.author.mention}, ${content}`, mentions, tts);
  }
}

IMessage._inherit(Message, function modelPropertyGetter(key) {
  return this._discordie._messages.get(this._messageId)[key]
});

/**
 * @readonly
 * @instance
 * @memberOf IMessage
 * @name author
 * @returns {IUser}
 */
IMessage._setValueOverride("author", function(v) {
  return v ? this._discordie.Users.get(v.id) : null;
});

/**
 * @readonly
 * @instance
 * @memberOf IMessage
 * @name mentions
 * @returns {Array<IUser>}
 */
IMessage._setValueOverride("mentions", function(v) {
  return v ? v.map(u => this._discordie.Users.get(u.id)) : [];
});

module.exports = IMessage;
<|endoftext|>


<commit_before>// Copyright 2014-2015, Renasar Technologies Inc.
/* jshint: node:true */
'use strict';

var di = require('di');

module.exports = runWorkItemsJobFactory;
di.annotate(runWorkItemsJobFactory, new di.Provide('Job.WorkItems.Run'));
di.annotate(runWorkItemsJobFactory, new di.Inject(
    'Job.Base',
    'Services.Waterline',
    'Logger',
    'Util',
    'uuid',
    'Q',
    'Assert',
    '_'
));

function runWorkItemsJobFactory(
    BaseJob,
    waterline,
    Logger,
    util,
    uuid,
    Q,
    assert,
    _
) {

    var logger = Logger.initialize(runWorkItemsJobFactory);

    /**
     *
     * @param {Object} [options]
     * @constructor
     */
    function RunWorkItemsJob(options, context, taskId) {
        RunWorkItemsJob.super_.call(this, logger, options, context, taskId);

        this.routingKey = this.context.graphId;
        assert.uuid(this.routingKey) ;

        _.defaults(this.options, {
            queuePollInterval: 1 * 1000,
            defaultLeaseDuration: 15 * 1000,
        });

        this.workerId = uuid();
        this._running = false;

        this._workItemCallbacks = {
            'Pollers.IPMI': this._executeIpmiPoller.bind(this),
            'Pollers.SNMP': this._executeSnmpPoller.bind(this)
        };
    }

    util.inherits(RunWorkItemsJob, BaseJob);

    /**
     * @memberOf RunWorkItemsJob
     */

    RunWorkItemsJob.prototype._run = function _run() {
        var self = this;
        self.on('done', function () {
            self._running = false;
        });
        self._running = true;

        self._runWorkItems().catch(function (err) {
            if (self._running) {
                self._done(err);
            }
        });
    };

    RunWorkItemsJob.prototype._runWorkItems = function _runWorkItems() {
        var self = this;
        return self._getWorkItem().then(function (workItem) {
            if (!workItem) {
                if (!self._running) {
                    return;
                }
                return Q.delay(self.options.queuePollInterval);
            }
            return self._executeWorkItem(workItem).then(function () {
                return waterline.workitems.setSucceeded(self.workerId, workItem);
            }).catch(function (err) {
                self.logger.error("Work item failed.", {
                    error: err,
                    taskId: self.taskId,
                    workitemId: workItem.id
                });

                return waterline.workitems.setFailed(self.workerId, workItem);
            });
        }).then(function () {
            return self._runWorkItems();
        });
    };

    RunWorkItemsJob.prototype._getWorkItem = function _getWorkItem() {
        var self = this;

        if (!self._running) {
            return Q.resolve();
        }

        return waterline.workitems.startNextScheduled(
            self.workerId,
            {},
            self.options.defaultLeaseDuration
        );
    };

    RunWorkItemsJob.prototype._executeWorkItem = function _executeWorkItem(workItem) {
        var self = this;
        var func = self._workItemCallbacks[workItem.name];
        if (func) {
            return func(workItem);
        }
        return Q.reject('Unknown work item: ' + workItem.name);
    };

    RunWorkItemsJob.prototype._executeIpmiPoller = function _executeIpmiPoller(workItem) {
        var self = this;

        assert.object(workItem.config, 'workItem.config');
        assert.string(workItem.config.command, 'workItem.config.command');

        var obmConfigFound = Q.resolve();
        if (workItem.node) {
            obmConfigFound = waterline.nodes.findOne(workItem.node).then(function (node) {
                if (node) {
                    var obmSetting = _.find(node.obmSettings, { service: 'ipmi-obm-service' });
                    if (obmSetting) {
                        return obmSetting.config;
                    }
                }
            });
        }
        return obmConfigFound.then(function (obmSettings) {
            var data = _.assign({},
                                obmSettings,
                                _.omit(workItem.config, 'command'),
                                { workItemId: workItem.id });
            return self._publishRunIpmiCommand(self.routingKey, workItem.config.command, data);
        });
    };

    RunWorkItemsJob.prototype._executeSnmpPoller = function _executeSnmpPoller(workItem) {
        assert.object(workItem.config, 'workItem.config');

        var config = _.assign({}, workItem.config, {
            workItemId: workItem.id
        });

        return this._publishRunSnmpCommand(this.routingKey, config);
    };

    return RunWorkItemsJob;
}
<commit_msg>Adding log statement to run work items job<commit_after>// Copyright 2014-2015, Renasar Technologies Inc.
/* jshint: node:true */
'use strict';

var di = require('di');

module.exports = runWorkItemsJobFactory;
di.annotate(runWorkItemsJobFactory, new di.Provide('Job.WorkItems.Run'));
di.annotate(runWorkItemsJobFactory, new di.Inject(
    'Job.Base',
    'Services.Waterline',
    'Logger',
    'Util',
    'uuid',
    'Q',
    'Assert',
    '_'
));

function runWorkItemsJobFactory(
    BaseJob,
    waterline,
    Logger,
    util,
    uuid,
    Q,
    assert,
    _
) {

    var logger = Logger.initialize(runWorkItemsJobFactory);

    /**
     *
     * @param {Object} [options]
     * @constructor
     */
    function RunWorkItemsJob(options, context, taskId) {
        RunWorkItemsJob.super_.call(this, logger, options, context, taskId);

        this.routingKey = this.context.graphId;
        assert.uuid(this.routingKey) ;

        _.defaults(this.options, {
            queuePollInterval: 1 * 1000,
            defaultLeaseDuration: 15 * 1000,
        });

        this.workerId = uuid();
        this._running = false;

        this._workItemCallbacks = {
            'Pollers.IPMI': this._executeIpmiPoller.bind(this),
            'Pollers.SNMP': this._executeSnmpPoller.bind(this)
        };
    }

    util.inherits(RunWorkItemsJob, BaseJob);

    /**
     * @memberOf RunWorkItemsJob
     */

    RunWorkItemsJob.prototype._run = function _run() {
        var self = this;
        self.on('done', function () {
            self._running = false;
        });
        self._running = true;

        self._runWorkItems().catch(function (err) {
            if (self._running) {
                self._done(err);
            }
        });
    };

    RunWorkItemsJob.prototype._runWorkItems = function _runWorkItems() {
        var self = this;
        return self._getWorkItem().then(function (workItem) {
            if (!workItem) {
                if (!self._running) {
                    return;
                }
                return Q.delay(self.options.queuePollInterval);
            }
            return self._executeWorkItem(workItem).then(function () {
                return waterline.workitems.setSucceeded(self.workerId, workItem);
            }).catch(function (err) {
                self.logger.error("Work item failed.", {
                    error: err,
                    taskId: self.taskId,
                    workitemId: workItem.id
                });

                return waterline.workitems.setFailed(self.workerId, workItem);
            });
        }).then(function () {
            return self._runWorkItems();
        });
    };

    RunWorkItemsJob.prototype._getWorkItem = function _getWorkItem() {
        var self = this;

        if (!self._running) {
            return Q.resolve();
        }

        return waterline.workitems.startNextScheduled(
            self.workerId,
            {},
            self.options.defaultLeaseDuration
        );
    };

    RunWorkItemsJob.prototype._executeWorkItem = function _executeWorkItem(workItem) {
        var self = this;
        var func = self._workItemCallbacks[workItem.name];
        if (func) {
            logger.silly('Executing Work Item', {
                id: workItem.id,
                name: workItem.name
            });
            return func(workItem);
        }
        return Q.reject('Unknown work item: ' + workItem.name);
    };

    RunWorkItemsJob.prototype._executeIpmiPoller = function _executeIpmiPoller(workItem) {
        var self = this;

        assert.object(workItem.config, 'workItem.config');
        assert.string(workItem.config.command, 'workItem.config.command');

        var obmConfigFound = Q.resolve();
        if (workItem.node) {
            obmConfigFound = waterline.nodes.findOne(workItem.node).then(function (node) {
                if (node) {
                    var obmSetting = _.find(node.obmSettings, { service: 'ipmi-obm-service' });
                    if (obmSetting) {
                        return obmSetting.config;
                    }
                }
            });
        }
        return obmConfigFound.then(function (obmSettings) {
            var data = _.assign({},
                                obmSettings,
                                _.omit(workItem.config, 'command'),
                                { workItemId: workItem.id });
            return self._publishRunIpmiCommand(self.routingKey, workItem.config.command, data);
        });
    };

    RunWorkItemsJob.prototype._executeSnmpPoller = function _executeSnmpPoller(workItem) {
        assert.object(workItem.config, 'workItem.config');

        var config = _.assign({}, workItem.config, {
            workItemId: workItem.id
        });

        return this._publishRunSnmpCommand(this.routingKey, config);
    };

    return RunWorkItemsJob;
}
<|endoftext|>


<commit_before>const {Group, QuantifiedValue, CodeFromValueSetValue, CodeFromAncestorValue, RefValue, OrValues} = require('../models');

class Dictionary {
  constructor() {
    this._map = {};
  }

  registerNamespace(ns) {
    this._map[ns.namespace] = ns;
  }

  lookup(identifier) {
    const ns = this._map[identifier.namespace];
    if (typeof ns != 'undefined') {
      return ns.lookup(identifier.name);
    }
  }
}

function exportToMarkdown(namespaces, alsoIncludeIndividuals=false) {
  const dictionary = new Dictionary();
  for (const ns of namespaces) {
    dictionary.registerNamespace(ns);
  }

  const results = {};
  for (const ns of namespaces) {
    const mds = [];
    for (const def of ns.definitions) {
      try {
        mds.push(defToMarkdown(def, dictionary));
      } catch(e) {
        console.error(`Failed to export ${def.identifier.fqn} to Markdown\n  `, e);
      }
    }
    const nsMD = `# ${ns.namespace}\n\n${mds.join('\n\n')}`;
    results[ns.namespace] = { markdown: nsMD, defMarkdowns: mds };
  }
  return results;
}

function defToMarkdown(def, dictionary) {
  let name = def.identifier.name;
  if (def.isEntry) {
    name += ' [Entry]';
  }
  let md = `### ${name}\n`;
  if (typeof def.description != 'undefined') {
    md += `${def.description} `;
  }

  if (def.concepts.length > 0) {
    for (const concept of def.concepts) {
      md += `${conceptToMarkdown(concept)}, `;
    }
    md = md.slice(0, -2);
  }
  md += `\n\n`;

  md += `|---|---|---|\n`;
  if (def instanceof Group) {
    for (const el of def.elements) {
      md += `| \`${el.value.identifier.name}\` | ${quantifiedValueToMarkdown(el)} | ${elementDescription(el, dictionary)} ||\n`;
    }
  } else {
    md += `| Type | ${valueToMarkdown(def.value)} ||\n`;
  }
  return md.slice(0, -1); // removes trailing newline
}

function quantifiedValueToMarkdown(value) {
  let card = '';
  if (value instanceof QuantifiedValue) {
    if (value.min == 0 && value.max == 1) {
      card = 'optional ';
    } else if (value.isMaxUnbounded()) {
      card = `${value.min} or more `;
    } else if (value.min == value.max) {
      card = value.min == 1 ? '' : `${value.min} `;
    } else {
      card = `${value.min} to ${value.max} `;
    }
  }
  return card;
}

function elementDescription(el, dictionary) {
  const value = el.value;

  if (value instanceof OrValues) {
    // ?
    let md = `Choice of: <ul>`;
    for (const option of value.values) {
      md += `<li>${valueToMarkdown(option)}</li>`;
    }
    return md + '
';
  }

  const def = dictionary.lookup(value.identifier);
  if (def && def.description) {
    return def.description;
  }

  return '';
}

function valueToMarkdown(value) {
  if (value instanceof QuantifiedValue) {
    value = value.value;
  }

  if (value instanceof OrValues) {
    let md = `Choice of: <ul>`;
    for (const option of value.values) {
      md += `<li>${valueToMarkdown(option)}</li>`;
    }
    return md + '
';
  } else {
    return typeToMarkdown(value);
  }
}

function typeToMarkdown(value) {
  if (value instanceof CodeFromValueSetValue) {
    return `code from ${value.valueset}`;
  } else if (value instanceof CodeFromAncestorValue) {
    return `code descending from ${conceptToMarkdown(value.ancestor)}`;
  } else if (value instanceof RefValue) {
    return `reference to ${identifierToMarkdown(value.identifier)}`;
  } else if (value.identifier.isPrimitive()) {
    return value.identifier.name;
  }

  // We fell through, so this is another element or entry type
  return identifierToMarkdown(value.identifier);
}

function conceptToMarkdown(concept) {
  var url;
  switch (concept.codesystem) {
  case 'http://uts.nlm.nih.gov/metathesaurus':
    url = `https://uts.nlm.nih.gov/metathesaurus.html?cui=${concept.code}`;
    break;
  case 'http://snomed.info/sct':
    url = `https://uts.nlm.nih.gov/snomedctBrowser.html?conceptId=${concept.code}`;
    break;
  case 'http://loinc.org':
    url = `http://s.details.loinc.org/LOINC/${concept.code}.html`;
    break;
  case 'http://unitsofmeasure.org':
    url = 'http://unitsofmeasure.org/ucum.html#section-Alphabetic-Index-By-Symbol';
    break;
  case '':
  // http://browser.ihtsdotools.org/?perspective=full&conceptId1=404684003&edition=us-edition&release=v20160901&server=https://browser-aws-1.ihtsdotools.org/api/snomed&langRefset=900000000000509007
    url = `${concept.codesystem}/${concept.code}`;
    break;
  default:
    url = `${concept.codesystem}/${concept.code}`;
  }
  let md = `[${concept.code}](${url})`;
  if (concept.label) {
    md = `${md} _(${concept.label})_`;
  }
  return md;
}

function identifierToMarkdown(identifier) {
  return `${identifier.namespace}.${identifier.name}`;
}

module.exports = {exportToMarkdown};<commit_msg>added slightly better links<commit_after>const {Group, QuantifiedValue, CodeFromValueSetValue, CodeFromAncestorValue, RefValue, OrValues} = require('../models');

class Dictionary {
  constructor() {
    this._map = {};
  }

  registerNamespace(ns) {
    this._map[ns.namespace] = ns;
  }

  lookup(identifier) {
    const ns = this._map[identifier.namespace];
    if (typeof ns != 'undefined') {
      return ns.lookup(identifier.name);
    }
  }
}

function exportToMarkdown(namespaces, alsoIncludeIndividuals=false) {
  const dictionary = new Dictionary();
  for (const ns of namespaces) {
    dictionary.registerNamespace(ns);
  }

  const results = {};
  for (const ns of namespaces) {
    const mds = [];
    let defs = ns.definitions.sort(function(l,r) {return l.identifier.name.localeCompare(r.identifier.name)})
    for (const def of defs) {
      try {
        mds.push(defToMarkdown(def, dictionary));
      } catch(e) {
        console.error(`Failed to export ${def.identifier.fqn} to Markdown\n  `, e);
      }
    }
    const nsMD = `# ${ns.namespace}\n\n${mds.join('\n\n')}`;
    results[ns.namespace] = { markdown: nsMD, defMarkdowns: mds };
  }
  return results;
}

function defToMarkdown(def, dictionary) {
  let name = def.identifier.name;
  if (def.isEntry) {
    name += ' [Entry]';
  }
  let md = `### ${name}\n`;
  if (typeof def.description != 'undefined') {
    md += `${def.description} `;
  }

  if (def.concepts.length > 0) {
    for (const concept of def.concepts) {
      md += `${conceptToMarkdown(concept)}, `;
    }
    md = md.slice(0, -2);
  }
  md += `\n\n`;

  md += `|---|---|---|\n`;
  if (def instanceof Group) {
    for (const el of def.elements) {
      if (el.value instanceof OrValues) {
        md += `|Choice|${quantifiedValueToMarkdown(el)}||\n`;

        for (const option of el.value.values) {
          md += `|        \\| [\`${option.identifier.name}\`](#bar) | ${quantifiedValueToMarkdown(option)} | ${elementDescription(option, dictionary)} |\n`;
        }
    } else {

        md += `| [\`${el.value.identifier.name}\`](../${el.value.identifier.namespace.split('.').splice(-1)}/#${el.value.identifier.name}) | ${quantifiedValueToMarkdown(el)} | ${elementDescription(el, dictionary)} |\n`;
      }
    }
  } else {
    md += `| \`Value\` | ${valueToMarkdown(def.value)} ||\n`;
  }
  return md.slice(0, -1); // removes trailing newline
}

function quantifiedValueToMarkdown(value) {
  let card = '';
  if (value instanceof QuantifiedValue) {
    if (value.min == 0 && value.max == 1) {
      card = 'optional ';
    } else if (value.isMaxUnbounded()) {
      card = `${value.min} or more `;
    } else if (value.min == value.max) {
      card = value.min == 1 ? '' : `${value.min} `;
    } else {
      card = `${value.min} to ${value.max} `;
    }
  }
  return card;
}

function elementDescription(value, dictionary) {

  if (value instanceof QuantifiedValue) {
    value = value.value;
  }

  if (value instanceof OrValues) {
    // ?
    let md = `Choice of: <ul>`;
    for (const option of value.values) {
      md += `<li>${valueToMarkdown(option)}</li>`;
    }
    return md + '
';
  }

  const def = dictionary.lookup(value.identifier);
  if (def && def.description) {
    return def.description;
  }

  return '';
}

function valueToMarkdown(value) {
  if (value instanceof QuantifiedValue) {
    value = value.value;
  }

  if (value instanceof OrValues) {
    let md = `Choice of: <ul>`;
    for (const option of value.values) {
      md += `<li>${valueToMarkdown(option)}</li>`;
    }
    return md + '
';
  } else {
    return typeToMarkdown(value);
  }
}

function typeToMarkdown(value) {
  if (value instanceof CodeFromValueSetValue) {
    return `code from ${value.valueset}`;
  } else if (value instanceof CodeFromAncestorValue) {
    return `code descending from ${conceptToMarkdown(value.ancestor)}`;
  } else if (value instanceof RefValue) {
    return `reference to ${identifierToMarkdown(value.identifier)}`;
  } else if (value.identifier.isPrimitive()) {
    return value.identifier.name;
  }

  // We fell through, so this is another element or entry type
  return `[${value.identifier.name}](../${value.identifier.namespace.split('.').splice(-1)}/#${value.identifier.name})`;
}

function conceptToMarkdown(concept) {
  var url;
  switch (concept.codesystem) {
  case 'http://uts.nlm.nih.gov/metathesaurus':
    url = `https://uts.nlm.nih.gov/metathesaurus.html?cui=${concept.code}`;
    break;
  case 'http://snomed.info/sct':
    url = `https://uts.nlm.nih.gov/snomedctBrowser.html?conceptId=${concept.code}`;
    break;
  case 'http://loinc.org':
    url = `http://s.details.loinc.org/LOINC/${concept.code}.html`;
    break;
  case 'http://unitsofmeasure.org':
    url = 'http://unitsofmeasure.org/ucum.html#section-Alphabetic-Index-By-Symbol';
    break;
  case '':
  // http://browser.ihtsdotools.org/?perspective=full&conceptId1=404684003&edition=us-edition&release=v20160901&server=https://browser-aws-1.ihtsdotools.org/api/snomed&langRefset=900000000000509007
    url = `${concept.codesystem}/${concept.code}`;
    break;
  default:
    url = `${concept.codesystem}/${concept.code}`;
  }
  let md = `[${concept.code}](${url})`;
  if (concept.label) {
    md = `${md} _(${concept.label})_`;
  }
  return md;
}

function identifierToMarkdown(identifier) {
  return `${identifier.namespace}.${identifier.name}`;
}

module.exports = {exportToMarkdown};<|endoftext|>