<commit_before>const path = require('path');

const brunch = require('brunch');
const fs = require('fs-extra');
const install = require('deps-install');
const logger = require('loggy');

const cleanURL = require('./clean-url.js');
const printBanner = require('./print-banner.js');

const defaultCommandName = 'aframe new';
const defaultTemplateAlias = 'aframe-default-template';
const defaultTemplateUrl = `aframevr-userland/${defaultTemplateAlias}`;

const initTemplate = (templateAlias, options) => {
  options = options || {};

  const cwd = process.cwd();

  const rootPath = path.resolve(options.rootPath || cwd).trim();
  const commandName = options.commandName || defaultCommandName;

  if (!templateAlias || typeof templateAlias !== 'string' ||
      templateAlias.charAt(0) === '.' && rootPath === cwd) {
    return printBannerAndExit(commandName);
  }

  const copyTemplateDir = () => {
    logger.log(`Using template "${templateAlias}" …`);

    const filter = filepath => !/^\.(git|hg|svn)$/.test(path.basename(filepath));
    logger.log(`Copying local template to "${rootPath}" …`);

    // TODO: Perhaps have `rootPath` default to `my-aframe-project`.
    return fs.copy(templateDir, rootPath, {errorOnExist: true, filter}).then(() => {
      const pkgType = ['package', 'bower'];
      return install({
        rootPath,
        pkgType,
        logger
      });
    });
  };

  let templateDir = path.join(__dirname, '..', 'templates', templateAlias);

  if (fs.existsSync(templateDir)) {
    return copyTemplateDir();
  }

  templateAlias = `aframe-${templateAlias}-template`;
  templateDir = path.join(__dirname, '..', 'templates', templateAlias);

  if (fs.existsSync(templateDir)) {
    return copyTemplateDir();
  }

  if (templateAlias.indexOf('/') === -1 && templateAlias.startsWith('aframe-')) {
    templateAlias = 'aframevr-userland/' + templateAlias;
  }

  const initSkeleton = require('init-skeleton').init;

  logger.log(`Using template "${templateAlias}" …`);

  return initSkeleton(templateAlias, {
    logger,
    rootPath,
    commandName
  });
};

exports.init = initTemplate;
exports.cleanURL = cleanURL;
exports.printBanner = commandName => {
  return printBanner(commandName).catch(err => {
    // console.log(err.message);
  });
};
<commit_msg>fix `aframe new --template` to work with external Git repos (fixes #78)<commit_after>const path = require('path');

const fs = require('fs-extra');
const install = require('deps-install');
const logger = require('loggy');

const cleanURL = require('./clean-url.js');
const printBanner = require('./print-banner.js');

const defaultCommandName = 'aframe new';

const initTemplate = (templateAlias, options) => {
  options = options || {};

  const cwd = process.cwd();

  const rootPath = path.resolve(options.rootPath || cwd).trim();
  const commandName = options.commandName || defaultCommandName;

  if (!templateAlias || typeof templateAlias !== 'string' ||
      templateAlias.charAt(0) === '.' && rootPath === cwd) {
    printBanner(defaultCommandName);
    process.exit(1);
  }

  const copyTemplateDir = dir => {
    logger.log(`Using template "${templateAlias}" …`);

    const filter = filepath => !/^\.(git|hg|svn)$/.test(path.basename(filepath));
    logger.log(`Copying local template to "${rootPath}" …`);

    // TODO: Perhaps have `rootPath` default to `my-aframe-project`.
    return fs.copy(dir, rootPath, {errorOnExist: true, filter}).then(() => {
      const pkgType = ['package', 'bower'];
      return install({
        rootPath,
        pkgType,
        logger
      });
    });
  };

  let templateDir = path.join(__dirname, '..', 'templates', templateAlias);

  if (fs.existsSync(templateDir)) {
    return copyTemplateDir(templateDir);
  }

  const localTemplateAlias = `aframe-${templateAlias}-template`;
  const localTemplateDir = path.join(__dirname, '..', 'templates', localTemplateAlias);

  if (fs.existsSync(localTemplateDir)) {
    return copyTemplateDir(localTemplateDir);
  }

  if (templateAlias.indexOf('/') === -1 && templateAlias.startsWith('aframe-')) {
    templateAlias = 'aframevr-userland/' + templateAlias;
  }

  const initSkeleton = require('init-skeleton').init;

  logger.log(`Using template "${templateAlias}" …`);

  return initSkeleton(templateAlias, {
    logger,
    rootPath,
    commandName
  });
};

exports.init = initTemplate;

exports.cleanURL = cleanURL;
<|endoftext|>


<commit_before>(function() {
  'use strict';

  var app     = this.app
    , _       = require('lodash')
    , debug   = require('debug')('signalk-server:interfaces:ws')
    , Primus  = require('primus')
    , primus  = new Primus(app.server, {
      transformer: 'websockets',
      pathname: '/signalk/stream' })
  ;

  app.connections = {};

  debug('Starting Primus/WS interface');

  primus.on('connection', function(spark) {
    debug(spark.id + " connected with params " + JSON.stringify(spark.query));

    var onChange;
    if (spark.query.stream === 'delta') {
      onChange = function(data) {
        spark.write(data);
      }
    } else {
      onChange = function(data) {
        spark.write(app.signalk.retrieve());
      };
      spark.write(app.signalk.retrieve());//output tree after connect
    }

    app.signalk.on('change', function(data) {
      onChange(data);
    });
    spark.onDisconnect = function() {
      app.signalk.removeListener('change', onChange);
    }

    app.connections[spark.id] = spark;
  });

  primus.on('disconnection', function(spark) {
    spark.onDisconnect();
    debug(spark.id + " disconnected");
  });

}).call(global);<commit_msg>Change delta to use 'change:delta' event<commit_after>(function() {
  'use strict';

  var app     = this.app
    , _       = require('lodash')
    , debug   = require('debug')('signalk-server:interfaces:ws')
    , Primus  = require('primus')
    , primus  = new Primus(app.server, {
      transformer: 'websockets',
      pathname: '/signalk/stream' })
  ;

  app.connections = {};

  debug('Starting Primus/WS interface');

  primus.on('connection', function(spark) {
    debug(spark.id + " connected with params " + JSON.stringify(spark.query));

    var onChange;
    var event;
    if (spark.query.stream === 'delta') {
      event = 'change:delta';
      onChange = function(data) {
        spark.write(data);
      }
    } else {
      event = 'change';
      onChange = function(data) {
        spark.write(app.signalk.retrieve());
      };
      spark.write(app.signalk.retrieve());//output tree after connect
    }

    app.signalk.on(event, function(data) {
      onChange(data);
    });
    spark.onDisconnect = function() {
      app.signalk.removeListener(event, onChange);
    }

    app.connections[spark.id] = spark;
  });

  primus.on('disconnection', function(spark) {
    spark.onDisconnect();
    debug(spark.id + " disconnected");
  });

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


<commit_before>/*-
 * Copyright 2015 Peculiar Ventures
 *
 * 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.
 */

/**
 * Handles decryption.
 *
 * @param cryptographer  an instance of WebCryptographer (or equivalent). Keep
 *                       in mind that decryption mutates the cryptographer.
 * @param rsa_key        private RSA key in json format. Parameters can be base64
 *                       encoded, strings or number (for 'e').
 *
 * @author Patrizio Bruno <patrizio@desertconsulting.net>
 */
JoseJWS.Signer = function(cryptographer, rsa_key) {
  "use strict";
  this.cryptographer = cryptographer;
  this.rsa_key = rsa_key;
  this.key_promise = Jose.Utils.importRsaPrivateKey(rsa_key, cryptographer.getContentSignAlgorithm(), "sign");

  this.headers = {};
};

JoseJWS.Signer.prototype.getHeaders = function() {
  "use strict";
  return this.headers;
};

/**
 * Computes signature.
 *
 * @param payload json or String to be signed
 * @param aad protected header (JS object)
 * @param header unprotected header (JS object)
 * @return Promise<String>
 */
JoseJWS.Signer.prototype.sign = function(payload, aad, header) {
  "use strict";

  var that = this,
    kid = Jose.WebCryptographer.keyId(that.rsa_key);

  if (!aad) {
    aad = {};
  }

  if (!aad.alg) {
    aad.alg = cryptographer.getContentSignAlgorithm();
    aad.typ = "JWT";
  }

  if(!aad.kid) {
    aad.kid = kid;
  }

  if(!header.kid) {
    header.kid = kid;
  }

  if (Utils.isString(payload)) {
    payload = Utils.arrayFromString(payload);
  } else {
    try {
      payload = Utils.arrayish(payload);
    } catch (e) {
      if (payload instanceof Object) {
        payload = Utils.arrayFromString(JSON.stringify(payload));
      }
    }
  }

  return this.cryptographer.sign(aad, payload, this.key_promise).then(function(signature) {
    return new JWS(aad, header, payload, signature);
  });
};

/**
 * Initialize a JWS object.
 *
 * @param protectedHeader protected header (JS object)
 * @param payload Uint8Array payload to be signed
 * @param signature ArrayBuffer signature of the payload
 * @param header unprotected header (JS object)
 *
 * @constructor
 */
var JWS = function(protectedHeader, header, payload, signature) {
  var that = this;
  that.header = header;
  that.payload = Utils.Base64Url.encodeArray(payload);
  that.signature = Utils.Base64Url.encodeArray(signature);
  that.signatures = [{kid: header.kid, signature: that.signature}];
  that.protected = Utils.Base64Url.encode(JSON.stringify(protectedHeader));
};

/**
 * Serialize a JWS object using the JSON serialization format
 *
 * @returns {Object} a copy of this
 */
JWS.prototype.JsonSerialize = function() {
  return JSON.stringify(this);
};

/**
 * Serialize a JWS object using the Compact Serialization Format
 *
 * @returns {string} BASE64URL(UTF8(PROTECTED HEADER)).BASE64URL(PAYLOAD).BASE64URL(SIGNATURE)
 */
JWS.prototype.CompactSerialize = function() {
  var that = this;
  return that.protected + '.' + that.payload + '.' + that.signature;
};
<commit_msg>add preliminary support for multiple signatures<commit_after>/*-
 * Copyright 2015 Peculiar Ventures
 *
 * 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.
 */

/**
 * Handles decryption.
 *
 * @param cryptographer  an instance of WebCryptographer (or equivalent). Keep
 *                       in mind that decryption mutates the cryptographer.
 * @param rsa_key        private RSA key in json format. Parameters can be base64
 *                       encoded, strings or number (for 'e').
 *
 * @author Patrizio Bruno <patrizio@desertconsulting.net>
 */
JoseJWS.Signer = function(cryptographer) {
  "use strict";
  var that = this;
  that.cryptographer = cryptographer;

  that.key_promises = {};
  that.waiting_kid = 0;
  that.headers = {};
  that.signer_aads = {};
  that.signer_headers = {};
};

/**
 * Adds a signer to JoseJWS instance. It'll be the on of the signers of the resulting JWS.
 *
 * @param rsa_key        private RSA key in json format. Parameters can be base64
 *                       encoded, strings or number (for 'e').
 */
JoseJWS.Signer.prototype.addSigner = function(rsa_key, key_id, aad, header) {
  var that = this,
    key_promise = Jose.Utils.importRsaPrivateKey(rsa_key, cryptographer.getContentSignAlgorithm(), "sign"),
    kid_promise;

  if (key_id) {
    kid_promise = new Promise(function(resolve, reject) {
      resolve(key_id);
    });
  } else {
    kid_promise = Jose.WebCryptographer.keyId(rsa_key);
  }

  that.waiting_kid++;

  return kid_promise.then(function(kid) {
    that.key_promises[kid] = key_promise;
    that.waiting_kid--;
    if (aad) that.signer_aads[kid] = aad;
    if (header) that.signer_headers[kid] = header;
    return kid;
  });
};

JoseJWS.Signer.prototype.getHeaders = function() {
  "use strict";
  return this.headers;
};

/**
 * Adds a signature to a JWS object
 * @param jws JWS Object to be signed or its representation
 * @param aad     Object protected header
 * @param header  Object unprotected header
 * @return Promise<String>
 */
JoseJWS.Signer.prototype.addSignature = function(jws, aad, header) {

  var that = this;

  if (Utils.isString(jws)) {
    jws = JSON.parse(jws);
  }

  if (jws.payload && Utils.isString(jws.payload) &&
    jws.protected && Utils.isString(jws.protected) &&
    jws.header && jws.header instanceof Object &&
    jws.signature && Utils.isString(jws.signature)) {
    return that.sign(JWS.fromObject(jws), aad, header);
  } else {
    throw new Error("JWS is not a valid JWS object");
  }
};

/**
 * Computes signature.
 *
 * @param payload JWS Object or String to be signed
 * @param aad     Object protected header
 * @param header  Object unprotected header
 * @return Promise<JWS>
 */
JoseJWS.Signer.prototype.sign = function(payload, aad, header) {
  "use strict";

  var that = this,
    check,
    kids = [];

  for (var ck in that.key_promises) {
    check = true;
    break;
  }

  if (!check) {
    throw new Error("No signers defined. At least one is required to sign the JWS.");
  }

  if (that.waiting_kid) {
    throw new Error("still generating key IDs");
  }

  function sign(message, protectedHeader, unprotectedHeader, rsa_key_promise, kid) {

    var toBeSigned;

    if (!protectedHeader) {
      protectedHeader = {};
    }

    if (!protectedHeader.alg) {
      protectedHeader.alg = cryptographer.getContentSignAlgorithm();
      protectedHeader.typ = "JWT";
    }

    if (!protectedHeader.kid) {
      protectedHeader.kid = kid;
    }

    if (Utils.isString(message)) {
      toBeSigned = Utils.arrayFromString(message);
    } else {
      try {
        toBeSigned = Utils.arrayish(message);
      } catch (e) {
        if (message instanceof JWS) {
          toBeSigned = Utils.arrayFromString(Utils.Base64Url.decode(message.payload));
        } else if (message instanceof Object) {
          toBeSigned = Utils.arrayFromString(JSON.stringify(message));
        } else {
          throw new Error("cannot sign this message");
        }
      }
    }

    return that.cryptographer.sign(protectedHeader, toBeSigned, rsa_key_promise).then(function(signature) {
      var jws = new JWS(protectedHeader, unprotectedHeader, toBeSigned, signature);
      if (message instanceof JWS) {
        delete jws.payload;
        if (!message.signatures) {
          message.signatures = [jws];
        } else {
          message.signatures.push(jws);
        }
        return message;
      }
      return jws;
    });
  }

  function doSign(pl, ph, uh, kps, kids) {
    if (kids.length) {
      var k_id = kids.shift();
      var rv = sign(pl, ph || that.signer_aads[k_id], uh || that.signer_headers[k_id], kps[k_id], k_id);
      if(kids.length) {
        rv = rv.then(function(jws) {
          return doSign(jws, null, null, kps, kids);
        });
      }
      return rv;
    }
  }

  for (var kid in that.key_promises) {
    kids.push(kid);
  }
  return doSign(payload, aad, header, that.key_promises, kids);
};

/**
 * Initialize a JWS object.
 *
 * @param protectedHeader protected header (JS object)
 * @param payload Uint8Array payload to be signed
 * @param signature ArrayBuffer signature of the payload
 * @param header unprotected header (JS object)
 *
 * @constructor
 */
var JWS = function(protectedHeader, header, payload, signature) {
  var that = this;
  that.header = header;
  that.payload = Utils.Base64Url.encodeArray(payload);
  if (signature) {
    that.signature = Utils.Base64Url.encodeArray(signature);
  }
  that.protected = Utils.Base64Url.encode(JSON.stringify(protectedHeader));
};

JWS.fromObject = function(obj) {
  var rv = new JWS(obj.protected, obj.header, obj.payload, null);
  rv.signature = obj.signature;
  rv.signatures = obj.signatures;
  return rv;
};

/**
 * Serialize a JWS object using the JSON serialization format
 *
 * @returns {Object} a copy of this
 */
JWS.prototype.JsonSerialize = function() {
  return JSON.stringify(this);
};

/**
 * Serialize a JWS object using the Compact Serialization Format
 *
 * @returns {string} BASE64URL(UTF8(PROTECTED HEADER)).BASE64URL(PAYLOAD).BASE64URL(SIGNATURE)
 */
JWS.prototype.CompactSerialize = function() {
  var that = this;
  return that.protected + '.' + that.payload + '.' + that.signature;
};
<|endoftext|>


<commit_before>/* jsmin.c
   2012-07-02

Copyright (c) 2002 Douglas Crockford  (www.crockford.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

function jsminFn(stdin, options) {
    // Fallback options
    options = options || {};

    // Grab stdout, stderr, exit, argc, and argv
    var stdout = options.stdout || console.log,
        stderr = options.stderr || console.error,
        exit = options.exit || process.exit,
        argc = options.argc || 0,
        argv = options.argv || [];

    // Generate fputs, fputc, getc, putc, fprintf
    var fputs = function (str, stream) {
          stream.write(str);
        },
        fputc = fputs,
        putc = fputs,
        fprintf = function (stream, formatStr, input) {
          var outStr = formatStr.replace('%s', input);
          fputs(outStr, stream);
        },
        getc = function () {
          return stdin.read(1);
        };
function puti(index, stream) {
    stream.writeFromIndex(index);
}

    // Begin normal jsmin.c code
    var EOF = -1;
    var theA;
    var theB;
    var theLookahead = EOF;
    var theX = EOF;
    var theY = EOF;
var getIndex = 0;
var peekIndex = 0;
var nextIndex = 0;
var theAIndex = 0;
var theBIndex = 0;
function geti(stream) {
    return stream.getIndex();
}
function getChar(index, stream) {
    return stream.charAt(index);
}
var assert = require('assert');

    function error(s) {
        fputs("JSMIN Error: ", stderr);
        fputs(s, stderr);
        fputc('\n', stderr);
        exit(1);
    }

    /* isAlphanum -- return true if the character is a letter, digit, underscore,
            dollar sign, or non-ASCII character.
    */

    function isAlphanum(c) {
        return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
            (c >= 'A' && c <= 'Z') || c === '_' || c === '$' || c === '\\' ||
            c > 126);
    }

    /* get -- return the next character from stdin. Watch out for lookahead. If
            the character is a control character, translate it to a space or
            linefeed.
    */

    function get() {
        var c = theLookahead;
        theLookahead = EOF;
        if (c === EOF) {
getIndex = geti(stdin);
            c = getc(stdin);
assert.strictEqual(getChar(getIndex, stdin), c);
            theY = theX;
            theX = c;
        }
        if (c >= ' ' || c === '\n' || c === EOF) {
            return c;
        }
        if (c === '\r') {
            return '\n';
        }
        return ' ';
    }

    /* peek -- get the next character without getting it.
    */

    function peek() {
        theLookahead = get();
peekIndex = getIndex;
        return theLookahead;
    }

    /* next -- get the next character, excluding comments. peek() is used to see
            if a '/' is followed by a '/' or '*'.
    */

    function next() {
        var c = get();
nextIndex = getIndex;
        if  (c === '/') {
            switch (peek()) {
            case '/':
                for (;;) {
                    c = get();
nextIndex = getIndex;
                    if (c <= '\n') {
                        return c;
                    }
                }
            case '*':
                get();
nextIndex = getIndex;
                for (;;) {
                    switch (get()) {
                    case '*':
                        if (peek() === '/') {
                            get();
nextIndex = getIndex;
                            return ' ';
                        }
                        break;
                    case EOF:
                        error("Unterminated comment.");
                    }
nextIndex = getIndex;
                }
            default:
                return c;
            }
        }
        return c;
    }

    /* action -- do something! What you do is determined by the argument:
            1   Output A. Copy B to A. Get the next B.
            2   Copy B to A. Get the next B. (Delete A).
            3   Get the next B. (Delete B).
       action treats a string as a single character. Wow!
       action recognizes a regular expression if it is preceded by ( or , or =.
    */

    function action(d) {
        switch (d) {
        case 1:
assert.strictEqual(getChar(theAIndex, stdin), theA);
            putc(theA, stdout);
            if (theA === theB && (theA === '+' || theA === '-') && theY !== theA) {
                putc(' ', stdout);
            }
        case 2:
            theA = theB;
theAIndex = theBIndex;
            if (theA === '\'' || theA === '"' || theA === '`') {
                for (;;) {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                    putc(theA, stdout);
                    theA = get();
theAIndex = getIndex;
                    if (theA === theB) {
                        break;
                    }
                    if (theA === '\\') {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                        putc(theA, stdout);
                        theA = get();
theAIndex = getIndex;
                    }
                    if (theA === EOF) {
                        error("Unterminated string literal.");
                    }
                }
            }
        case 3:
            theB = next();
theBIndex = nextIndex;
            if (theB === '/' && (theA === '(' || theA === ',' || theA === '=' ||
                                theA === ':' || theA === '[' || theA === '!' ||
                                theA === '&' || theA === '|' || theA === '?' ||
                                theA === '{' || theA === '}' || theA === ';' ||
                                theA === '\n')) {
assert.strictEqual(getChar(theAIndex, stdin), theA);
assert.strictEqual(getChar(theBIndex, stdin), theB);
                putc(theA, stdout);
                putc(theB, stdout);
                for (;;) {
                    theA = get();
theAIndex = getIndex;
                    if (theA === '[') {
                        for (;;) {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                            putc(theA, stdout);
                            theA = get();
theAIndex = getIndex;
                            if (theA === ']') {
                                break;
                            }
                            if (theA === '\\') {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                                putc(theA, stdout);
                                theA = get();
theAIndex = getIndex;
                            }
                            if (theA === EOF) {
                                error("Unterminated set in Regular Expression literal.");
                            }
                        }
                    } else if (theA === '/') {
                        break;
                    } else if (theA ==='\\') {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                        putc(theA, stdout);
                        theA = get();
theAIndex = getIndex;
                    }
                    if (theA === EOF) {
                        error("Unterminated Regular Expression literal.");
                    }
assert.strictEqual(getChar(theAIndex, stdin), theA);
                    putc(theA, stdout);
                }
                theB = next();
theBIndex = nextIndex;
            }
        }
    }

    /* jsmin -- Copy the input to the output, deleting the characters which are
            insignificant to JavaScript. Comments will be removed. Tabs will be
            replaced with spaces. Carriage returns will be replaced with linefeeds.
            Most spaces and linefeeds will be removed.
    */

    function jsmin() {
        if (peek() === 0xEF) {
            get();
            get();
            get();
        }
        theA = '\n';
        action(3);
        while (theA !== EOF) {
            switch (theA) {
            case ' ':
                if (isAlphanum(theB)) {
                    action(1);
                } else {
                    action(2);
                }
                break;
            case '\n':
                switch (theB) {
                case '{':
                case '[':
                case '(':
                case '+':
                case '-':
                case '!':
                case '~':
                    action(1);
                    break;
                case ' ':
                    action(3);
                    break;
                default:
                    if (isAlphanum(theB)) {
                        action(1);
                    } else {
                        action(2);
                    }
                }
                break;
            default:
                switch (theB) {
                case ' ':
                    if (isAlphanum(theA)) {
                        action(1);
                        break;
                    }
                    action(3);
                    break;
                case '\n':
                    switch (theA) {
                    case '}':
                    case ']':
                    case ')':
                    case '+':
                    case '-':
                    case '"':
                    case '\'':
                    case '`':
                        action(1);
                        break;
                    default:
                        if (isAlphanum(theA)) {
                            action(1);
                        } else {
                            action(3);
                        }
                    }
                    break;
                default:
                    action(1);
                    break;
                }
            }
        }
    }

    /* main -- Output any command line arguments as comments
            and then minify the input.
    */
    function main(argc, argv) {
        var i;
        for (i = 1; i < argc; i += 1) {
            fprintf(stdout, "// %s\n", argv[i]);
        }
        jsmin();
        return 0;
    }

    // Invoke and return main
    return main(argc, argv);

}

// Export jsminFn
module.exports = jsminFn;<commit_msg>It works ;_;<commit_after>/* jsmin.c
   2012-07-02

Copyright (c) 2002 Douglas Crockford  (www.crockford.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

function jsminFn(stdin, options) {
    // Fallback options
    options = options || {};

    // Grab stdout, stderr, exit, argc, and argv
    var stdout = options.stdout || console.log,
        stderr = options.stderr || console.error,
        exit = options.exit || process.exit,
        argc = options.argc || 0,
        argv = options.argv || [];

    // Generate fputs, fputc, getc, putc, fprintf
    var fputs = function (str, stream) {
          stream.write(str);
        },
        fputc = fputs,
        putc = fputs,
        fprintf = function (stream, formatStr, input) {
          var outStr = formatStr.replace('%s', input);
          fputs(outStr, stream);
        },
        getc = function () {
          return stdin.read(1);
        };
function puti(index, stream) {
    stream.writeFromIndex(index);
}

    // Begin normal jsmin.c code
    var EOF = -1;
    var theA;
    var theB;
    var theLookahead = EOF;
    var theX = EOF;
    var theY = EOF;
var getIndex = 0;
var peekIndex = 0;
var nextIndex = 0;
var theAIndex = 0;
var theBIndex = 0;
function geti(stream) {
    return stream.getIndex();
}
function getChar(index, stream) {
    return stream.charAt(index);
}
var assert = require('assert');

    function error(s) {
        fputs("JSMIN Error: ", stderr);
        fputs(s, stderr);
        fputc('\n', stderr);
        exit(1);
    }

    /* isAlphanum -- return true if the character is a letter, digit, underscore,
            dollar sign, or non-ASCII character.
    */

    function isAlphanum(c) {
        return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
            (c >= 'A' && c <= 'Z') || c === '_' || c === '$' || c === '\\' ||
            c > 126);
    }

    /* get -- return the next character from stdin. Watch out for lookahead. If
            the character is a control character, translate it to a space or
            linefeed.
    */

    function get() {
        var c = theLookahead;
        theLookahead = EOF;
        if (c === EOF) {
getIndex = geti(stdin);
            c = getc(stdin);
assert.strictEqual(getChar(getIndex, stdin), c);
            theY = theX;
            theX = c;
        }
        if (c >= ' ' || c === '\n' || c === EOF) {
            return c;
        }
        if (c === '\r') {
            return '\n';
        }
        return ' ';
    }

    /* peek -- get the next character without getting it.
    */

    function peek() {
        theLookahead = get();
peekIndex = getIndex;
        return theLookahead;
    }

    /* next -- get the next character, excluding comments. peek() is used to see
            if a '/' is followed by a '/' or '*'.
    */

    function next() {
        var c = get();
nextIndex = getIndex;
        if  (c === '/') {
            switch (peek()) {
            case '/':
                for (;;) {
                    c = get();
nextIndex = getIndex;
                    if (c <= '\n') {
                        return c;
                    }
                }
            case '*':
                get();
nextIndex = getIndex;
                for (;;) {
                    switch (get()) {
                    case '*':
                        if (peek() === '/') {
                            get();
nextIndex = getIndex;
                            return ' ';
                        }
                        break;
                    case EOF:
                        error("Unterminated comment.");
                    }
nextIndex = getIndex;
                }
            default:
                return c;
            }
        }
        return c;
    }

    /* action -- do something! What you do is determined by the argument:
            1   Output A. Copy B to A. Get the next B.
            2   Copy B to A. Get the next B. (Delete A).
            3   Get the next B. (Delete B).
       action treats a string as a single character. Wow!
       action recognizes a regular expression if it is preceded by ( or , or =.
    */

    function action(d) {
        switch (d) {
        case 1:
assert.strictEqual(getChar(theAIndex, stdin), theA);
            puti(theAIndex, stdout);
            if (theA === theB && (theA === '+' || theA === '-') && theY !== theA) {
                putc(' ', stdout);
            }
        case 2:
            theA = theB;
theAIndex = theBIndex;
            if (theA === '\'' || theA === '"' || theA === '`') {
                for (;;) {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                    puti(theAIndex, stdout);
                    theA = get();
theAIndex = getIndex;
                    if (theA === theB) {
                        break;
                    }
                    if (theA === '\\') {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                        puti(theAIndex, stdout);
                        theA = get();
theAIndex = getIndex;
                    }
                    if (theA === EOF) {
                        error("Unterminated string literal.");
                    }
                }
            }
        case 3:
            theB = next();
theBIndex = nextIndex;
            if (theB === '/' && (theA === '(' || theA === ',' || theA === '=' ||
                                theA === ':' || theA === '[' || theA === '!' ||
                                theA === '&' || theA === '|' || theA === '?' ||
                                theA === '{' || theA === '}' || theA === ';' ||
                                theA === '\n')) {
assert.strictEqual(getChar(theAIndex, stdin), theA);
assert.strictEqual(getChar(theBIndex, stdin), theB);
                puti(theAIndex, stdout);
                puti(theBIndex, stdout);
                for (;;) {
                    theA = get();
theAIndex = getIndex;
                    if (theA === '[') {
                        for (;;) {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                            puti(theAIndex, stdout);
                            theA = get();
theAIndex = getIndex;
                            if (theA === ']') {
                                break;
                            }
                            if (theA === '\\') {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                                puti(theAIndex, stdout);
                                theA = get();
theAIndex = getIndex;
                            }
                            if (theA === EOF) {
                                error("Unterminated set in Regular Expression literal.");
                            }
                        }
                    } else if (theA === '/') {
                        break;
                    } else if (theA ==='\\') {
assert.strictEqual(getChar(theAIndex, stdin), theA);
                        puti(theAIndex, stdout);
                        theA = get();
theAIndex = getIndex;
                    }
                    if (theA === EOF) {
                        error("Unterminated Regular Expression literal.");
                    }
assert.strictEqual(getChar(theAIndex, stdin), theA);
                    puti(theAIndex, stdout);
                }
                theB = next();
theBIndex = nextIndex;
            }
        }
    }

    /* jsmin -- Copy the input to the output, deleting the characters which are
            insignificant to JavaScript. Comments will be removed. Tabs will be
            replaced with spaces. Carriage returns will be replaced with linefeeds.
            Most spaces and linefeeds will be removed.
    */

    function jsmin() {
        if (peek() === 0xEF) {
            get();
            get();
            get();
        }
        theA = '\n';
        action(3);
        while (theA !== EOF) {
            switch (theA) {
            case ' ':
                if (isAlphanum(theB)) {
                    action(1);
                } else {
                    action(2);
                }
                break;
            case '\n':
                switch (theB) {
                case '{':
                case '[':
                case '(':
                case '+':
                case '-':
                case '!':
                case '~':
                    action(1);
                    break;
                case ' ':
                    action(3);
                    break;
                default:
                    if (isAlphanum(theB)) {
                        action(1);
                    } else {
                        action(2);
                    }
                }
                break;
            default:
                switch (theB) {
                case ' ':
                    if (isAlphanum(theA)) {
                        action(1);
                        break;
                    }
                    action(3);
                    break;
                case '\n':
                    switch (theA) {
                    case '}':
                    case ']':
                    case ')':
                    case '+':
                    case '-':
                    case '"':
                    case '\'':
                    case '`':
                        action(1);
                        break;
                    default:
                        if (isAlphanum(theA)) {
                            action(1);
                        } else {
                            action(3);
                        }
                    }
                    break;
                default:
                    action(1);
                    break;
                }
            }
        }
    }

    /* main -- Output any command line arguments as comments
            and then minify the input.
    */
    function main(argc, argv) {
        var i;
        for (i = 1; i < argc; i += 1) {
            fprintf(stdout, "// %s\n", argv[i]);
        }
        jsmin();
        return 0;
    }

    // Invoke and return main
    return main(argc, argv);

}

// Export jsminFn
module.exports = jsminFn;<|endoftext|>


<commit_before>const vm = require("vm"),
	path = require("path"),
	fs = require("fs");

let mysql;

function htmlEntities(str) {
	return str.replace(/&/g, "&").replace(/</g, "<")
		.replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}

function addSlashes(str) {
	return str.replace(/[\\"']/g, "\\$&").replace(/\u0000/g, "\\0");
}

function ucFirst(str) {
	if (!str.length) {
		return "";
	}

	return str[0].toUpperCase() + str.substr(1);
}

function isSet(variable) {
	return typeof variable !== "undefined";
}

function generateError(err) {
	let start = err.stack.indexOf("%file%") + 6,
		end = err.stack.indexOf("\n", start) - start,
		msg = err.message.toString();

	err = err.stack.substr(start, end).split(":");

	return "Fatal error: " + msg + " in " + err[0] + " on line " + err[1];
}

module.exports = (root, data, headers) => {
	let output = "",
		cache = null,
		ended = false,
		dbStream,
		session = "",
		sandbox = {
			COOKIE: {}
		},
		i;

	sandbox.SERVER = root.SERVER;

	sandbox.GET = root.GET;

	sandbox.POST = root.POST;

	sandbox.FILES = root.FILES;

	for (i in root.COOKIES) {
		if (root.COOKIES.hasOwnProperty(i)) {
			sandbox.COOKIE[i] = decodeURIComponent(root.COOKIES[i]);
		}
	}

	sandbox.require = require;

	sandbox.htmlEntities = htmlEntities;

	sandbox.addSlashes = addSlashes;

	sandbox.ucFirst = ucFirst;

	sandbox.isSet = isSet;

	sandbox.echo = str => {
		if (typeof str !== "string") {
			str = JSON.stringify(str);
		}

		output += str;
	};

	sandbox.setHeader = (name, value) => {
		headers[name] = value;

		if (name.toLowerCase() === "location" && root.status !== 201 &&
				(root.status < 300 || root.status > 399)) {
			root.status = 302;
		}
	};

	sandbox.setCache = (bool, time) => {
		cache = null;

		if (bool) {
			cache = {
				expires: time
			};
		}
	};

	sandbox.setCookie = (name, value, expire, path, domain, secure, http) => {
		root.setCookie(name, value, expire, path, domain, secure, http);
	};

	sandbox.setStatus = code => {
		root.status = code;
	};

	sandbox.fileRename = (oldPath, newPath) => {
		if (!path.isAbsolute(oldPath)) {
			oldPath = path.join(path.dirname(root.filename), oldPath);
		}

		if (!path.isAbsolute(newPath)) {
			newPath = path.join(path.dirname(root.filename), newPath);
		}

		fs.renameSync(oldPath, newPath);
	};

	sandbox.fileExists = file => {
		if (!path.isAbsolute(file)) {
			file = path.join(path.dirname(root.filename), file);
		}

		return fs.existsSync(file);
	};

	sandbox.fileGetContents = file => {
		if (!path.isAbsolute(file)) {
			file = path.join(path.dirname(root.filename), file);
		}

		if (fs.existsSync(file)) {
			return fs.readFileSync(file);
		}

		return "Error: could not find file " + file;
	};

	sandbox.filePutContents = (file, str) => {
		if (!path.isAbsolute(file)) {
			file = path.join(path.dirname(root.filename), file);
		}

		fs.writeFileSync(file, str);
	};

	sandbox.include = file => {
		try {
			if (!path.isAbsolute(file)) {
				file = path.join(path.dirname(root.filename), file);
			}

			data = fs.readFileSync(file);

			vm.runInNewContext(data, sandbox, {
				filename: "%file%" + file
			});
		} catch (err) {
			sandbox.echo(generateError(err));

			sandbox.exit();
		}
	};

	sandbox.sessionStart = () => {
		let cfg = root.getCfg("sessions"),
			name = cfg.name || "JSSSESSID",
			id = "",
			tmp,
			i;

		if (sandbox.COOKIE[name] &&
				root.server.sessions[sandbox.COOKIE[name]]) {
			id = sandbox.COOKIE[name];
		} else {
			for (i = 0; i < 16; ++i) {
				tmp = Math.floor(Math.random() * 256);

				id += ("0" + tmp.toString(16)).slice(-2);
			}

			sandbox.setCookie(name, id);

			root.server.sessions[id] = {};
		}

		sandbox.SESSION = root.server.sessions[id];

		root.server.sessions.lastAccessed[id] = Date.now();

		session = id;
	};

	sandbox.sessionDestroy = () => {
		if (session) {
			root.server.sessions[session] = null;
			root.server.sessions.lastAccessed[session] = null;

			sandbox.SESSION = null;

			session = "";
		}
	};

	sandbox.mysqlConnect = (conn, cb) => {
		if (!mysql) {
			mysql = require("mysql");
		}

		dbStream = mysql.createConnection(conn);
		dbStream.connect(err => {
			if (err) {
				sandbox.echo(err.message.toString());

				sandbox.exit();
			} else if (cb) {
				try {
					cb();
				} catch (err) {
					sandbox.echo(generateError(err));

					sandbox.exit();
				}
			}
		});
		dbStream.on("error", err => {
			if (err.code === "PROTOCOL_CONNECTION_LOST") {
				console.log("[notice] database connection lost");
			}
		});
	};

	sandbox.mysqlQuery = (query, values, cb) => {
		if (typeof values === "function") {
			cb = values;

			values = null;
		}

		dbStream.query(query, values, (err, results) => {
			if (err) {
				sandbox.echo(err.message.toString());

				sandbox.exit();
			} else if (cb) {
				try {
					cb(results);
				} catch (err) {
					sandbox.echo(generateError(err));

					sandbox.exit();
				}
			}
		});
	};

	sandbox.mysqlClose = cb => {
		if (dbStream) {
			dbStream.end(err => {
				if (err) {
					sandbox.echo(err.message.toString());

					sandbox.exit();
				} else if (cb) {
					try {
						cb();
					} catch (err) {
						sandbox.echo(generateError(err));

						sandbox.exit();
					}
				}
			});
			dbStream = null;
		}
	};

	sandbox.exit = str => {
		if (!ended) {
			ended = true;

			if (root.cookies.length) {
				root.res.setHeader("Set-Cookie", root.cookies);
			}

			if (session) {
				root.server.sessions[session] = sandbox.SESSION;
			}

			if (str) {
				output += str;
			}

			root.sendData(output, headers, cache);

			sandbox.mysqlClose();
		}
	};

	try {
		vm.runInNewContext(data, sandbox, {
			filename: "%file%" + root.filename
		});
	} catch (err) {
		output = generateError(err);

		sandbox.exit();
	}
};<commit_msg>Update JSS functions<commit_after>const vm = require("vm"),
	path = require("path"),
	fs = require("fs");

let mysql;

function urlEncode(str) {
	return encodeURIComponent(str).replace(/[!'()]/g, escape)
		.replace(/\*/g, "%2A");
}

function htmlEntities(str) {
	return str.replace(/&/g, "&").replace(/</g, "<")
		.replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
}

function addSlashes(str) {
	return str.replace(/[\\"']/g, "\\$&").replace(/\u0000/g, "\\0");
}

function ucFirst(str) {
	if (!str.length) {
		return "";
	}

	return str[0].toUpperCase() + str.substr(1);
}

function isSet(variable) {
	return typeof variable !== "undefined";
}

function isNumeric(value) {
	return !isNaN(parseInt(value, 10));
}

function numberFormat(number, sep = ",") {
	let str = number + "",
		i = str.indexOf(".");

	if (str.length < 4) {
		return str;
	}

	for (i = (i > -1 ? i : str.length) - 3; i > 0; i -= 3) {
		str = str.substr(0, i) + sep + str.substr(i);
	}

	return str;
}

function strPad(str, len = 3, pad = "0", type = "left") {
	let tmp = ["", "", (str + "").length];

	while (tmp[2] < len) {
		if (type === "both") {
			if (tmp[2] + pad.length < len) {
				tmp[1] += pad;
				tmp[2] += pad.length;
			} else {
				tmp[1] += pad.substr(0, len - tmp[2]);
				tmp[2] += len - tmp[2];
			}
		}

		if (tmp[2] + pad.length < len) {
			tmp[type === "right" ? 1 : 0] += pad;
			tmp[2] += pad.length;
		} else {
			tmp[type === "right" ? 1 : 0] += pad.substr(0, len - tmp[2]);
			tmp[2] += len - tmp[2];
		}
	}

	return tmp[0] + str + tmp[1];
}

function generateError(err) {
	let start = err.stack.indexOf("%file%") + 6,
		end = err.stack.indexOf("\n", start) - start,
		msg = err.message.toString();

	err = err.stack.substr(start, end).split(":");

	return "Fatal error: " + msg + " in " + err[0] + " on line " + err[1];
}

module.exports = (root, data, headers) => {
	let output = "",
		cache = null,
		ended = false,
		dbStream,
		session = "",
		sandbox = {
			COOKIE: {}
		},
		i;

	sandbox.SERVER = root.SERVER;

	sandbox.GET = root.GET;

	sandbox.POST = root.POST;

	sandbox.FILES = root.FILES;

	for (i in root.COOKIES) {
		if (root.COOKIES.hasOwnProperty(i)) {
			sandbox.COOKIE[i] = decodeURIComponent(root.COOKIES[i]);
		}
	}

	sandbox.require = require;

	sandbox.urlEncode = urlEncode;

	sandbox.htmlEntities = htmlEntities;

	sandbox.addSlashes = addSlashes;

	sandbox.ucFirst = ucFirst;

	sandbox.isSet = isSet;

	sandbox.isNumeric = isNumeric;

	sandbox.numberFormat = numberFormat;

	sandbox.strPad = strPad;

	sandbox.echo = str => {
		if (typeof str !== "string") {
			str = JSON.stringify(str);
		}

		output += str;
	};

	sandbox.setHeader = (name, value) => {
		headers[name] = value;

		if (name.toLowerCase() === "location" && root.status !== 201 &&
				(root.status < 300 || root.status > 399)) {
			root.status = 302;
		}
	};

	sandbox.setCache = (bool, time) => {
		cache = null;

		if (bool) {
			cache = {
				expires: time
			};
		}
	};

	sandbox.setCookie = (name, value, expire, path, domain, secure, http) => {
		root.setCookie(name, value, expire, path, domain, secure, http);
	};

	sandbox.setStatus = code => {
		root.status = code;
	};

	sandbox.fileRename = (oldPath, newPath) => {
		if (!path.isAbsolute(oldPath)) {
			oldPath = path.join(path.dirname(root.filename), oldPath);
		}

		if (!path.isAbsolute(newPath)) {
			newPath = path.join(path.dirname(root.filename), newPath);
		}

		fs.renameSync(oldPath, newPath);
	};

	sandbox.fileExists = file => {
		if (!path.isAbsolute(file)) {
			file = path.join(path.dirname(root.filename), file);
		}

		return fs.existsSync(file);
	};

	sandbox.fileGetContents = file => {
		if (!path.isAbsolute(file)) {
			file = path.join(path.dirname(root.filename), file);
		}

		if (fs.existsSync(file)) {
			return fs.readFileSync(file);
		}

		return "Error: could not find file " + file;
	};

	sandbox.filePutContents = (file, str) => {
		if (!path.isAbsolute(file)) {
			file = path.join(path.dirname(root.filename), file);
		}

		fs.writeFileSync(file, str);
	};

	sandbox.include = file => {
		try {
			if (!path.isAbsolute(file)) {
				file = path.join(path.dirname(root.filename), file);
			}

			data = fs.readFileSync(file);

			vm.runInNewContext(data, sandbox, {
				filename: "%file%" + file
			});
		} catch (err) {
			sandbox.echo(generateError(err));

			sandbox.exit();
		}
	};

	sandbox.sessionStart = () => {
		let cfg = root.getCfg("sessions"),
			name = cfg.name || "JSSSESSID",
			id = "",
			tmp,
			i;

		if (sandbox.COOKIE[name] &&
				root.server.sessions[sandbox.COOKIE[name]]) {
			id = sandbox.COOKIE[name];
		} else {
			for (i = 0; i < 16; ++i) {
				tmp = Math.floor(Math.random() * 256);

				id += ("0" + tmp.toString(16)).slice(-2);
			}

			sandbox.setCookie(name, id);

			root.server.sessions[id] = {};
		}

		sandbox.SESSION = root.server.sessions[id];

		root.server.sessions.lastAccessed[id] = Date.now();

		session = id;
	};

	sandbox.sessionDestroy = () => {
		if (session) {
			root.server.sessions[session] = null;
			root.server.sessions.lastAccessed[session] = null;

			sandbox.SESSION = null;

			session = "";
		}
	};

	sandbox.mysqlConnect = (conn, cb) => {
		if (!mysql) {
			mysql = require("mysql");
		}

		dbStream = mysql.createConnection(conn);
		dbStream.connect(err => {
			if (err) {
				sandbox.echo(err.message.toString());

				sandbox.exit();
			} else if (cb) {
				try {
					cb();
				} catch (err) {
					sandbox.echo(generateError(err));

					sandbox.exit();
				}
			}
		});
		dbStream.on("error", err => {
			if (err.code === "PROTOCOL_CONNECTION_LOST") {
				console.log("[notice] database connection lost");
			}
		});
	};

	sandbox.mysqlQuery = (query, values, cb) => {
		if (typeof values === "function") {
			cb = values;

			values = null;
		}

		dbStream.query(query, values, (err, results) => {
			if (err) {
				sandbox.echo(err.message.toString());

				sandbox.exit();
			} else if (cb) {
				try {
					cb(results);
				} catch (err) {
					sandbox.echo(generateError(err));

					sandbox.exit();
				}
			}
		});
	};

	sandbox.mysqlClose = cb => {
		if (dbStream) {
			dbStream.end(err => {
				if (err) {
					sandbox.echo(err.message.toString());

					sandbox.exit();
				} else if (cb) {
					try {
						cb();
					} catch (err) {
						sandbox.echo(generateError(err));

						sandbox.exit();
					}
				}
			});
			dbStream = null;
		}
	};

	sandbox.exit = str => {
		if (!ended) {
			ended = true;

			if (root.cookies.length) {
				root.res.setHeader("Set-Cookie", root.cookies);
			}

			if (session) {
				root.server.sessions[session] = sandbox.SESSION;
			}

			if (str) {
				sandbox.echo(str);
			}

			root.sendData(output, headers, cache);

			sandbox.mysqlClose();
		}
	};

	try {
		vm.runInNewContext(data, sandbox, {
			filename: "%file%" + root.filename
		});
	} catch (err) {
		output = generateError(err);

		sandbox.exit();
	}
};<|endoftext|>


<commit_before>import path from 'path';
import { writeFile } from 'fs-extra';
import puppeteerCore from 'puppeteer-core';
import express from 'express';
import getPort from 'get-port';
import { logger } from '@storybook/node-logger';

const read = async url => {
  const puppeteer = await usePuppeteer();
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto(url);

  await page.waitForFunction(
    'window.__STORYBOOK_STORY_STORE__ && window.__STORYBOOK_STORY_STORE__.extract && window.__STORYBOOK_STORY_STORE__.extract()'
  );
  const data = JSON.parse(
    await page.evaluate(async () => {
      // eslint-disable-next-line no-undef
      const d = window.__STORYBOOK_STORY_STORE__.extract();

      const result = Object.entries(d).reduce(
        (acc, [k, v]) => ({
          ...acc,
          [k]: {
            ...v,
            parameters: {
              globalArgs: v.parameters.globalArgs,
              globalArgTypes: v.parameters.globalArgTypes,
              options: v.parameters.options,
              args: v.parameters.args,
              argTypes: v.parameters.argTypes,
              framework: v.parameters.framework,
              fileName: v.parameters.fileName,
              docsOnly: v.parameters.docsOnly,
            },
          },
        }),
        {}
      );
      return JSON.stringify(result, null, 2);
    })
  );

  setImmediate(() => {
    browser.close();
  });
  return data;
};

const useLocation = async input => {
  if (input.match(/^http/)) {
    return [input, async () => {}];
  }

  const app = express();

  app.use(express.static(input));

  const port = await getPort();

  return new Promise((resolve, reject) => {
    const server = app.listen(port, e => {
      if (e) {
        reject(e);
      }

      const result = `http://localhost:${port}/iframe.html`;

      logger.info(`connecting to: ${result}`);

      resolve([result, server.close.bind(server)]);
    });
  });
};

const usePuppeteer = async () => {
  try {
    // eslint-disable-next-line import/no-extraneous-dependencies, global-require
    require('puppeteer');

    return puppeteerCore;
  } catch (e) {
    // it's not installed
    logger.info('installing puppeteer...');
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line global-require
      require('child_process').exec(
        `node ${require.resolve(path.join('puppeteer-core', 'install.js'))}`,
        error => (error ? reject(error) : resolve(puppeteerCore))
      );
    });
  }
};

export async function extract(input, targetPath) {
  if (input && targetPath) {
    const [location, exit] = await useLocation(input);

    const stories = await read(location);

    await writeFile(targetPath, JSON.stringify({ stories }, null, 2));

    await exit();
  } else {
    throw new Error(
      'Extract: please specify a path where your built-storybook is (can be a public url) and a target directory'
    );
  }
}
<commit_msg>Fix browser availablility check<commit_after>import path from 'path';
import { writeFile } from 'fs-extra';
import puppeteerCore from 'puppeteer-core';
import express from 'express';
import getPort from 'get-port';
import { logger } from '@storybook/node-logger';

const read = async url => {
  const browser = await usePuppeteerBrowser();
  const page = await browser.newPage();

  await page.goto(url);

  await page.waitForFunction(
    'window.__STORYBOOK_STORY_STORE__ && window.__STORYBOOK_STORY_STORE__.extract && window.__STORYBOOK_STORY_STORE__.extract()'
  );
  const data = JSON.parse(
    await page.evaluate(async () => {
      // eslint-disable-next-line no-undef
      const d = window.__STORYBOOK_STORY_STORE__.extract();

      const result = Object.entries(d).reduce(
        (acc, [k, v]) => ({
          ...acc,
          [k]: {
            ...v,
            parameters: {
              globalArgs: v.parameters.globalArgs,
              globalArgTypes: v.parameters.globalArgTypes,
              options: v.parameters.options,
              args: v.parameters.args,
              argTypes: v.parameters.argTypes,
              framework: v.parameters.framework,
              fileName: v.parameters.fileName,
              docsOnly: v.parameters.docsOnly,
            },
          },
        }),
        {}
      );
      return JSON.stringify(result, null, 2);
    })
  );

  setImmediate(() => {
    browser.close();
  });
  return data;
};

const useLocation = async input => {
  if (input.match(/^http/)) {
    return [input, async () => {}];
  }

  const app = express();

  app.use(express.static(input));

  const port = await getPort();

  return new Promise((resolve, reject) => {
    const server = app.listen(port, e => {
      if (e) {
        reject(e);
      }

      const result = `http://localhost:${port}/iframe.html`;

      logger.info(`connecting to: ${result}`);

      resolve([result, server.close.bind(server)]);
    });
  });
};

const usePuppeteerBrowser = () => {
  try {
    return puppeteerCore.launch();
  } catch (e) {
    // it's not installed
    logger.info('installing puppeteer...');
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line global-require
      require('child_process').exec(
        `node ${require.resolve(path.join('puppeteer-core', 'install.js'))}`,
        error => (error ? reject(error) : resolve(puppeteerCore.launch()))
      );
    });
  }
};

export async function extract(input, targetPath) {
  if (input && targetPath) {
    const [location, exit] = await useLocation(input);

    const stories = await read(location);

    await writeFile(targetPath, JSON.stringify({ stories }, null, 2));

    await exit();
  } else {
    throw new Error(
      'Extract: please specify a path where your built-storybook is (can be a public url) and a target directory'
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

var webbot = require('./webbot')
  , chai = require('chai')
  , expect = chai.expect
  , should = chai.should()
  , util = require('hw-util')
  , fs = require('fs')
  , async = require('async')
  , ErrorHandler = require('../node_modules/webdriverio/lib/utils/ErrorHandler')
  , logFactory = util.logFactory
  //, log = logFactory('client-commands')
  , browserLog = logFactory('browser')
  , clientCommands = exports;

clientCommands.checkLocalFile = function (file, content, timeout, callback) {
  var browser = this
    , config = webbot.getScenario().config
    , found, interval;
  found = false;
  interval = setInterval(function () {
    fs.exists(file, function (exists) {
      if (!exists) {
        return;
      }
      clearInterval(interval);
      found = true;
      fs.readFile(file, {encoding: 'utf-8'}, function (err, content) {
        should.not.exist(err);
        browser.log('Check downloaded file content');
        content.should.equal(config.file.content);
        callback();
      });
    });
  }, 1000);
  setTimeout(function () {
    found.should.be.true;
    clearInterval(interval);
  }, config.scenario.file && config.scenario.file.download && config.scenario.file.download.timeout || 30000);
  return browser;
};

clientCommands.findTextInList = function (options, callback) {
  var browser = this;
  callback = callback || function (err, result) {
    should.not.exist(err, util.format('Error :', err));
    result.value.match.should.be.ok;
  };
  browser
    .execute(function (options) {
      var items, i, elt, filterIsRegexp, match
        , result = {
          index: -1,
          match: false,
          elts: []
        };
      filterIsRegexp = options.filter instanceof RegExp;
      items = document.querySelectorAll(options.listSelector);
      for (i = 0; !result.match && i < items.length; i++) {
        elt = options.eltSelector ? items[i].querySelector(options.eltSelector) : items[i];
        match = filterIsRegexp ? elt.textContent.match(options.filter) : elt.textContent.trim() === options.filter;
        if (match) {
          result.index = i;
          result.match = match;
        }
      }
      return result;
    }, options, callback);
  return browser;
};

clientCommands.getExistingText = function (selector, expectedValue, callback) {
  var browser = this;
  browser
    .getText(selector, function (err, value) {
      should.not.exist(err, util.format('Selector %s not found', selector));
      value.should.equal(expectedValue);
    })
    .call(callback);
  return browser;
};

clientCommands.getExistingTitle = function (expectedValue, callback) {
  var browser = this;
  browser
    .getTitle(function (err, value) {
      should.not.exist(err, 'Page title not found');
      value.should.equal(expectedValue);
    })
    .call(callback);
  return browser;
};

clientCommands.log = function () {
  var browser = this
    , args = Array.prototype.slice.call(arguments)
    , callback = args.pop();
  browser.logIndex = browser.logIndex ? ++browser.logIndex : 1;
  args[0] = util.format('#%s - %s', browser.logIndex, args[0]);
  browser.call(function () {
    browserLog.info.apply(browser, args);
    callback();
  });
  return browser;
};

clientCommands.waitAndCheckText = function (selector, timeout, expectedText, callback) { // Attend qu'un selector aie la valeur attendue
  var browser = this;
  browser
    .waitForExist(selector, timeout, function (err, exists) {
      expect(err).not.to.be.ok;
      expect(exists).to.be.true;
    })
    .getText(selector, webbot.expectValueChecker(expectedText))
    .call(callback);
  return browser;
};

clientCommands.waitForSomething = function (selector, someFunc, someArgs, timeout) { // Attend quelque chose définit par une fonction
  var callback
    , self = this
    , response = {};
  callback = arguments[arguments.length - 1];
  if (typeof selector !== 'string') {
    return callback(new ErrorHandler.CommandError('number or type of arguments don\'t agree with waitForChecked command'));
  }
  if (typeof timeout !== 'number') {
    timeout = 500;
  }
  async
    .waterfall([
      function (cb) {
        self.timeoutsAsyncScript(timeout, cb);
      },
      function (res, cb) {
        response.timeoutsAsyncScript = res;
        self.selectorExecuteAsync(selector, someFunc, someArgs, cb);
      },
      function (result, res, cb) {
        response.selectorExecuteAsync = res;
        cb();
      }
    ], function (err) {
      callback(err, response.selectorExecuteAsync && response.selectorExecuteAsync.executeAsync ? response.selectorExecuteAsync.executeAsync.value : false, response);
    });
};<commit_msg>debug<commit_after>'use strict';

var webbot = require('./webbot')
  , chai = require('chai')
  , expect = chai.expect
  , should = chai.should()
  , util = require('hw-util')
  , fs = require('fs')
  , async = require('async')
  , ErrorHandler = require('../node_modules/webdriverio/lib/utils/ErrorHandler')
  , logFactory = util.logFactory
  //, log = logFactory('client-commands')
  , browserLog = logFactory('browser')
  , clientCommands = exports;

clientCommands.checkLocalFile = function (file, content, timeout, callback) {
  var browser = this
    , config = webbot.getScenario().config
    , found, interval;
  found = false;
  interval = setInterval(function () {
    fs.exists(file, function (exists) {
      if (!exists) {
        return;
      }
      clearInterval(interval);
      found = true;
      fs.readFile(file, {encoding: 'utf-8'}, function (err, content) {
        should.not.exist(err);
        browser.log('Check downloaded file content');
        content.should.equal(config.file.content);
        callback();
      });
    });
  }, 1000);
  setTimeout(function () {
    found.should.be.true;
    clearInterval(interval);
  }, config.scenario.file && config.scenario.file.download && config.scenario.file.download.timeout || 30000);
  return browser;
};

clientCommands.findTextInList = function (options, callback) {
  var browser = this;
  callback = callback || function (err, result) {
    should.not.exist(err, util.format('Error :', err));
    result.value.match.should.be.ok;
  };
  browser
    .execute(function (options) {
      var items, i, elt, filterIsRegexp, match
        , result = {
          index: -1,
          match: false,
          elts: []
        };
      filterIsRegexp = options.filter instanceof RegExp;
      items = document.querySelectorAll(options.listSelector);
      for (i = 0; !result.match && i < items.length; i++) {
        elt = options.eltSelector ? items[i].querySelector(options.eltSelector) : items[i];
        match = filterIsRegexp ? elt.textContent.match(options.filter) : elt.textContent.trim() === options.filter;
        if (match) {
          result.index = i;
          result.match = match;
        }
      }
      return result;
    }, options, callback);
  return browser;
};

clientCommands.getExistingText = function (selector, expectedValue, callback) {
  var browser = this;
  browser
    .getText(selector, function (err, value) {
      should.not.exist(err, util.format('Selector %s not found', selector));
      value.should.equal(expectedValue);
    })
    .call(callback);
  return browser;
};

clientCommands.getExistingTitle = function (expectedValue, callback) {
  var browser = this;
  browser
    .getTitle(function (err, value) {
      should.not.exist(err, 'Page title not found');
      value.should.equal(expectedValue);
    })
    .call(callback);
  return browser;
};

clientCommands.log = function () {
  var browser = this
    , args = Array.prototype.slice.call(arguments)
    , callback = args.pop();
  browser.logIndex = browser.logIndex ? ++browser.logIndex : 1;
  args[0] = util.format('#%s - %s', browser.logIndex, args[0]);
  browser.call(function () {
    browserLog.info.apply(browser, args);
    callback();
  });
  return browser;
};

clientCommands.waitAndCheckText = function (selector, timeout, expectedText, callback) { // Attend qu'un selector aie la valeur attendue
  var browser = this;
  browser
    .waitForExist(selector, timeout, function (err, exists) {
      expect(err).not.to.be.ok;
      expect(exists).to.be.true;
    })
    .getText(selector, webbot.helpers.expectValueChecker(expectedText))
    .call(callback);
  return browser;
};

clientCommands.waitForSomething = function (selector, someFunc, someArgs, timeout) { // Attend quelque chose définit par une fonction
  var callback
    , self = this
    , response = {};
  callback = arguments[arguments.length - 1];
  if (typeof selector !== 'string') {
    return callback(new ErrorHandler.CommandError('number or type of arguments don\'t agree with waitForChecked command'));
  }
  if (typeof timeout !== 'number') {
    timeout = 500;
  }
  async
    .waterfall([
      function (cb) {
        self.timeoutsAsyncScript(timeout, cb);
      },
      function (res, cb) {
        response.timeoutsAsyncScript = res;
        self.selectorExecuteAsync(selector, someFunc, someArgs, cb);
      },
      function (result, res, cb) {
        response.selectorExecuteAsync = res;
        cb();
      }
    ], function (err) {
      callback(err, response.selectorExecuteAsync && response.selectorExecuteAsync.executeAsync ? response.selectorExecuteAsync.executeAsync.value : false, response);
    });
};<|endoftext|>


<commit_before>if (! Symbol.asyncIterator) {
    Symbol.asyncIterator = Symbol('asyncIterator');
}

global.__jymfony = global.__jymfony || {};

const forAwait = (iterator, callback) => {
    const originalIterator = iterator;
    if (! iterator.next) {
        iterator = iterator[Symbol.asyncIterator] || iterator[Symbol.iterator];
    }

    if (! iterator) {
        throw new Error(Object.prototype.toString.call(originalIterator) + ' is not iterable');
    } else if (isGeneratorFunction(iterator)) {
        iterator = iterator();
    }

    return new Promise((resolve, reject) => {
        async function next() {
            try {
                const step = await iterator.next();
                if (! step.done) {
                    const retVal = await callback(await step.value);
                    if (undefined !== retVal) {
                        return resolve(retVal);
                    }

                    return next();
                }

                resolve(await step.value);
            } catch (e) {
                reject(e);
            }

            return null;
        }

        next();
    });
};

__jymfony.forAwait = forAwait;
<commit_msg>[util] allow forAwait to iterate arrays<commit_after>if (! Symbol.asyncIterator) {
    Symbol.asyncIterator = Symbol('asyncIterator');
}

global.__jymfony = global.__jymfony || {};

const forAwait = (iterator, callback) => {
    const originalIterator = iterator;
    if (isArray(iterator)) {
        iterator = iterator.values();
    }

    if (! iterator.next) {
        iterator = iterator[Symbol.asyncIterator] || iterator[Symbol.iterator];
    }

    if (! iterator) {
        throw new Error(Object.prototype.toString.call(originalIterator) + ' is not iterable');
    } else if (! isFunction(iterator.next) && isFunction(iterator)) {
        iterator = iterator();
    }

    return new Promise((resolve, reject) => {
        async function next() {
            try {
                const step = await iterator.next();
                if (! step.done) {
                    const retVal = await callback(await step.value);
                    if (undefined !== retVal) {
                        return resolve(retVal);
                    }

                    return next();
                }

                resolve(await step.value);
            } catch (e) {
                reject(e);
            }

            return null;
        }

        next();
    });
};

__jymfony.forAwait = forAwait;
<|endoftext|>


<commit_before>import Web3 from 'web3';
import { incorrectNetworkAlert, noMetaMaskAlert, invalidNetworkIDAlert } from './alerts'
import { getEncodedABIClientSide } from './microservices'
import { GAS_PRICE } from './constants'

// instantiate new web3 instance
const web3 = new Web3();

// get current provider
export function getCurrentProvider() {
	console.log(web3.currentProvider);
  return web3.currentProvider;
}

export function checkWeb3(web3) {
  if (!web3) {
    setTimeout(function() {
      getWeb3((web3) => {
        if (!web3) return noMetaMaskAlert();
        web3.eth.getAccounts().then((accounts) => {
          if (accounts.length === 0) {
            return noMetaMaskAlert();
          }
        });
      });
    }, 500);
  } else {
    web3.eth.getAccounts().then((accounts) => {
      if (accounts.length === 0) {
        return noMetaMaskAlert();
      }
    });
  }
}

export function getWeb3(cb) {
  var web3 = window.web3;
	if (typeof web3 === 'undefined') {
    // no web3, use fallback
    console.error("Please use a web3 browser");
    cb(web3, false);
  } else {
    // window.web3 == web3 most of the time. Don't override the provided,
    // web3, just wrap it in your Web3.
    var myWeb3 = new Web3(web3.currentProvider);

    //checkNetworkVersion(myWeb3, function(isOraclesNetwork) {
    cb(myWeb3, false);
    //});
  }
  return myWeb3;
}

export function checkNetWorkByID(web3, _networkIdFromGET) {
  console.log(_networkIdFromGET);
  if (!_networkIdFromGET) {
    return invalidNetworkIDAlert();
  }
  web3.eth.net.getId().then((_networkIdFromNetwork) => {
    let networkNameFromGET = getNetWorkNameById(_networkIdFromGET);
    let networkNameFromNetwork = getNetWorkNameById(_networkIdFromNetwork);
    if (networkNameFromGET !== networkNameFromNetwork) {
      console.log(networkNameFromGET +"!="+ networkNameFromNetwork);
      incorrectNetworkAlert(networkNameFromGET, networkNameFromNetwork);
    }
  });
}

function getNetWorkNameById(_id) {
  console.log(_id);
  switch (parseInt(_id, 10)) {
    case 1: {
      return "Mainnet";
    } break;
    case 2: {
      return "Morden";
    } break;
    case 3: {
      return "Ropsten";
    } break;
    case 4: {
      return "Rinkeby";
    } break;
    case 42: {
      return "Kovan";
    } break;
     case 12648430: {
       return "Oracles dev test";
    }  break;
    default: {
      return "Unknown";
    } break;
  }
}

export function getNetworkVersion(web3, cb) {
  web3.eth.net.getId().then((netId) => {
    cb(netId);
  });
}

export function setExistingContractParams(abi, addr, $this) {
  let state = $this.state;
  setTimeout(function() {
    getWeb3((web3) => {
      attachToContract(web3, abi, addr, function(err, crowdsaleContract) {
        let propsCount = 0;
        let cbCount = 0;
        propsCount++;
        crowdsaleContract.token.call(function(err, tokenAddr) {
          cbCount++;
          console.log("tokenAddr: " + tokenAddr);
          state.contracts.token.addr = tokenAddr;

          if (propsCount === cbCount) {
            $this.setState(state);
          }
        });

        propsCount++;
        crowdsaleContract.multisigWallet.call(function(err, multisigWalletAddr) {
          cbCount++;
          console.log("multisigWalletAddr: " + multisigWalletAddr);
          state.contracts.multisig.addr = multisigWalletAddr;

          if (propsCount === cbCount) {
            $this.setState(state);
          }
        });
      });
    })
  });
}

export function deployContract(i, web3, abi, bin, params, state, cb) {
  getEncodedABIClientSide(web3, abi, state, params, i, (ABIencoded) => {
    console.log(ABIencoded);
    let binFull = bin + ABIencoded.substr(2);
    web3.eth.getAccounts().then(function(accounts) {
      web3.eth.estimateGas({
        from: accounts[0],
        data: binFull
      }, function(err, estimatedGas) {
        if (err) console.log('errrrrrrrrrrrrrrrrr', err);
        console.log('gas is estimated', estimatedGas, 'err', err)
        let estimatedGasMax = 3716260;
        if (!estimatedGas) estimatedGas = estimatedGasMax;
        if (estimatedGas > estimatedGasMax) estimatedGas = estimatedGasMax;
        else estimatedGas += 100000;

        let contractInstance = new web3.eth.Contract(abi);

        let deployOpts = {
          data: "0x" + bin,
          arguments: params
        };

        let sendOpts = {
          from: accounts[0],
          gas: estimatedGas,
          gasPrice: GAS_PRICE
        };

        let isMined = false;

        contractInstance.deploy(deployOpts).send(sendOpts)
        //contractInstance.new(...totalParams)
        .on('error', function(error) {
          console.log(error);
          return cb(error, null);
        })
        .on('transactionHash', function(transactionHash){
          console.log("contract deployment transaction: " + transactionHash);

          checkTxMined(web3, transactionHash, function txMinedCallback(receipt) {
            if (isMined) return;

            if (receipt) {
              if (receipt.blockNumber) {
                console.log("Contract deployment is mined from polling of tx receipt");
                isMined = true;
                console.log(receipt.contractAddress) // instance with the new contract address
                return cb(null, receipt.contractAddress);
              } else {
                console.log("Still mining... Polling of transaction once more");
                setTimeout(function() {
                  checkTxMined(web3, transactionHash, txMinedCallback)
                }, 5000);
              }
            } else {
              console.log("Still mining... Polling of transaction once more");
              setTimeout(function() {
                checkTxMined(web3, transactionHash, txMinedCallback)
              }, 5000);
            }
          })
        })
        /*.on('receipt', function(receipt){
          if (errorArised) {
           console.log(receipt.contractAddress) // contains the new contract address
           cb(null, receipt.contractAddress);
          }
        })*/
        .on('confirmation', function(confirmationNumber, receipt){
          //console.log(confirmationNumber, receipt);
          /*if (errorArised) {
           console.log(receipt.contractAddress) // contains the new contract address
           cb(null, receipt.contractAddress);
          }*/

        })
        .then(function(newContractInstance){
          if (!isMined) {
            console.log("Contract deployment is mined from Promise");
            isMined = true;
            console.log(newContractInstance.options.address) // instance with the new contract address
            cb(null, newContractInstance.options.address);
          }
        });
      });
    });
  });
}

export function sendTXToContract(web3, method, cb) {
  let isMined = false;
  method
  //contractInstance.new(...totalParams)
  .on('error', function(error) {
    console.log(error);
    return cb(error);
  })
  .on('transactionHash', function(transactionHash){
    console.log("contract method transaction: " + transactionHash);

    checkTxMined(web3, transactionHash, function txMinedCallback(receipt) {
      if (isMined) return;

      if (receipt) {
        if (receipt.blockNumber) {
          console.log("Sending tx to contract is mined from polling of tx receipt");
          isMined = true;
          console.log(receipt) // instance with the new contract address
          return cb();
        } else {
          console.log("Still mining... Polling of transaction once more");
          setTimeout(function() {
            checkTxMined(web3, transactionHash, txMinedCallback)
          }, 5000);
        }
      } else {
        console.log("Still mining... Polling of transaction once more");
        setTimeout(function() {
          checkTxMined(web3, transactionHash, txMinedCallback)
        }, 5000);
      }
    })
  })
  /*.on('receipt', function(receipt){
  })*/
  .on('confirmation', function(confirmationNumber, receipt){
  })
  .then(function(result){
    if (!isMined) {
      console.log("Sending tx to contract is mined from Promise");
      isMined = true;
      console.log(result) // instance with the new contract address
      cb();
    }
  });
}

export function checkTxMined(web3, txhash, cb) {
  web3.eth.getTransactionReceipt(txhash, function(err, receipt) {
    if (receipt)
      console.log(receipt);
    cb(receipt);
  });
}

export function attachToContract(web3, abi, addr, cb) {
  web3.eth.getAccounts().then((accounts) => {
    web3.eth.defaultAccount = accounts[0];
		console.log("web3.eth.defaultAccount:" + web3.eth.defaultAccount);

		let contractInstance = new web3.eth.Contract(abi, addr, {
      from: web3.eth.defaultAccount
    });

    //console.log(contractInstance);
    //console.log(contractInstance.options);

		if (cb) cb(null, contractInstance);
  });
}

// export web3 object instance
export default web3;
<commit_msg>Use web3 HttpProvider in development if web3 is not injected<commit_after>import Web3 from 'web3';
import { incorrectNetworkAlert, noMetaMaskAlert, invalidNetworkIDAlert } from './alerts'
import { getEncodedABIClientSide } from './microservices'
import { GAS_PRICE } from './constants'

// instantiate new web3 instance
const web3 = new Web3();

// get current provider
export function getCurrentProvider() {
	console.log(web3.currentProvider);
  return web3.currentProvider;
}

export function checkWeb3(web3) {
  if (!web3) {
    setTimeout(function() {
      getWeb3((web3) => {
        if (!web3) return noMetaMaskAlert();
        web3.eth.getAccounts().then((accounts) => {
          if (accounts.length === 0) {
            return noMetaMaskAlert();
          }
        });
      });
    }, 500);
  } else {
    web3.eth.getAccounts().then((accounts) => {
      if (accounts.length === 0) {
        return noMetaMaskAlert();
      }
    });
  }
}

export function getWeb3(cb) {
  var web3 = window.web3;
	if (typeof web3 === 'undefined') {
    // no web3, use fallback
    console.error("Please use a web3 browser");
    if (process.env.NODE_ENV === 'development') {
      web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
    }

    cb(web3, false);
  } else {
    // window.web3 == web3 most of the time. Don't override the provided,
    // web3, just wrap it in your Web3.
    var myWeb3 = new Web3(web3.currentProvider);

    //checkNetworkVersion(myWeb3, function(isOraclesNetwork) {
    cb(myWeb3, false);
    //});
  }
  return myWeb3;
}

export function checkNetWorkByID(web3, _networkIdFromGET) {
  console.log(_networkIdFromGET);
  if (!_networkIdFromGET) {
    return invalidNetworkIDAlert();
  }
  web3.eth.net.getId().then((_networkIdFromNetwork) => {
    let networkNameFromGET = getNetWorkNameById(_networkIdFromGET);
    let networkNameFromNetwork = getNetWorkNameById(_networkIdFromNetwork);
    if (networkNameFromGET !== networkNameFromNetwork) {
      console.log(networkNameFromGET +"!="+ networkNameFromNetwork);
      incorrectNetworkAlert(networkNameFromGET, networkNameFromNetwork);
    }
  });
}

function getNetWorkNameById(_id) {
  console.log(_id);
  switch (parseInt(_id, 10)) {
    case 1: {
      return "Mainnet";
    } break;
    case 2: {
      return "Morden";
    } break;
    case 3: {
      return "Ropsten";
    } break;
    case 4: {
      return "Rinkeby";
    } break;
    case 42: {
      return "Kovan";
    } break;
     case 12648430: {
       return "Oracles dev test";
    }  break;
    default: {
      return "Unknown";
    } break;
  }
}

export function getNetworkVersion(web3, cb) {
  web3.eth.net.getId().then((netId) => {
    cb(netId);
  });
}

export function setExistingContractParams(abi, addr, $this) {
  let state = $this.state;
  setTimeout(function() {
    getWeb3((web3) => {
      attachToContract(web3, abi, addr, function(err, crowdsaleContract) {
        let propsCount = 0;
        let cbCount = 0;
        propsCount++;
        crowdsaleContract.token.call(function(err, tokenAddr) {
          cbCount++;
          console.log("tokenAddr: " + tokenAddr);
          state.contracts.token.addr = tokenAddr;

          if (propsCount === cbCount) {
            $this.setState(state);
          }
        });

        propsCount++;
        crowdsaleContract.multisigWallet.call(function(err, multisigWalletAddr) {
          cbCount++;
          console.log("multisigWalletAddr: " + multisigWalletAddr);
          state.contracts.multisig.addr = multisigWalletAddr;

          if (propsCount === cbCount) {
            $this.setState(state);
          }
        });
      });
    })
  });
}

export function deployContract(i, web3, abi, bin, params, state, cb) {
  getEncodedABIClientSide(web3, abi, state, params, i, (ABIencoded) => {
    console.log(ABIencoded);
    let binFull = bin + ABIencoded.substr(2);
    web3.eth.getAccounts().then(function(accounts) {
      web3.eth.estimateGas({
        from: accounts[0],
        data: binFull
      }, function(err, estimatedGas) {
        if (err) console.log('errrrrrrrrrrrrrrrrr', err);
        console.log('gas is estimated', estimatedGas, 'err', err)
        let estimatedGasMax = 3716260;
        if (!estimatedGas) estimatedGas = estimatedGasMax;
        if (estimatedGas > estimatedGasMax) estimatedGas = estimatedGasMax;
        else estimatedGas += 100000;

        let contractInstance = new web3.eth.Contract(abi);

        let deployOpts = {
          data: "0x" + bin,
          arguments: params
        };

        let sendOpts = {
          from: accounts[0],
          gas: estimatedGas,
          gasPrice: GAS_PRICE
        };

        let isMined = false;

        contractInstance.deploy(deployOpts).send(sendOpts)
        //contractInstance.new(...totalParams)
        .on('error', function(error) {
          console.log(error);
          return cb(error, null);
        })
        .on('transactionHash', function(transactionHash){
          console.log("contract deployment transaction: " + transactionHash);

          checkTxMined(web3, transactionHash, function txMinedCallback(receipt) {
            if (isMined) return;

            if (receipt) {
              if (receipt.blockNumber) {
                console.log("Contract deployment is mined from polling of tx receipt");
                isMined = true;
                console.log(receipt.contractAddress) // instance with the new contract address
                return cb(null, receipt.contractAddress);
              } else {
                console.log("Still mining... Polling of transaction once more");
                setTimeout(function() {
                  checkTxMined(web3, transactionHash, txMinedCallback)
                }, 5000);
              }
            } else {
              console.log("Still mining... Polling of transaction once more");
              setTimeout(function() {
                checkTxMined(web3, transactionHash, txMinedCallback)
              }, 5000);
            }
          })
        })
        /*.on('receipt', function(receipt){
          if (errorArised) {
           console.log(receipt.contractAddress) // contains the new contract address
           cb(null, receipt.contractAddress);
          }
        })*/
        .on('confirmation', function(confirmationNumber, receipt){
          //console.log(confirmationNumber, receipt);
          /*if (errorArised) {
           console.log(receipt.contractAddress) // contains the new contract address
           cb(null, receipt.contractAddress);
          }*/

        })
        .then(function(newContractInstance){
          if (!isMined) {
            console.log("Contract deployment is mined from Promise");
            isMined = true;
            console.log(newContractInstance.options.address) // instance with the new contract address
            cb(null, newContractInstance.options.address);
          }
        });
      });
    });
  });
}

export function sendTXToContract(web3, method, cb) {
  let isMined = false;
  method
  //contractInstance.new(...totalParams)
  .on('error', function(error) {
    console.log(error);
    return cb(error);
  })
  .on('transactionHash', function(transactionHash){
    console.log("contract method transaction: " + transactionHash);

    checkTxMined(web3, transactionHash, function txMinedCallback(receipt) {
      if (isMined) return;

      if (receipt) {
        if (receipt.blockNumber) {
          console.log("Sending tx to contract is mined from polling of tx receipt");
          isMined = true;
          console.log(receipt) // instance with the new contract address
          return cb();
        } else {
          console.log("Still mining... Polling of transaction once more");
          setTimeout(function() {
            checkTxMined(web3, transactionHash, txMinedCallback)
          }, 5000);
        }
      } else {
        console.log("Still mining... Polling of transaction once more");
        setTimeout(function() {
          checkTxMined(web3, transactionHash, txMinedCallback)
        }, 5000);
      }
    })
  })
  /*.on('receipt', function(receipt){
  })*/
  .on('confirmation', function(confirmationNumber, receipt){
  })
  .then(function(result){
    if (!isMined) {
      console.log("Sending tx to contract is mined from Promise");
      isMined = true;
      console.log(result) // instance with the new contract address
      cb();
    }
  });
}

export function checkTxMined(web3, txhash, cb) {
  web3.eth.getTransactionReceipt(txhash, function(err, receipt) {
    if (receipt)
      console.log(receipt);
    cb(receipt);
  });
}

export function attachToContract(web3, abi, addr, cb) {
  web3.eth.getAccounts().then((accounts) => {
    web3.eth.defaultAccount = accounts[0];
		console.log("web3.eth.defaultAccount:" + web3.eth.defaultAccount);

		let contractInstance = new web3.eth.Contract(abi, addr, {
      from: web3.eth.defaultAccount
    });

    //console.log(contractInstance);
    //console.log(contractInstance.options);

		if (cb) cb(null, contractInstance);
  });
}

// export web3 object instance
export default web3;
<|endoftext|>


<commit_before>import { register } from '../ChatCommands';
import { log } from '../../actions/ChatActionCreators';
import {
  setVolume,
  mute,
  unmute
} from '../../actions/PlaybackActionCreators';
import {
  doUpvote,
  doDownvote
} from '../../actions/VoteActionCreators';

register(
  'volume',
  'Set the current volume.',
  {
    action: (value) => {
      const volume = parseInt(value, 10);
      if (!Number.isFinite(volume) || volume < 0 || volume > 100) {
        return log('Volume must be a number between 0 and 100.');
      }
      return setVolume(volume);
    }
  }
);

register('mute', 'Mute the volume.', {
  action: () => mute()
});

register('unmute', 'Unmute the media volume.', {
  action: () => unmute()
});

register('upvote', 'Upvote the current track.', {
  action: () => doUpvote()
});

register('downvote', 'Downvote the current track.', {
  action: () => doDownvote()
});
<commit_msg>Add /playback chat command to toggle media playback. (#777)<commit_after>import { register } from '../ChatCommands';
import { log } from '../../actions/ChatActionCreators';
import {
  setVolume,
  mute,
  unmute
} from '../../actions/PlaybackActionCreators';
import {
  doUpvote,
  doDownvote
} from '../../actions/VoteActionCreators';
import { set as setSetting } from '../../actions/SettingsActionCreators';

register(
  'volume',
  'Set the current volume.',
  {
    action: (value) => {
      const volume = parseInt(value, 10);
      if (!Number.isFinite(volume) || volume < 0 || volume > 100) {
        return log('Volume must be a number between 0 and 100.');
      }
      return setVolume(volume);
    }
  }
);

register('mute', 'Mute the volume.', {
  action: () => mute()
});

register('unmute', 'Unmute the media volume.', {
  action: () => unmute()
});

register('upvote', 'Upvote the current track.', {
  action: () => doUpvote()
});

register('downvote', 'Downvote the current track.', {
  action: () => doDownvote()
});

register('playback', 'Enable or disable playback. Syntax: "/playback on|off"', {
  action: (type) => {
    if (type.toLowerCase() === 'on') {
      return setSetting('videoEnabled', true);
    }
    if (type.toLowerCase() === 'off') {
      return setSetting('videoEnabled', false);
    }
    return log('Use "/playback on" to enable media playback or "/playback off" to disable it.');
  }
});
<|endoftext|>


<commit_before>import I18n from "i18n-js";

/**
* I18n Helper
*
* Provides helper methods for I18n.
*
* @object I18nHelper
* @param {String} value
*/
const I18nHelper = {

  /**
   * Formats delimiter and separator through i18n
   *
   * @method i18nFormatting
   * @return {Object} Delimeter and separator values
   */
  i18nFormatting: {
    delimiter: I18n.t("number.format.delimiter", { defaultValue: "," }),
    separator: I18n.t("number.format.separator", { defaultValue: "." })
  },

  /**
   * Adds formatting to the value
   *
   * @method formatValue
   * @param {String} value Unformatted Value
   * @return {String} formated value
   */
  formatValue: (valueToFormat = 0, precision =  2) => {
    valueToFormat = valueToFormat;
    valueToFormat = I18n.toNumber(valueToFormat, {
      precision: precision,
      delimiter: I18nHelper.i18nFormatting.delimiter,
      separator: I18nHelper.i18nFormatting.separator
    });
    return valueToFormat;
  },

  /**
   * Removes delimiters and separators from value
   *
   * @method removeFormat
   * @param {String} valueWithFormat Formatted value
   * @return {String} value with no format
   */
  removeFormat: (valueWithFormat = '') => {
    let value = valueWithFormat;
    let regex = new RegExp('\\' + I18nHelper.i18nFormatting.delimiter, "g");

    value = value.replace(regex, "", "g");
    value = value.replace(I18nHelper.i18nFormatting.separator, ".");

    return value;
  }
};

export default I18nHelper;
<commit_msg>code cleanup<commit_after>import I18n from "i18n-js";

/**
* I18n Helper
*
* Provides helper methods for I18n.
*
* @object I18nHelper
* @param {String} value
*/
const I18nHelper = {

  /**
   * Formats delimiter and separator through i18n
   *
   * @method i18nFormatting
   * @return {Object} Delimeter and separator values
   */
  i18nFormatting: {
    delimiter: I18n.t("number.format.delimiter", { defaultValue: "," }),
    separator: I18n.t("number.format.separator", { defaultValue: "." })
  },

  /**
   * Adds formatting to the value
   *
   * @method formatValue
   * @param {String} value Unformatted Value
   * @return {String} formated value
   */
  formatValue: (valueToFormat = 0, precision =  2) => {
    return  I18n.toNumber(valueToFormat, {
      precision: precision,
      delimiter: I18nHelper.i18nFormatting.delimiter,
      separator: I18nHelper.i18nFormatting.separator
    });
  },

  /**
   * Removes delimiters and separators from value
   *
   * @method removeFormat
   * @param {String} valueWithFormat Formatted value
   * @return {String} value with no format
   */
  removeFormat: (valueWithFormat = '') => {
    let regex = new RegExp('\\' + I18nHelper.i18nFormatting.delimiter, "g");

    valueWithFormat = valueWithFormat.replace(regex, "", "g");

    return valueWithFormat.replace(I18nHelper.i18nFormatting.separator, ".");
  }
};

export default I18nHelper;
<|endoftext|>