<commit_before>if (typeof require === "function") {
    var bigInt = require("big-integer");
    var getRandomValues = require('get-random-values');
    var UTF8 = require('utf-8');
} else {

}

var _sssa_utils = (function (root) {
    var prime = bigInt("115792089237316195423570985008687907853269984665640564039457584007913129639747");

    function random() {
        var bytes = new Uint8Array(32),
            string = "",
            i = 0;

        getRandomValues(bytes)
        for (i in bytes) {
            string += Array((2 - bytes[i].toString(16).length) + 1).join(0) + bytes[i].toString(16);
        }

        return bigInt(string, 16);
    }

    function split_ints(secrets) {
        var result = [],
            working = [],
            i = 0,
            hex_data = "";

        working = UTF8.setBytesFromString(secrets);

        for (i in working) {
            hex_data += Array((2 - working[i].toString(16).length) + 1).join(0) + working[i].toString(16);
        }

        for (i = 0; i < hex_data.length/64; i++) {
            if ((i+1)*64 < hex_data.length) {
                result[i] = bigInt(hex_data.substring(i*64, (i+1)*64), 16);
            } else {
                result[i] = bigInt(hex_data.substring(i*64) + Array(((i+1)*64 - hex_data.length)+1).join(0), 16);
            }
        }

        return result;
    }

    function merge_ints(secrets) {
        var hex_data = "",
            bytes = [],
            temp = "",
            i = 0;

        for (i in secrets) {
            temp = secrets[i].toString(16);
            temp = Array(64 - temp.length + 1).join(0) + temp;
            hex_data += temp;
        }

        hex_data = hex_data.replace(/(00){1,}$/, '');

        for (i = 0; i < hex_data.length/2; i++) {
            bytes.push(parseInt(hex_data.substring(i*2, (i+1)*2), 16));
        }

        return UTF8.getStringFromBytes(bytes);
    }

    return {
        'random': random,
        'split_ints': split_ints,
        'merge_ints': merge_ints,
    }
}(this));

var _sssa = (function(root) {
    console.log(_sssa_utils);
    var utils = _sssa_utils;

    function create(minimum, shares, raw) {
        if (minimum < shares) {
            return;
        }

        var secret = utils.split_int(raw),
            numbers = [bigInt(0)],
            polynomial = [],
            result = [],
            i = 0,
            j = 1;

        for (i in secret) {
            polynomial.push([secret[i]]);
            for (j = 1; j < minimum; j++) {
                value = util.random();
                while (value in numbers) {
                    value = util.random();
                }
                numbers.push(value);

                polynomial[i].push(value);
            }
        }

        for (i = 0; i < shares; i++) {
            for (j in secret) {
                value = util.random();
                while (value in numbers) {
                    value = util.random();
                }
                numbers.push(value);

                if (typeof result[i] !== typeof "string") {
                    result[i] = "";
                } else {
                    result[i] += utils.to_base64(value);
                    result[i] += utils.to_base64(utils.evaluate_polynomial(polynomial[j], value));
                }
            }
        }

        return result;
    }

    function combine(shares) {
        var secrets = [],
            share = "",
            count = 0,
            cshare = "",
            secret = [],
            origin = bigInt(0),
            originy = bigInt(0),
            numerator = bigInt(1),
            denominator = bigInt(1),
            i = 0,
            j = 0,
            k = 0;

        for (i in shares) {
            if (shares[i].length % 88 != 0) {
                return;
            }

            share = shares[i];
            count = share.length / 88;
            secrets[i] = [];

            for (j = 0; j < count; j++) {
                cshare = share.substring(j*88, (j+1)*88);
                secrets[i][j] = [utils.from_base64(cshare.substring(0, 44)), utils.from_base64(cshare.substring(44))];
            }
        }

        for (j = 0; j < secrets[0].length; j++) {
            secret[j] = bigInt(0);
            for (i in secrets) {
                origin = secrets[i][j][0];
                originy = secrets[i][j][1];
                numerator = bigInt(1);
                denominator = bigInt(1);

                for (k in secrets) {
                    if (k !== i) {
                        numerator = numerator.multiply(secrets[k][j][0].multiply(-1)).mod(utils.prime);
                        denominator = denominator.multiply(origin.subtract(secrets[k][j][0])).mod(utils.prime);
                    }
                }

                secret[j] = secret[j].add(originy.multiply(numerator).mod(utils.prime).multiply(denominator).mod(utils.prime)).mod(utils.prime);
            }
        }

        return utils.merge_int(secret);
    }

    return sssa = {
        'create': create,
        'combine': combine
    };
}(this));

// Node.js check
if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
    module.exports = _sssa;
} else {
    sssa = _sssa;
}
<commit_msg>Working splitting, base64 encode/decode<commit_after>if (typeof require === "function") {
    var bigInt = require("big-integer");
    var getRandomValues = require('get-random-values');
    var UTF8 = require('utf-8');
}

var _sssa_utils = (function (root) {
    var prime = bigInt("115792089237316195423570985008687907853269984665640564039457584007913129639747");

    function random() {
        var bytes = new Uint8Array(32),
            string = "",
            i = 0;

        getRandomValues(bytes)
        for (i in bytes) {
            string += Array((2 - bytes[i].toString(16).length) + 1).join(0) + bytes[i].toString(16);
        }

        return bigInt(string, 16);
    }

    function split_ints(secrets) {
        var result = [],
            working = [],
            i = 0,
            hex_data = "";

        working = UTF8.setBytesFromString(secrets);

        for (i in working) {
            hex_data += Array((2 - working[i].toString(16).length) + 1).join(0) + working[i].toString(16);
        }

        for (i = 0; i < hex_data.length/64; i++) {
            if ((i+1)*64 < hex_data.length) {
                result[i] = bigInt(hex_data.substring(i*64, (i+1)*64), 16);
            } else {
                result[i] = bigInt(hex_data.substring(i*64) + Array(((i+1)*64 - hex_data.length)+1).join(0), 16);
            }
        }

        return result;
    }

    function merge_ints(secrets) {
        var hex_data = "",
            bytes = [],
            temp = "",
            i = 0;

        for (i in secrets) {
            temp = secrets[i].toString(16);
            temp = Array(64 - temp.length + 1).join(0) + temp;
            hex_data += temp;
        }

        hex_data = hex_data.replace(/(00){1,}$/, '');

        for (i = 0; i < hex_data.length/2; i++) {
            bytes.push(parseInt(hex_data.substring(i*2, (i+1)*2), 16));
        }

        return UTF8.getStringFromBytes(bytes);
    }

    function evaluate_polynomial(coefficients, value) {
        var result = bigInt(coefficients[0]),
            i = 0,
            tmp = bigInt(0);

        for (i = 0; i < coefficients.length; i++) {
            result = result.add(value.modPow(s, prime).multiply(coefficients[i]).mod(prime));
        }

        return result.mod(prime);
    }

    function to_base64(number) {
        var hex_data = number.toString(16),
            result = "",
            i = 0;

        hex_data = Array(64 - hex_data.length + 1).join('0') + hex_data;

        for (i = 0; i < hex_data.length/2; i++) {
            result += String.fromCharCode(parseInt(hex_data.substring(i*2, (i+1)*2), 16));
        }

        return btoa(result);
    }

    function from_base64(number) {
        var bytes = atob(number),
            hex_data = "",
            tmp = "",
            i = 0;

        for (i = 0; i < bytes.length; i++) {
            temp = bytes.charCodeAt(i).toString(16);
            temp = Array(2 - (temp.length % 3) + 1).join(0) + temp;
            hex_data += temp;
        }

        hex_data = hex_data.replace(/^(00){1,}/, '');

        return bigInt(hex_data, 16);
    }

    return {
        'random': random,
        'split_ints': split_ints,
        'merge_ints': merge_ints,
        'to_base64': to_base64,
        'from_base64': from_base64,
    }
}(this));

var _sssa = (function(root) {
    var utils = _sssa_utils;

    function create(minimum, shares, raw) {
        if (minimum < shares) {
            return;
        }

        var secret = utils.split_int(raw),
            numbers = [bigInt(0)],
            polynomial = [],
            result = [],
            i = 0,
            j = 1;

        for (i in secret) {
            polynomial.push([secret[i]]);
            for (j = 1; j < minimum; j++) {
                value = util.random();
                while (value in numbers) {
                    value = util.random();
                }
                numbers.push(value);

                polynomial[i].push(value);
            }
        }

        for (i = 0; i < shares; i++) {
            for (j in secret) {
                value = util.random();
                while (value in numbers) {
                    value = util.random();
                }
                numbers.push(value);

                if (typeof result[i] !== typeof "string") {
                    result[i] = "";
                } else {
                    result[i] += utils.to_base64(value);
                    result[i] += utils.to_base64(utils.evaluate_polynomial(polynomial[j], value));
                }
            }
        }

        return result;
    }

    function combine(shares) {
        var secrets = [],
            share = "",
            count = 0,
            cshare = "",
            secret = [],
            origin = bigInt(0),
            originy = bigInt(0),
            numerator = bigInt(1),
            denominator = bigInt(1),
            i = 0,
            j = 0,
            k = 0;

        for (i in shares) {
            if (shares[i].length % 88 != 0) {
                return;
            }

            share = shares[i];
            count = share.length / 88;
            secrets[i] = [];

            for (j = 0; j < count; j++) {
                cshare = share.substring(j*88, (j+1)*88);
                secrets[i][j] = [utils.from_base64(cshare.substring(0, 44)), utils.from_base64(cshare.substring(44))];
            }
        }

        for (j = 0; j < secrets[0].length; j++) {
            secret[j] = bigInt(0);
            for (i in secrets) {
                origin = secrets[i][j][0];
                originy = secrets[i][j][1];
                numerator = bigInt(1);
                denominator = bigInt(1);

                for (k in secrets) {
                    if (k !== i) {
                        numerator = numerator.multiply(secrets[k][j][0].multiply(-1)).mod(utils.prime);
                        denominator = denominator.multiply(origin.subtract(secrets[k][j][0])).mod(utils.prime);
                    }
                }

                secret[j] = secret[j].add(originy.multiply(numerator).mod(utils.prime).multiply(denominator).mod(utils.prime)).mod(utils.prime);
            }
        }

        return utils.merge_int(secret);
    }

    return sssa = {
        'create': create,
        'combine': combine
    };
}(this));

// Node.js check
if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
    var sssa = _sssa;
    module.exports = sssa;
} else {
    sssa = _sssa;
}
<|endoftext|>


<commit_before>/**
 * Caps main module that defines the public API
 */
define(function( require ) {
        'use strict';

        var $ = require('jquery'),
            version = '0.16.4';

        // ECMA 5 polyfills
        require('helper/polyfills');

        // caps API
        return  {
            fn: require('fn/index'),
            version: version,
            getListInfo: require('getListInfo/index'),
            getListItems: require('getListItems/index'),
            processBatchData: require('processBatchData/index')
        };
    }
);<commit_msg>add events to caps namespace<commit_after>/**
 * Caps main module that defines the public API
 */
define(function( require ) {
        'use strict';

        var $ = require('jquery'),
            Events = require('fn/events'),
            version = '0.17.1',
            caps;

        // ECMA 5 polyfills
        require('helper/polyfills');

        caps = {
            fn: require('fn/index'),
            version: version,
            getListInfo: require('getListInfo/index'),
            getListItems: require('getListItems/index'),
            processBatchData: require('processBatchData/index')
        };

        // Add events in caps name space
        Events.includeIn(caps);

        // caps API
        return  caps;
    }
);<|endoftext|>


<commit_before>const request = require('request')
const lodash = require('lodash')
const json2xml = require('jsontoxml')
const xmlJsonParser = require('xml2json')
const utils = require('./utils')
const config = require('./config')

const wrapPictureResource = (o) => ({
  fileName: o.fileName,
  description: o.description,
  base64: o.file,
})

const wrapCaseResource = (o) => ({
  caseId: o.service_request_id,
  status: lodash.isEmpty(o.status) ? 0 : 1,
  district: o.area,
  serviceName: o.service_name,
  subjectName: o.subproject,
  agency: o.agency,
  description: o.description,
  address: o.address_string,
  latitude: lodash.isEmpty(o.lat) ? null : o.lat,
  longitude: lodash.isEmpty(o.long) ? null: o.long,
  createAt: o.requested_datetime,
  updateAt: lodash.isEmpty(o.updated_datetime) ? null : o.updated_datetime,
  pictures: ((!o.Pictures) ? [] : (lodash.isArray(o.Pictures.Picture)) ? o.Pictures.Picture : [o.Pictures.Picture]).map(wrapPictureResource),
})

const getCase = function(caseId, callback) {
  const body = json2xml(utils.wrapValueCdataTag({
    root: {
      city_id: config.CITY_ID,
      service_request_id: caseId, },
  }))
  request.get({
    url: `${config.API_HOST}/ServiceRequestsQuery.aspx`,
    json: false,
    body: body,
  }, function() {
    utils.validateResponse(...arguments, (e, data) => {
      if (e) {
        return callback(e, null)
      }
      callback(e, (data.root.records) ? wrapCaseResource(data.root.records.record) : null)
    })
  })
}

const getCasesByIds = function(caseIds, callback) {
  const body = json2xml(utils.wrapValueCdataTag({
    root: {
      city_id: config.CITY_ID,
      service_request_id: caseIds.join(','),
    },
  }))
  request.get({
    url: `${config.API_HOST}/ServiceRequestsQuery.aspx`,
    json: false,
    body: body,
  }, function() {
    utils.validateResponse(...arguments, (e, data) => {
      if (e) {
        return callback(e, null)
      }
      const num = parseInt(data.root.count)
      switch (num) {
        case 0: return callback(e, {
          num: num,
          cases: [],
        })
        case 1: return callback(e, {
          num: num,
          cases: [wrapCaseResource(data.root.records.record)],
        })
        default: return callback(e, {
          num: num,
          cases: data.root.records.record.map(wrapCaseResource),
        })
      }
    })
  })
}

const getCases = function() {
  if (3 === arguments.length) {
    [options, callback] = [{}, arguments[2]]
  }
  else if (4 <= arguments.length) {
    [options, callback] = [arguments[2], arguments[3]]
  }
  else {
    return
  }
  const [startTime, endTime] = [arguments[0], arguments[1]]
  const datetimePattern = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/
  if (!datetimePattern.exec(startTime) || !datetimePattern.exec(endTime)) {
    return callback('Invalid time format', null)
  }
  if (options.serviceName && Array.isArray(options.serviceName)) {
    options.serviceName = options.serviceName.join(',')
  }
  const root = utils.camel2Snake(Object.assign({
    cityId: config.CITY_ID,
    startDate: startTime,
    endDate: endTime,
  }, options))
  const body = json2xml(utils.wrapValueCdataTag({root: root}))
  request.get({
    url: `${config.API_HOST}/ServiceRequestsQuery.aspx`,
    json: false,
    body: body,
  }, function() {
    utils.validateResponse(...arguments, (e, data) => {
      if (e) {
        return callback(e, null)
      }
      const num = parseInt(data.root.count)
      switch (num) {
        case 0: return callback(e, {
          num: num,
          cases: [],
        })
        case 1: return callback(e, {
          num: num,
          cases: [wrapCaseResource(data.root.records.record)],
        })
        default: return callback(e, {
          num: num,
          cases: data.root.records.record.map(wrapCaseResource),
        })
      }
    })
  })
}

module.exports = {
  getCase: getCase,
  getCases: getCases,
  getCasesByIds: getCasesByIds,
}
<commit_msg>Rename the variables<commit_after>const request = require('request')
const lodash = require('lodash')
const json2xml = require('jsontoxml')
const xmlJsonParser = require('xml2json')
const utils = require('./utils')
const config = require('./config')

const wrapPictureResource = (o) => ({
  fileName: o.fileName,
  description: o.description,
  base64: o.file,
})

const wrapCaseResource = (o) => ({
  caseId: o.service_request_id,
  status: lodash.isEmpty(o.status) ? 0 : 1,
  district: o.area,
  serviceName: o.service_name,
  subjectName: o.subproject,
  agency: o.agency,
  description: o.description,
  address: o.address_string,
  latitude: lodash.isEmpty(o.lat) ? null : o.lat,
  longitude: lodash.isEmpty(o.long) ? null: o.long,
  createAt: o.requested_datetime,
  updateAt: lodash.isEmpty(o.updated_datetime) ? null : o.updated_datetime,
  pictures: ((!o.Pictures) ? [] : (lodash.isArray(o.Pictures.Picture)) ? o.Pictures.Picture : [o.Pictures.Picture]).map(wrapPictureResource),
})

const getCase = function(caseId, callback) {
  const body = json2xml(utils.wrapValueCdataTag({
    root: {
      city_id: config.CITY_ID,
      service_request_id: caseId, },
  }))
  request.get({
    url: `${config.API_HOST}/ServiceRequestsQuery.aspx`,
    json: false,
    body: body,
  }, function() {
    utils.validateResponse(...arguments, (e, data) => {
      if (e) {
        return callback(e, null)
      }
      callback(e, (data.root.records) ? wrapCaseResource(data.root.records.record) : null)
    })
  })
}

const getCasesByIds = function(caseIds, callback) {
  const body = json2xml(utils.wrapValueCdataTag({
    root: {
      city_id: config.CITY_ID,
      service_request_id: caseIds.join(','),
    },
  }))
  request.get({
    url: `${config.API_HOST}/ServiceRequestsQuery.aspx`,
    json: false,
    body: body,
  }, function() {
    utils.validateResponse(...arguments, (e, data) => {
      if (e) {
        return callback(e, null)
      }
      const num = parseInt(data.root.count)
      switch (num) {
        case 0: return callback(e, {
          num: num,
          cases: [],
        })
        case 1: return callback(e, {
          num: num,
          cases: [wrapCaseResource(data.root.records.record)],
        })
        default: return callback(e, {
          num: num,
          cases: data.root.records.record.map(wrapCaseResource),
        })
      }
    })
  })
}

const getCases = function() {
  if (3 === arguments.length) {
    [options, callback] = [{}, arguments[2]]
  }
  else if (4 <= arguments.length) {
    [options, callback] = [arguments[2], arguments[3]]
  }
  else {
    return
  }
  const [startFrom, endTo] = [arguments[0], arguments[1]]
  const datetimePattern = /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/
  if (!datetimePattern.exec(startFrom) || !datetimePattern.exec(endTo)) {
    return callback('Invalid time format', null)
  }
  if (options.serviceName && Array.isArray(options.serviceName)) {
    options.serviceName = options.serviceName.join(',')
  }
  const root = utils.camel2Snake(Object.assign({
    cityId: config.CITY_ID,
    startDate: startFrom,
    endDate: endTo,
  }, options))
  const body = json2xml(utils.wrapValueCdataTag({root: root}))
  request.get({
    url: `${config.API_HOST}/ServiceRequestsQuery.aspx`,
    json: false,
    body: body,
  }, function() {
    utils.validateResponse(...arguments, (e, data) => {
      if (e) {
        return callback(e, null)
      }
      const num = parseInt(data.root.count)
      switch (num) {
        case 0: return callback(e, {
          num: num,
          cases: [],
        })
        case 1: return callback(e, {
          num: num,
          cases: [wrapCaseResource(data.root.records.record)],
        })
        default: return callback(e, {
          num: num,
          cases: data.root.records.record.map(wrapCaseResource),
        })
      }
    })
  })
}

module.exports = {
  getCase: getCase,
  getCases: getCases,
  getCasesByIds: getCasesByIds,
}
<|endoftext|>


<commit_before>// Bitcoin utility functions

var Crypto = require('./crypto-js/index');

module.exports = {
  /**
   * Cross-browser compatibility version of Array.isArray.
   */
  isArray: Array.isArray || function(o)
  {
    return Object.prototype.toString.call(o) === '[object Array]';
  },

  /**
   * Turn an integer into a little-endian array of |length| bytes
   */
  numToBytes: function(num, length) {
    if (length === undefined) length = 8;
    if (length === 0) return [];
    return [num % 256].concat(this.numToBytes(Math.floor(num / 256), length - 1));
  },

  bytesToNum: function(bytes) {
    var num = 0;
    var factor = 1;
    for (var i = 0; i < bytes.length; ++i) {
      num += bytes[i] * factor;
      factor *= 256;
    }
    return num;
  },

  /**
   * Turn an integer into a "var_int".
   *
   * "var_int" is a variable length integer used by Bitcoin's binary format.
   *
   * NOTE:  This function was just buggy in the original implementation.
   *
   * Returns a byte array.
   */
  numToVarInt: function (i) {
    if (i < 0xfd) {
      // unsigned char
      return [i];
    } else if (i < 0x10000) {
      // unsigned short (LE)
      return [0xfd, i & 255, i >>> 8];    // little endian!
    } else if (i < 0x100000000) {
      // unsigned int (LE)
      return [0xfe].concat(Crypto.util.wordsToBytes([i]).reverse());  // little endian!
    } else {
      throw "long long not implemented";
      // unsigned long long (LE)
      //return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i]).reverse());
    }
  },

  hexToBytes: function(hex) {
    for (var bytes = [], c = 0; c < hex.length; c += 2) {
      var byte = parseInt(hex.substr(c, 2), 16);
      if (isNaN(byte)) {
        throw 'illegal input';
      }
      bytes.push(byte);
    }
    return bytes;
  },

  bytesToHex: function (bytes) {
    for (var hex = [], i = 0; i < bytes.length; i++) {
      if (bytes[i] > 0xff) {
        throw 'illegal input';
      }
      hex.push((bytes[i] >>> 4).toString(16));
      hex.push((bytes[i] & 0xF).toString(16));
    }
    return hex.join("");
  },

  /**
   * Parse a Bitcoin value byte array, returning a BigInteger.
   */
  valueToBigInt: function (valueBuffer)
  {
    if (valueBuffer instanceof BigInteger) return valueBuffer;

    // Prepend zero byte to prevent interpretation as negative integer
    return BigInteger.fromByteArrayUnsigned(valueBuffer);
  },

  /**
   * Format a Bitcoin value as a string.
   *
   * Takes a BigInteger or byte-array and returns that amount of Bitcoins in a
   * nice standard formatting.
   *
   * Examples:
   * 12.3555
   * 0.1234
   * 900.99998888
   * 34.00
   */
  formatValue: function (valueBuffer) {
    var value = this.valueToBigInt(valueBuffer).toString();
    var integerPart = value.length > 8 ? value.substr(0, value.length-8) : '0';
    var decimalPart = value.length > 8 ? value.substr(value.length-8) : value;
    while (decimalPart.length < 8) decimalPart = "0"+decimalPart;
    decimalPart = decimalPart.replace(/0*$/, '');
    while (decimalPart.length < 2) decimalPart += "0";
    return integerPart+"."+decimalPart;
  },

  /**
   * Parse a floating point string as a Bitcoin value.
   *
   * Keep in mind that parsing user input is messy. You should always display
   * the parsed value back to the user to make sure we understood his input
   * correctly.
   */
  parseValue: function (valueString) {
    // TODO: Detect other number formats (e.g. comma as decimal separator)
    var valueComp = valueString.split('.');
    var integralPart = valueComp[0];
    var fractionalPart = valueComp[1] || "0";
    while (fractionalPart.length < 8) fractionalPart += "0";
    fractionalPart = fractionalPart.replace(/^0+/g, '');
    var value = BigInteger.valueOf(parseInt(integralPart));
    value = value.multiply(BigInteger.valueOf(100000000));
    value = value.add(BigInteger.valueOf(parseInt(fractionalPart)));
    return value;
  },

  /**
   * Calculate RIPEMD160(SHA256(data)).
   *
   * Takes an arbitrary byte array as inputs and returns the hash as a byte
   * array.
   */
  sha256ripe160: function (data) {
    return Crypto.RIPEMD160(Crypto.SHA256(data, {asBytes: true}), {asBytes: true});
  },

  /**
   * Calculate SHA256(SHA256(data)).
   *
   * Takes an arbitrary byte array as inputs and returns the doubly hashed
   * data as a byte array.
   */
  dsha256: function (data) {
    return Crypto.SHA256(Crypto.SHA256(data, { asBytes: true }), { asBytes: true });
  }
};
<commit_msg>Remove dead code<commit_after>// Bitcoin utility functions

var Crypto = require('./crypto-js/index');

module.exports = {
  /**
   * Cross-browser compatibility version of Array.isArray.
   */
  isArray: Array.isArray || function(o)
  {
    return Object.prototype.toString.call(o) === '[object Array]';
  },

  /**
   * Turn an integer into a little-endian array of |length| bytes
   */
  numToBytes: function(num, length) {
    if (length === undefined) length = 8;
    if (length === 0) return [];
    return [num % 256].concat(this.numToBytes(Math.floor(num / 256), length - 1));
  },

  bytesToNum: function(bytes) {
    var num = 0;
    var factor = 1;
    for (var i = 0; i < bytes.length; ++i) {
      num += bytes[i] * factor;
      factor *= 256;
    }
    return num;
  },

  /**
   * Turn an integer into a "var_int".
   *
   * "var_int" is a variable length integer used by Bitcoin's binary format.
   *
   * NOTE:  This function was just buggy in the original implementation.
   *
   * Returns a byte array.
   */
  numToVarInt: function (i) {
    if (i < 0xfd) {
      // unsigned char
      return [i];
    } else if (i < 0x10000) {
      // unsigned short (LE)
      return [0xfd, i & 255, i >>> 8];    // little endian!
    } else if (i < 0x100000000) {
      // unsigned int (LE)
      return [0xfe].concat(Crypto.util.wordsToBytes([i]).reverse());  // little endian!
    } else {
      throw "long long not implemented";
      // unsigned long long (LE)
      //return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i]).reverse());
    }
  },

  hexToBytes: function(hex) {
    for (var bytes = [], c = 0; c < hex.length; c += 2) {
      var byte = parseInt(hex.substr(c, 2), 16);
      if (isNaN(byte)) {
        throw 'illegal input';
      }
      bytes.push(byte);
    }
    return bytes;
  },

  bytesToHex: function (bytes) {
    for (var hex = [], i = 0; i < bytes.length; i++) {
      if (bytes[i] > 0xff) {
        throw 'illegal input';
      }
      hex.push((bytes[i] >>> 4).toString(16));
      hex.push((bytes[i] & 0xF).toString(16));
    }
    return hex.join("");
  },

  /**
   * Parse a Bitcoin value byte array, returning a BigInteger.
   */
  valueToBigInt: function (valueBuffer)
  {
    if (valueBuffer instanceof BigInteger) return valueBuffer;

    // Prepend zero byte to prevent interpretation as negative integer
    return BigInteger.fromByteArrayUnsigned(valueBuffer);
  },

  /**
   * Calculate RIPEMD160(SHA256(data)).
   *
   * Takes an arbitrary byte array as inputs and returns the hash as a byte
   * array.
   */
  sha256ripe160: function (data) {
    return Crypto.RIPEMD160(Crypto.SHA256(data, {asBytes: true}), {asBytes: true});
  },

  /**
   * Calculate SHA256(SHA256(data)).
   *
   * Takes an arbitrary byte array as inputs and returns the doubly hashed
   * data as a byte array.
   */
  dsha256: function (data) {
    return Crypto.SHA256(Crypto.SHA256(data, { asBytes: true }), { asBytes: true });
  }
};
<|endoftext|>


<commit_before>dc.bubbleChart = function(parent, chartGroup) {
    var NODE_CLASS = "node";
    var BUBBLE_CLASS = "bubble";
    var MIN_RADIUS = 10;

    var _chart = dc.singleSelectionChart(dc.colorChart(dc.coordinateGridChart({})));

    _chart.renderLabel(true);
    _chart.renderTitle(false);

    var _r = d3.scale.linear().domain([0, 100]);
    var _rValueAccessor = function(d) {
        return d.r;
    };

    _chart.transitionDuration(750);

    var bubbleLocator = function(d) {
        return "translate(" + (bubbleX(d)) + "," + (bubbleY(d)) + ")";
    };

    _chart.plotData = function() {
         _r.range([0, _chart.xAxisLength() / 3]);

        var bubbleG = _chart.g().selectAll("g." + NODE_CLASS)
            .data(_chart.group().all());

        renderNodes(bubbleG);

        updateNodes(bubbleG);

        removeNodes(bubbleG);

        _chart.fadeDeselectedArea();
    };

    function renderNodes(bubbleG) {
        var bubbleGEnter = bubbleG.enter().append("g");
        bubbleGEnter
            .attr("class", NODE_CLASS)
            .attr("transform", bubbleLocator)
            .append("circle").attr("class", function(d, i) {
                return BUBBLE_CLASS + " " + i;
            })
            .on("click", onClick)
            .attr("fill", function(d, i) {
                return _chart.colors()(i);
            })
            .attr("r", 0);
        dc.transition(bubbleG, _chart.transitionDuration())
            .attr("r", function(d) {
                return bubbleR(d);
            });

        renderLabel(bubbleGEnter);

        renderTitles(bubbleGEnter);
    }

    var labelFunction = function(d) {
        return bubbleR(d) > MIN_RADIUS ? _chart.label()(d) : "";
    };

    function renderLabel(bubbleGEnter) {
        if (_chart.renderLabel()) {

            bubbleGEnter.append("text")
                .attr("text-anchor", "middle")
                .attr("dy", ".3em")
                .on("click", onClick)
                .text(labelFunction);
        }
    }

    function updateLabels(bubbleGEnter) {
        if (_chart.renderLabel()) {
            bubbleGEnter.selectAll("text")
                .text(labelFunction);
        }
    }

    var titleFunction = function(d) {
        return _chart.title()(d);
    };

    function renderTitles(g) {
        if (_chart.renderTitle()) {
            g.append("title").text(titleFunction);
        }
    }

    function updateTitles(g) {
        if (_chart.renderTitle()) {
            g.selectAll("title").text(titleFunction);
        }
    }

    function updateNodes(bubbleG) {
        dc.transition(bubbleG, _chart.transitionDuration())
            .attr("transform", bubbleLocator)
            .selectAll("circle." + BUBBLE_CLASS)
            .attr("r", function(d) {
                return bubbleR(d);
            });
        updateLabels(bubbleG);
        updateTitles(bubbleG);
    }

    function removeNodes(bubbleG) {
        dc.transition(bubbleG.exit().selectAll("circle." + BUBBLE_CLASS), _chart.transitionDuration())
            .attr("r", 0)
            .remove();
    }

    var onClick = function(d) {
        _chart.filter(d.key);
        dc.redrawAll(_chart.chartGroup());
    };

    function bubbleX(d) {
        return _chart.x()(_chart.keyAccessor()(d)) + _chart.margins().left;
    }

    function bubbleY(d) {
        return _chart.margins().top + _chart.y()(_chart.valueAccessor()(d));
    }

    function bubbleR(d) {
        return _chart.r()(_chart.radiusValueAccessor()(d));
    }

    _chart.renderBrush = function(g) {
        // override default x axis brush from parent chart
    };

    _chart.redrawBrush = function(g) {
        // override default x axis brush from parent chart
        _chart.fadeDeselectedArea();
    };

    _chart.fadeDeselectedArea = function() {
        var normalOpacity = 1;
        var fadeOpacity = 0.1;
        if (_chart.hasFilter()) {
            _chart.selectAll("g." + NODE_CLASS).select("circle").each(function(d) {
                if (_chart.isSelectedSlice(d)) {
                    _chart.highlightSelected(this);
                } else {
                    _chart.fadeDeselected(this);
                }
            });
        } else {
            _chart.selectAll("g." + NODE_CLASS).selectAll("circle").each(function(d) {
                _chart.resetHighlight(this);
            });
        }
    };

    _chart.isSelectedSlice = function(d) {
        return _chart.filter() == d.key;
    };

    _chart.r = function(_) {
        if (!arguments.length) return _r;
        _r = _;
        return _chart;
    };

    _chart.radiusValueAccessor = function(_) {
        if (!arguments.length) return _rValueAccessor;
        _rValueAccessor = _;
        return _chart;
    };

    return _chart.anchor(parent, chartGroup);
};
<commit_msg>[issue #18] fix bubble g on exit only removing circle issue<commit_after>dc.bubbleChart = function(parent, chartGroup) {
    var NODE_CLASS = "node";
    var BUBBLE_CLASS = "bubble";
    var MIN_RADIUS = 10;

    var _chart = dc.singleSelectionChart(dc.colorChart(dc.coordinateGridChart({})));

    _chart.renderLabel(true);
    _chart.renderTitle(false);

    var _r = d3.scale.linear().domain([0, 100]);
    var _rValueAccessor = function(d) {
        return d.r;
    };

    _chart.transitionDuration(750);

    var bubbleLocator = function(d) {
        return "translate(" + (bubbleX(d)) + "," + (bubbleY(d)) + ")";
    };

    _chart.plotData = function() {
        _r.range([0, _chart.xAxisLength() / 3]);

        var bubbleG = _chart.g().selectAll("g." + NODE_CLASS)
            .data(_chart.group().all());

        renderNodes(bubbleG);

        updateNodes(bubbleG);

        removeNodes(bubbleG);

        _chart.fadeDeselectedArea();
    };

    function renderNodes(bubbleG) {
        var bubbleGEnter = bubbleG.enter().append("g");
        bubbleGEnter
            .attr("class", NODE_CLASS)
            .attr("transform", bubbleLocator)
            .append("circle").attr("class", function(d, i) {
                return BUBBLE_CLASS + " " + i;
            })
            .on("click", onClick)
            .attr("fill", function(d, i) {
                return _chart.colors()(i);
            })
            .attr("r", 0);
        dc.transition(bubbleG, _chart.transitionDuration())
            .attr("r", function(d) {
                return bubbleR(d);
            });

        renderLabel(bubbleGEnter);

        renderTitles(bubbleGEnter);
    }

    var labelFunction = function(d) {
        return bubbleR(d) > MIN_RADIUS ? _chart.label()(d) : "";
    };

    function renderLabel(bubbleGEnter) {
        if (_chart.renderLabel()) {

            bubbleGEnter.append("text")
                .attr("text-anchor", "middle")
                .attr("dy", ".3em")
                .on("click", onClick)
                .text(labelFunction);
        }
    }

    function updateLabels(bubbleGEnter) {
        if (_chart.renderLabel()) {
            bubbleGEnter.selectAll("text")
                .text(labelFunction);
        }
    }

    var titleFunction = function(d) {
        return _chart.title()(d);
    };

    function renderTitles(g) {
        if (_chart.renderTitle()) {
            g.append("title").text(titleFunction);
        }
    }

    function updateTitles(g) {
        if (_chart.renderTitle()) {
            g.selectAll("title").text(titleFunction);
        }
    }

    function updateNodes(bubbleG) {
        dc.transition(bubbleG, _chart.transitionDuration())
            .attr("transform", bubbleLocator)
            .selectAll("circle." + BUBBLE_CLASS)
            .attr("r", function(d) {
                return bubbleR(d);
            });
        updateLabels(bubbleG);
        updateTitles(bubbleG);
    }

    function removeNodes(bubbleG) {
        bubbleG.exit().remove();
    }

    var onClick = function(d) {
        _chart.filter(d.key);
        dc.redrawAll(_chart.chartGroup());
    };

    function bubbleX(d) {
        return _chart.x()(_chart.keyAccessor()(d)) + _chart.margins().left;
    }

    function bubbleY(d) {
        return _chart.margins().top + _chart.y()(_chart.valueAccessor()(d));
    }

    function bubbleR(d) {
        return _chart.r()(_chart.radiusValueAccessor()(d));
    }

    _chart.renderBrush = function(g) {
        // override default x axis brush from parent chart
    };

    _chart.redrawBrush = function(g) {
        // override default x axis brush from parent chart
        _chart.fadeDeselectedArea();
    };

    _chart.fadeDeselectedArea = function() {
        var normalOpacity = 1;
        var fadeOpacity = 0.1;
        if (_chart.hasFilter()) {
            _chart.selectAll("g." + NODE_CLASS).select("circle").each(function(d) {
                if (_chart.isSelectedSlice(d)) {
                    _chart.highlightSelected(this);
                } else {
                    _chart.fadeDeselected(this);
                }
            });
        } else {
            _chart.selectAll("g." + NODE_CLASS).selectAll("circle").each(function(d) {
                _chart.resetHighlight(this);
            });
        }
    };

    _chart.isSelectedSlice = function(d) {
        return _chart.filter() == d.key;
    };

    _chart.r = function(_) {
        if (!arguments.length) return _r;
        _r = _;
        return _chart;
    };

    _chart.radiusValueAccessor = function(_) {
        if (!arguments.length) return _rValueAccessor;
        _rValueAccessor = _;
        return _chart;
    };

    return _chart.anchor(parent, chartGroup);
};
<|endoftext|>


<commit_before>"use strict";
(function(window) {
    var config = {
      silent: false
    }
    var directives = {};

    /**
    * Converts attributes into key-value pairs
    * @param {Node} node
    * @return {Object} Key-Value pairs of Attributes
    */
    var extractAttrs = function(node) {
      var attrs = {};
      if(!node.attributes) return attrs;
      var rawAttrs = node.attributes;
      for(var i = 0; i < rawAttrs.length; i++) {
        attrs[rawAttrs[i].name] = rawAttrs[i].value
      }

      return attrs;
    }

    /**
    * Compiles a template with given data
    * @param {String} template
    * @param {Object} data
    * @return {String} Template with data rendered
    */
    var compileTemplate = function(template, data) {
      var code = template,
          re = /{{([A-Za-z0-9_.\[\]]+)}}/gi;
      code.replace(re, function(match, p) {
        code = code.replace(match, "` + data." + p + " + `");
      });
      var compile = new Function("data", "var out = `" + code + "`; return out");
      return compile(data);
    }

    function Moon(opts) {
        var _el = opts.el;
        var _data = opts.data;
        var _methods = opts.methods;
        var self = this;
        this.$el = document.querySelector(_el);
        this.components = opts.components;
        this.dom = {type: this.$el.nodeName, children: [], node: this.$el};

        // Change state when $data is changed
        Object.defineProperty(this, '$data', {
            get: function() {
                return _data;
            },
            set: function(value) {
                _data = value;
                this.build(this.dom.children);
            }
        });

        /**
        * Logs a Message
        * @param {String} msg
        */
        this.log = function(msg) {
          if(!config.silent) console.log(msg);
        }

        /**
        * Throws an Error
        * @param {String} msg
        */
        this.error = function(msg) {
          console.log("Moon ERR: " + msg);
        }

        /**
        * Creates an object to be used in a Virtual DOM
        * @param {String} type
        * @param {Array} children
        * @param {String} val
        * @param {Object} props
        * @param {Node} node
        * @return {Object} Object usable in Virtual DOM
        */
        this.createElement = function(type, children, val, props, node) {
          return {type: type, children: children, val: val, props: props, node: node};
        }

        /**
        * Create Elements Recursively For all Children
        * @param {Array} children
        * @return {Array} Array of elements usable in Virtual DOM
        */
        this.recursiveChildren = function(children) {
          var recursiveChildrenArr = [];
          for(var i = 0; i < children.length; i++) {
            var child = children[i];
            recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
          }
          return recursiveChildrenArr;
        }

        /**
        * Creates Virtual DOM
        * @param {Node} node
        */
        this.createVirtualDOM = function(node) {
          var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
          this.dom = vdom;
        }

        /**
        * Turns Custom Components into their Corresponding Templates
        */
        this.componentsToHTML = function() {
          for(var component in this.components) {
            var componentsFound = document.getElementsByTagName(component);
            componentsFound = Array.prototype.slice.call(componentsFound);
            for(var i = 0; i < componentsFound.length; i++) {
              var componentFound = componentsFound[i];
              var componentProps = extractAttrs(componentFound);
              var componentDummy = document.createElement('div');
              componentDummy.innerHTML = this.components[component].template;
              componentDummy = componentDummy.firstChild;

              for(var attr in componentProps) {
                componentDummy.setAttribute(attr, componentProps[attr]);
              }

              componentFound.outerHTML = componentDummy.outerHTML;
            }
          }
        }

        /**
        * Sets Value in Data
        * @param {String} key
        * @param {String} val
        */
        this.set = function(key, val) {
          this.$data[key] = val;
          this.build(this.dom.children);
        }

        /**
        * Gets Value in Data
        * @param {String} key
        * @return {String} Value of key in data
        */
        this.get = function(key) {
          return this.$data[key];
        }

        /**
        * Makes an AJAX Request
        * @param {String} method
        * @param {String} url
        * @param {Object} params
        * @param {Function} cb
        */
        this.ajax = function(method, url, params, cb) {
          var xmlHttp = new XMLHttpRequest();
          method = method.toUpperCase();
          if(typeof params === "function") {
            cb = params;
          }
          var urlParams = "?";
          if(method === "POST") {
            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            for(var param in params) {
              urlParams += param + "=" + params[param] + "&";
            }
          }
          xmlHttp.onreadystatechange = function() {
          if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            cb(JSON.parse(xmlHttp.responseText));
          }
          xmlHttp.open(method, url, true);
          xmlHttp.send(method === "POST" ? urlParams : null);
        }

        /**
        * Calls a method
        * @param {String} method
        */
        this.method = function(method) {
          _methods[method]();
        }

        // Default Directives
        directives["m-if"] = function(el, val, vdom) {
          var evaluated = new Function("return " + val);
          if(!evaluated()) {
            el.textContent = "";
          } else {
            el.textContent = compileTemplate(vdom.val, self.$data);
          }
        }

        directives["m-on"] = function(el, val, vdom) {
          var splitVal = val.split(":");
          var eventToCall = splitVal[0];
          var methodToCall = splitVal[1];
          el.addEventListener(eventToCall, function() {
            self.method(methodToCall);
          });
          el.removeAttribute("m-on");
          delete vdom.props["m-on"];
        }

        directives["m-model"] = function(el, val, vdom) {
          el.value = self.get(val);
          el.addEventListener("input", function() {
            self.set(val, el.value);
          });
          el.removeAttribute("m-model");
          delete vdom.props["m-model"];
        }

        directives["m-once"] = function(el, val, vdom) {
          vdom.val = el.textContent;
          for(var child in vdom.children) {
            vdom.children[child].val = compileTemplate(vdom.children[child].val, self.$data);
          }
        }

        // directives["m-for"] = function(el, val, vdom) {
        //   var splitVal = val.split(" in ");
        //   var alias = splitVal[0];
        //   var arr = self.get(splitVal[1]);
        //   var clone = el.cloneNode(true);
        //   var oldVal = vdom.val;
        //   var compilable = vdom.val.replace(new RegExp(alias, "gi"), splitVal[1] + '[0]');
        //   vdom.val = compileTemplate(compilable, self.$data);
        //   el.innerHTML = vdom.val;
        //   for(var i = 1; i < arr.length; i++) {
        //     var newClone = clone.cloneNode(true);
        //     var compilable = oldVal.replace(new RegExp(alias, "gi"), splitVal[1] + '[' + i + ']');
        //     newClone.innerHTML = compileTemplate(compilable, self.$data);
        //     var parent = el.parentNode;
        //     parent.appendChild(newClone);
        //   }
        //   vdom.val = el.textContent;
        //   delete vdom.props["m-for"];
        // }

        /**
        * Builds the DOM With Data
        * @param {Array} children
        */
        this.build = function(children) {
          for(var i = 0; i < children.length; i++) {
            var el = children[i];

            if(el.type === "#text") {
              el.node.textContent = compileTemplate(el.val, this.$data);
            } else if(el.props) {
              for(var prop in el.props) {
                var propVal = el.props[prop];
                var compiledProperty = compileTemplate(propVal, this.$data);
                var directive = directives[prop];
                if(directive) {
                  directive(el.node, compiledProperty, el);
                }

                el.node.setAttribute(prop, compiledProperty);
              }
            }

            this.build(el.children);
          }
        }

        /**
        * Initializes Moon
        */
        this.init = function() {
          this.log("======= Moon =======");
          this.componentsToHTML();
          this.createVirtualDOM(this.$el);
          this.build(this.dom.children);
        }

        // Initialize 🎉
        this.init();
    }

    /**
    * Sets the Configuration of Moon
    * @param {Object} opts
    */
    Moon.config = function(opts) {
      if(opts.silent) {
        config.silent = opts.silent;
      }
    }

    /**
    * Runs an external Plugin
    * @param {Object} plugin
    */
    Moon.use = function(plugin) {
      plugin.init(Moon);
    }

    /**
    * Creates a Directive
    * @param {String} name
    * @param {Function} action
    */
    Moon.directive = function(name, action) {
      directives["m-" + name] = action;
    }

    window.Moon = Moon;
    window.$ = function(el) {
      el = document.querySelectorAll(el);
      return el.length === 1 ? el[0] : el;
    }

})(window);
<commit_msg>get root element utility<commit_after>"use strict";
(function(window) {
    var config = {
      silent: false
    }
    var directives = {};

    /**
    * Converts attributes into key-value pairs
    * @param {Node} node
    * @return {Object} Key-Value pairs of Attributes
    */
    var extractAttrs = function(node) {
      var attrs = {};
      if(!node.attributes) return attrs;
      var rawAttrs = node.attributes;
      for(var i = 0; i < rawAttrs.length; i++) {
        attrs[rawAttrs[i].name] = rawAttrs[i].value
      }

      return attrs;
    }

    /**
    * Compiles a template with given data
    * @param {String} template
    * @param {Object} data
    * @return {String} Template with data rendered
    */
    var compileTemplate = function(template, data) {
      var code = template,
          re = /{{([A-Za-z0-9_.\[\]]+)}}/gi;
      code.replace(re, function(match, p) {
        code = code.replace(match, "` + data." + p + " + `");
      });
      var compile = new Function("data", "var out = `" + code + "`; return out");
      return compile(data);
    }

    var getRootElement = function(el) {

    }

    function Moon(opts) {
        var _el = opts.el;
        var _data = opts.data;
        var _methods = opts.methods;
        var self = this;
        this.$el = document.querySelector(_el);
        this.components = opts.components;
        this.dom = {type: this.$el.nodeName, children: [], node: this.$el};

        // Change state when $data is changed
        Object.defineProperty(this, '$data', {
            get: function() {
                return _data;
            },
            set: function(value) {
                _data = value;
                this.build(this.dom.children);
            }
        });

        /**
        * Logs a Message
        * @param {String} msg
        */
        this.log = function(msg) {
          if(!config.silent) console.log(msg);
        }

        /**
        * Throws an Error
        * @param {String} msg
        */
        this.error = function(msg) {
          console.log("Moon ERR: " + msg);
        }

        /**
        * Creates an object to be used in a Virtual DOM
        * @param {String} type
        * @param {Array} children
        * @param {String} val
        * @param {Object} props
        * @param {Node} node
        * @return {Object} Object usable in Virtual DOM
        */
        this.createElement = function(type, children, val, props, node) {
          return {type: type, children: children, val: val, props: props, node: node};
        }

        /**
        * Create Elements Recursively For all Children
        * @param {Array} children
        * @return {Array} Array of elements usable in Virtual DOM
        */
        this.recursiveChildren = function(children) {
          var recursiveChildrenArr = [];
          for(var i = 0; i < children.length; i++) {
            var child = children[i];
            recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
          }
          return recursiveChildrenArr;
        }

        /**
        * Creates Virtual DOM
        * @param {Node} node
        */
        this.createVirtualDOM = function(node) {
          var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
          this.dom = vdom;
        }

        /**
        * Turns Custom Components into their Corresponding Templates
        */
        this.componentsToHTML = function() {
          for(var component in this.components) {
            var componentsFound = document.getElementsByTagName(component);
            componentsFound = Array.prototype.slice.call(componentsFound);
            for(var i = 0; i < componentsFound.length; i++) {
              var componentFound = componentsFound[i];
              var componentProps = extractAttrs(componentFound);
              var componentDummy = document.createElement('div');
              componentDummy.innerHTML = this.components[component].template;
              componentDummy = componentDummy.firstChild;

              for(var attr in componentProps) {
                componentDummy.setAttribute(attr, componentProps[attr]);
              }

              componentFound.outerHTML = componentDummy.outerHTML;
            }
          }
        }

        /**
        * Sets Value in Data
        * @param {String} key
        * @param {String} val
        */
        this.set = function(key, val) {
          this.$data[key] = val;
          this.build(this.dom.children);
        }

        /**
        * Gets Value in Data
        * @param {String} key
        * @return {String} Value of key in data
        */
        this.get = function(key) {
          return this.$data[key];
        }

        /**
        * Makes an AJAX Request
        * @param {String} method
        * @param {String} url
        * @param {Object} params
        * @param {Function} cb
        */
        this.ajax = function(method, url, params, cb) {
          var xmlHttp = new XMLHttpRequest();
          method = method.toUpperCase();
          if(typeof params === "function") {
            cb = params;
          }
          var urlParams = "?";
          if(method === "POST") {
            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            for(var param in params) {
              urlParams += param + "=" + params[param] + "&";
            }
          }
          xmlHttp.onreadystatechange = function() {
          if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            cb(JSON.parse(xmlHttp.responseText));
          }
          xmlHttp.open(method, url, true);
          xmlHttp.send(method === "POST" ? urlParams : null);
        }

        /**
        * Calls a method
        * @param {String} method
        */
        this.method = function(method) {
          _methods[method]();
        }

        // Default Directives
        directives["m-if"] = function(el, val, vdom) {
          var evaluated = new Function("return " + val);
          if(!evaluated()) {
            el.textContent = "";
          } else {
            el.textContent = compileTemplate(vdom.val, self.$data);
          }
        }

        directives["m-on"] = function(el, val, vdom) {
          var splitVal = val.split(":");
          var eventToCall = splitVal[0];
          var methodToCall = splitVal[1];
          el.addEventListener(eventToCall, function() {
            self.method(methodToCall);
          });
          el.removeAttribute("m-on");
          delete vdom.props["m-on"];
        }

        directives["m-model"] = function(el, val, vdom) {
          el.value = self.get(val);
          el.addEventListener("input", function() {
            self.set(val, el.value);
          });
          el.removeAttribute("m-model");
          delete vdom.props["m-model"];
        }

        directives["m-once"] = function(el, val, vdom) {
          vdom.val = el.textContent;
          for(var child in vdom.children) {
            vdom.children[child].val = compileTemplate(vdom.children[child].val, self.$data);
          }
        }

        // directives["m-for"] = function(el, val, vdom) {
        //   var splitVal = val.split(" in ");
        //   var alias = splitVal[0];
        //   var arr = self.get(splitVal[1]);
        //   var clone = el.cloneNode(true);
        //   var oldVal = vdom.val;
        //   var compilable = vdom.val.replace(new RegExp(alias, "gi"), splitVal[1] + '[0]');
        //   vdom.val = compileTemplate(compilable, self.$data);
        //   el.innerHTML = vdom.val;
        //   for(var i = 1; i < arr.length; i++) {
        //     var newClone = clone.cloneNode(true);
        //     var compilable = oldVal.replace(new RegExp(alias, "gi"), splitVal[1] + '[' + i + ']');
        //     newClone.innerHTML = compileTemplate(compilable, self.$data);
        //     var parent = el.parentNode;
        //     parent.appendChild(newClone);
        //   }
        //   vdom.val = el.textContent;
        //   delete vdom.props["m-for"];
        // }

        /**
        * Builds the DOM With Data
        * @param {Array} children
        */
        this.build = function(children) {
          for(var i = 0; i < children.length; i++) {
            var el = children[i];

            if(el.type === "#text") {
              el.node.textContent = compileTemplate(el.val, this.$data);
            } else if(el.props) {
              for(var prop in el.props) {
                var propVal = el.props[prop];
                var compiledProperty = compileTemplate(propVal, this.$data);
                var directive = directives[prop];
                if(directive) {
                  directive(el.node, compiledProperty, el);
                }

                el.node.setAttribute(prop, compiledProperty);
              }
            }

            this.build(el.children);
          }
        }

        /**
        * Initializes Moon
        */
        this.init = function() {
          this.log("======= Moon =======");
          this.componentsToHTML();
          this.createVirtualDOM(this.$el);
          this.build(this.dom.children);
        }

        // Initialize 🎉
        this.init();
    }

    /**
    * Sets the Configuration of Moon
    * @param {Object} opts
    */
    Moon.config = function(opts) {
      if(opts.silent) {
        config.silent = opts.silent;
      }
    }

    /**
    * Runs an external Plugin
    * @param {Object} plugin
    */
    Moon.use = function(plugin) {
      plugin.init(Moon);
    }

    /**
    * Creates a Directive
    * @param {String} name
    * @param {Function} action
    */
    Moon.directive = function(name, action) {
      directives["m-" + name] = action;
    }

    window.Moon = Moon;
    window.$ = function(el) {
      el = document.querySelectorAll(el);
      return el.length === 1 ? el[0] : el;
    }

})(window);
<|endoftext|>


<commit_before>'use strict';
/* ============================================================ *\
	 IMAGES
\* ============================================================ */

// Gulp dependencies
var path = require('path');
var gulpif     = require('gulp-if')
var rename     = require('gulp-rename');

// Module dependencies
var imagemin 		= 		require('gulp-imagemin');
var pngquant 		= 		require('imagemin-pngquant');
var svgmin 			= 		require('gulp-svgmin');
var responsive 	= 		require('gulp-responsive');
var helpers = require('./helpers');

module.exports = function(gulp, projectConfig, tasks) {

	/* --------------------
	*	CONFIGURATION
	* ---------------------*/

	var TASK_NAME = 'images';

	// Task Config
	var taskConfig = require(path.resolve(process.cwd(), projectConfig.dirs.config, 'task.' + TASK_NAME + '.js'))(projectConfig);

	var imageminOptions = {
		progressive: true,
		svgoPlugins: [{removeViewBox: false}],
		use: [pngquant()]
	};

	var svgPlugins = [{
			removeDimensions: true
		}, {
			removeTitle: true
		}
	];

	var svgminOptions = {};

	/* --------------------
	*	MODULE TASKS
	* ---------------------*/

	gulp.task('imagemin', function () {
		return gulp.src(taskConfig.images)
			.pipe(gulpif(projectConfig.prod, imagemin(imageminOptions))) //Production only
			.pipe(gulp.dest(projectConfig.paths.dest.images));
	});

	gulp.task('svgmin', function () {
		return gulp.src(taskConfig.svgs)
			.pipe(svgmin(svgminOptions))
			.pipe(gulp.dest(projectConfig.paths.dest.images));
	});

	gulp.task('responsive-images', function () {
		return gulp.src(taskConfig.responsiveImages.src)
			.pipe(responsive(helpers.getImageSizes(taskConfig.responsiveImages.config)))
			.pipe(gulp.dest(projectConfig.paths.dest.images));
	});

	gulp.task(TASK_NAME, ['responsive-images', 'imagemin', 'svgmin']);

	/* --------------------
	*	WATCH TASKS
	* ---------------------*/

	gulp.task('watch:' + TASK_NAME, function () {
		gulp.watch(
			taskConfig.watch,
			[TASK_NAME]
		);
	});

	/* ----------------------------
	*	CARTRIDGE TASK MANAGEMENT
	* -----------------------------*/

	// Add the clean path for the generated styles
	projectConfig.cleanPaths.push(projectConfig.paths.dest[TASK_NAME]);
	// Add the task to the default list
	tasks.default.push(TASK_NAME);
	// Add the task to the watch list
	tasks.watch.push('watch:' + TASK_NAME);
}
<commit_msg>refactor: optimise images before generating responsive images<commit_after>'use strict';
/* ============================================================ *\
	 IMAGES
\* ============================================================ */

// Gulp dependencies
var path = require('path');
var gulpif     = require('gulp-if')
var rename     = require('gulp-rename');

// Module dependencies
var imagemin 		= 		require('gulp-imagemin');
var pngquant 		= 		require('imagemin-pngquant');
var svgmin 			= 		require('gulp-svgmin');
var responsive 	= 		require('gulp-responsive');
var helpers = require('./helpers');

module.exports = function(gulp, projectConfig, tasks) {

	/* --------------------
	*	CONFIGURATION
	* ---------------------*/

	var TASK_NAME = 'images';

	// Task Config
	var taskConfig = require(path.resolve(process.cwd(), projectConfig.dirs.config, 'task.' + TASK_NAME + '.js'))(projectConfig);

	var imageminOptions = {
		progressive: true,
		svgoPlugins: [{removeViewBox: false}],
		use: [pngquant()]
	};

	var svgPlugins = [{
			removeDimensions: true
		}, {
			removeTitle: true
		}
	];

	var svgminOptions = {};

	/* --------------------
	*	MODULE TASKS
	* ---------------------*/

	gulp.task('imagemin', function () {
		return gulp.src(taskConfig.images)
			.pipe(gulpif(projectConfig.prod, imagemin(imageminOptions))) //Production only
			.pipe(gulp.dest(projectConfig.paths.dest.images));
	});

	gulp.task('svgmin', function () {
		return gulp.src(taskConfig.svgs)
			.pipe(svgmin(svgminOptions))
			.pipe(gulp.dest(projectConfig.paths.dest.images));
	});

	gulp.task('responsive-images', function () {
		return gulp.src(taskConfig.responsiveImages.src)
			.pipe(responsive(helpers.getImageSizes(taskConfig.responsiveImages.config)))
			.pipe(gulp.dest(projectConfig.paths.dest.images));
	});

	gulp.task(TASK_NAME, ['imagemin', 'responsive-images', 'svgmin']);

	/* --------------------
	*	WATCH TASKS
	* ---------------------*/

	gulp.task('watch:' + TASK_NAME, function () {
		gulp.watch(
			taskConfig.watch,
			[TASK_NAME]
		);
	});

	/* ----------------------------
	*	CARTRIDGE TASK MANAGEMENT
	* -----------------------------*/

	// Add the clean path for the generated styles
	projectConfig.cleanPaths.push(projectConfig.paths.dest[TASK_NAME]);
	// Add the task to the default list
	tasks.default.push(TASK_NAME);
	// Add the task to the watch list
	tasks.watch.push('watch:' + TASK_NAME);
}
<|endoftext|>


<commit_before>define(function () {
    function _forEach(func) {
        var l = this.length || 0, i = 0, rtn = null, prop = null;
        if (this.length !== undefined) {
            for(;i<l;i++) {
                rtn = func(i, this[i]);
                if (rtn === false) { // Break out on false
                    break;
                }
            }
        } else { // Object
            for(prop in this) {
                if (this.hasOwnProperty(prop)) {
                    rtn = func(i, this[prop]);
                    if (rtn === false) { // Break out on false
                        break;
                    }
                }
                i++;
            }
        }
        return this;
    }

    function extend() {
        var target = arguments[0], obj = null, i=1, k;
        for(; i<arguments.length; i++) {
            obj = arguments[i];
            for(k in obj) {
                if (obj.hasOwnProperty(k) && obj[k] !== null && obj[k] !== undefined) {
                    target[k] = obj[k];
                }
            }
        }
        return target;
    }

    function trim(txt) {
        var trimLeft = /^[\s\xA0]+/,
            trimRight = /[\s\xA0]+$/;
        return txt == null ?
            "" :
            txt.trim ?
                txt.trim() :
                txt.toString().replace(trimLeft, "").replace(trimRight, "");
    }

    function makeArray(obj) {
        // .slice.call() makes an array from array-like object
        return [].slice.call(obj);
    }

    // HTML "templating"
    function innerHTML(template) {
        var div = document.createElement("div");
        div.innerHTML = template;
        return makeArray(div.childNodes);
    }

    var fn = {
            each: _forEach,

            map: function (callback) {
                var mapped = [];
                this.each(function (i, el) {
                    mapped = mapped.concat(callback(i, el));
                });
                return mjp(mapped);
            },

            filter: function (callback) {
                var filtered = [];
                this.each(function (i, el) {
                    callback(i, el) && filtered.push(el);
                });
                return mjp(filtered);
            },

            html: function (value) {
                if (typeof value === "string") {
                    this.each(function (i, el) {
                        el.innerHTML = value;
                    });
                } else {
                    return this.length ? this[0].innerHTML : "";
                }
            }
        },

        // Main
        mjp = function (sel, context) {
            var raw_nodes = [], nodes = [],
                root = context || document,
                sel_type = typeof sel;

            if (sel_type === "string") {
                if (sel.slice(0, 1) === "<") {
                    nodes = innerHTML(sel);
                } else if (sel.indexOf(",") > -1) { // Multiple selectors
                    // TODO: write test
                    sel = sel.split(",");
                    for(var i=0;i<sel.length;i++) {
                        nodes = nodes.concat(makeArray(
                                    root.querySelectorAll(trim(sel[i]))));
                    }
                } else {
                    raw_nodes = root.querySelectorAll(sel);
                }
            } else if (sel_type === "object") {
                if (sel.length !== undefined) {
                    if (Array.isArray(sel)) {
                        nodes = sel;
                    } else {
                        raw_nodes = sel;
                    }
                } else {
                    nodes = [sel];
                }
            }
            if (raw_nodes.length) {
                raw_nodes.forEach = _forEach;
                raw_nodes.forEach(function (i, node) {
                    nodes.push(node);
                });
            }
            // Add useful methods (TODO: create extend object method)
            extend(nodes, mjp.fn);
            return nodes;
        };

    mjp.extend = extend;

    mjp.extend(mjp, {
        fn: fn,
        trim: trim,
        isFunction: function (obj) { return typeof obj === "function"; },
        isArray: function (obj) { return Array.isArray(obj); },
        makeArray: makeArray
    });

    return mjp;
});
<commit_msg>Added version number to mjp object<commit_after>define(function () {
    function _forEach(func) {
        var l = this.length || 0, i = 0, rtn = null, prop = null;
        if (this.length !== undefined) {
            for(;i<l;i++) {
                rtn = func(i, this[i]);
                if (rtn === false) { // Break out on false
                    break;
                }
            }
        } else { // Object
            for(prop in this) {
                if (this.hasOwnProperty(prop)) {
                    rtn = func(i, this[prop]);
                    if (rtn === false) { // Break out on false
                        break;
                    }
                }
                i++;
            }
        }
        return this;
    }

    function extend() {
        var target = arguments[0], obj = null, i=1, k;
        for(; i<arguments.length; i++) {
            obj = arguments[i];
            for(k in obj) {
                if (obj.hasOwnProperty(k) && obj[k] !== null && obj[k] !== undefined) {
                    target[k] = obj[k];
                }
            }
        }
        return target;
    }

    function trim(txt) {
        var trimLeft = /^[\s\xA0]+/,
            trimRight = /[\s\xA0]+$/;
        return txt == null ?
            "" :
            txt.trim ?
                txt.trim() :
                txt.toString().replace(trimLeft, "").replace(trimRight, "");
    }

    function makeArray(obj) {
        // .slice.call() makes an array from array-like object
        return [].slice.call(obj);
    }

    // HTML "templating"
    function innerHTML(template) {
        var div = document.createElement("div");
        div.innerHTML = template;
        return makeArray(div.childNodes);
    }

    var fn = {
            mjp: "v0.8.0",

            each: _forEach,

            map: function (callback) {
                var mapped = [];
                this.each(function (i, el) {
                    mapped = mapped.concat(callback(i, el));
                });
                return mjp(mapped);
            },

            filter: function (callback) {
                var filtered = [];
                this.each(function (i, el) {
                    callback(i, el) && filtered.push(el);
                });
                return mjp(filtered);
            },

            html: function (value) {
                if (typeof value === "string") {
                    this.each(function (i, el) {
                        el.innerHTML = value;
                    });
                } else {
                    return this.length ? this[0].innerHTML : "";
                }
            }
        },

        // Main
        mjp = function (sel, context) {
            var raw_nodes = [], nodes = [],
                root = context || document,
                sel_type = typeof sel;

            if (sel_type === "string") {
                if (sel.slice(0, 1) === "<") {
                    nodes = innerHTML(sel);
                } else if (sel.indexOf(",") > -1) { // Multiple selectors
                    // TODO: write test
                    sel = sel.split(",");
                    for(var i=0;i<sel.length;i++) {
                        nodes = nodes.concat(makeArray(
                                    root.querySelectorAll(trim(sel[i]))));
                    }
                } else {
                    raw_nodes = root.querySelectorAll(sel);
                }
            } else if (sel_type === "object") {
                if (sel.length !== undefined) {
                    if (Array.isArray(sel)) {
                        nodes = sel;
                    } else {
                        raw_nodes = sel;
                    }
                } else {
                    nodes = [sel];
                }
            }
            if (raw_nodes.length) {
                raw_nodes.forEach = _forEach;
                raw_nodes.forEach(function (i, node) {
                    nodes.push(node);
                });
            }
            // Add useful methods (TODO: create extend object method)
            extend(nodes, mjp.fn);
            return nodes;
        };

    mjp.extend = extend;

    mjp.extend(mjp, {
        fn: fn,
        trim: trim,
        isFunction: function (obj) { return typeof obj === "function"; },
        isArray: function (obj) { return Array.isArray(obj); },
        makeArray: makeArray
    });

    return mjp;
});
<|endoftext|>


<commit_before>/* eslint-disable camelcase */
const {exec} = require('child_process');
const path = require('path');
const url = require('url');
const crypto = require('crypto');
const {fs} = require('mz');
const git = require('simple-git/promise')();
const axios = require('axios');
const log = require('./logger');
const envs = require('./envs');

const env = process.env;

const INVALID_URI_CHARACTERS = /\//g;

if (!env.GITHUB_TOKEN && !env.GITLAB_TOKEN) throw new Error('GITHUB_TOKEN and/or GITLAB_TOKEN must be defined in environment. Create one at https://github.com/settings/tokens or https://gitlab.com/profile/personal_access_tokens');
if (!env.GITHUB_WEBHOOK_SECRET && !env.GITLAB_WEBHOOK_SECRET) throw new Error('GITHUB_WEBHOOK_SECRET and/or GITLAB_WEBHOOK_SECRET must be defined in environment. Create one at https://github.com/{OWNERNAME}/{REPONAME}/settings/hooks or https://gitlab.com/{OWNERNAME}/{REPONAME}/settings/integration (swap in the path to your repo)');
if (!env.ZEIT_API_TOKEN) throw new Error('ZEIT_API_TOKEN must be defined in environment. Create one at https://zeit.co/account/tokens');

const now = (cmd='') => {
  const nowBin = path.resolve('./node_modules/now/build/bin/now');
  return `${nowBin} ${cmd} --token ${env.ZEIT_API_TOKEN}`;
};

function stage(cwd, {alias}) {
  return new Promise((resolve, reject) => {
    let url, aliasError;
    const nowProc = exec(now(envs()), {cwd});
    nowProc.stderr.on('data', (error) => reject(new Error(error)));
    nowProc.stdout.on('data', (data) => {if (!url) url = data;});
    nowProc.stdout.on('close', () => {
      if (!url) return reject(new Error('Deployment failed'));
      log.info(`> Setting ${url} to alias ${alias}`);
      const aliasProc = exec(now(`alias set ${url} ${alias}`), {cwd});
      aliasProc.stderr.on('data', (error) => {aliasError = error;});
      aliasProc.on('close', () => {
        if (aliasError) return reject(new Error(aliasError));
        log.info(`> Alias ready ${alias}`);
        resolve(alias);
      });
    });
  });
}

async function sync(cloneUrl, localDirectory, {ref, checkout}) {
  try {
    await fs.stat(localDirectory);
  } catch (error) {
    log.info('> Cloning repository...');
    await git.clone(cloneUrl, localDirectory, ['--depth=1', `--branch=${ref}`]);
  }

  await git.cwd(localDirectory);
  log.info(`> Fetching ${ref}...`);
  await git.fetch('origin', ref);
  log.info(`> Checking out ${ref}@${checkout}...`);
  await git.checkout(checkout);
}

function UnsafeWebhookPayloadError(language) {
  const asJson = {
    error: {
      type: 'fatal',
      name: 'UNSAFE_WEBHOOK_PAYLOAD',
      message: `We could not cryptograhpically verify the payload sent to the stage-ci webhook from ${language.provider.name}. Make sure your ${language.provider.name} environment variable matches the Secret field in your ${language.provider.name} webhook config ${language.provider.webhookLocationInstructions}.`
    }
  };
  this.message = asJson.error.message;
  this.name = asJson.error.name;
  this.asJson = asJson;
}

function github({headers, body}) {
  // Don't log but give a very specific error. We don't want to fill the logs.
  if (!isGithubRequestCrypographicallySafe({headers, body, secret: env.GITHUB_WEBHOOK_SECRET}))
    throw new UnsafeWebhookPayloadError({
      provider: {
        name: 'Github',
        environmentVariable: 'GITHUB_WEBHOOK_SECRET',
        webhookLocationInstructions: 'at https://github.com/{OWNERNAME}/{REPONAME}/settings/hooks (swap in the path to your repo)'
      }
    });

  if (!['opened', 'synchronize'].includes(body.action)) return {success: false};

  const {repository, pull_request} = body;
  const {ref, sha} = pull_request.head;

  const githubApi = axios.create({
    headers: {
      'Authorization': `token ${env.GITHUB_TOKEN}`
    }
  });

  return {
    ref,
    sha,
    success: true,
    name: repository.full_name,
    alias: `https://${repository.name.replace(/[^A-Z0-9]/ig, '-')}-${ref.replace(INVALID_URI_CHARACTERS, '-')}.now.sh`,
    cloneUrl: url.format(Object.assign(
      url.parse(repository.clone_url),
      {auth: env.GITHUB_TOKEN}
    )),
    setStatus: (state, description, targetUrl) => {
      log.info(`> Setting GitHub status to "${state}"...`);
      return githubApi.post(pull_request.statuses_url, {
        state,
        description,
        target_url: targetUrl,
        context: 'ci/stage-ci'
      });
    }
  };
}

function gitlab({headers, body} = {}) {
  if (!isGitLabRequestSafe({headers}))
    throw new UnsafeWebhookPayloadError({
      provider: {
        name: 'Gitlab',
        environmentVariable: 'GITLAB_WEBHOOK_SECRET',
        webhookLocationInstructions: 'at https://gitlab.com/{OWNERNAME}/{REPONAME}/settings/integrations (swap in the path to your repo)'
      }
    });

  if (body.object_kind !== 'merge_request') return {success: false};
  if (!['opened', 'reopened'].includes(body.object_attributes.state)) return {success: false};

  const {object_attributes: {source, source_branch, last_commit: {id}, target, target_project_id}} = body;

  let {web_url} = source;
  web_url = url.parse(web_url);
  const statuses_url = `${web_url.protocol}//${web_url.hostname}/api/v4/projects/${target_project_id}/statuses/${id}`;

  const gitlabApi = axios.create({
    headers: {
      'PRIVATE-TOKEN': env.GITLAB_TOKEN
    }
  });

  return {
    ref: source_branch,
    sha: id,
    success: true,
    name: target.path_with_namespace,
    alias: `https://${source.name.replace(/[^A-Z0-9]/ig, '-')}-${source_branch.replace(INVALID_URI_CHARACTERS, '-')}.now.sh`,
    cloneUrl: url.format(Object.assign(
      url.parse(source.http_url),
      {auth: `gitlab-ci-token:${env.GITLAB_TOKEN}`}
    )),
    setStatus: (state, description, targetUrl) => {
      log.info(`> Setting GitLab status to "${state}"...`);
      return gitlabApi.post(statuses_url, {
        state,
        description,
        target_url: targetUrl,
        context: 'ci/stage-ci'
      });
    }
  };
}

function isGithubRequestCrypographicallySafe({headers, body, secret}) {
  const blob = JSON.stringify(body);
  const hmac = crypto.createHmac('sha1', secret);
  const ourSignature = `sha1=${hmac.update(blob).digest('hex')}`;
  const theirSignature = headers['x-hub-signature'];
  const bufferA = Buffer.from(ourSignature, 'utf8');
  const bufferB = Buffer.from(theirSignature, 'utf8');
  return crypto.timingSafeEqual(bufferA, bufferB);
}

function isGitLabRequestSafe({headers}) {
  return headers['x-gitlab-token'] === env.GITLAB_WEBHOOK_SECRET;
}

module.exports = {
  stage,
  sync,
  github,
  gitlab
};
<commit_msg>Replace env variables using object destructuring<commit_after>/* eslint-disable camelcase */
const {exec} = require('child_process');
const path = require('path');
const url = require('url');
const crypto = require('crypto');
const {fs} = require('mz');
const git = require('simple-git/promise')();
const axios = require('axios');
const log = require('./logger');
const envs = require('./envs');

const {
  GITHUB_TOKEN,
  GITHUB_WEBHOOK_SECRET,
  GITLAB_TOKEN,
  GITLAB_WEBHOOK_SECRET,
  ZEIT_API_TOKEN
} = process.env;

const INVALID_URI_CHARACTERS = /\//g;

if (!GITHUB_TOKEN && !GITLAB_TOKEN) throw new Error('GITHUB_TOKEN and/or GITLAB_TOKEN must be defined in environment. Create one at https://github.com/settings/tokens or https://gitlab.com/profile/personal_access_tokens');
if (!GITHUB_WEBHOOK_SECRET && !GITLAB_WEBHOOK_SECRET) throw new Error('GITHUB_WEBHOOK_SECRET and/or GITLAB_WEBHOOK_SECRET must be defined in environment. Create one at https://github.com/{OWNERNAME}/{REPONAME}/settings/hooks or https://gitlab.com/{OWNERNAME}/{REPONAME}/settings/integration (swap in the path to your repo)');
if (!ZEIT_API_TOKEN) throw new Error('ZEIT_API_TOKEN must be defined in environment. Create one at https://zeit.co/account/tokens');

const now = (cmd='') => {
  const nowBin = path.resolve('./node_modules/now/build/bin/now');
  return `${nowBin} ${cmd} --token ${ZEIT_API_TOKEN}`;
};

function stage(cwd, {alias}) {
  return new Promise((resolve, reject) => {
    let url, aliasError;
    const nowProc = exec(now(envs()), {cwd});
    nowProc.stderr.on('data', (error) => reject(new Error(error)));
    nowProc.stdout.on('data', (data) => {if (!url) url = data;});
    nowProc.stdout.on('close', () => {
      if (!url) return reject(new Error('Deployment failed'));
      log.info(`> Setting ${url} to alias ${alias}`);
      const aliasProc = exec(now(`alias set ${url} ${alias}`), {cwd});
      aliasProc.stderr.on('data', (error) => {aliasError = error;});
      aliasProc.on('close', () => {
        if (aliasError) return reject(new Error(aliasError));
        log.info(`> Alias ready ${alias}`);
        resolve(alias);
      });
    });
  });
}

async function sync(cloneUrl, localDirectory, {ref, checkout}) {
  try {
    await fs.stat(localDirectory);
  } catch (error) {
    log.info('> Cloning repository...');
    await git.clone(cloneUrl, localDirectory, ['--depth=1', `--branch=${ref}`]);
  }

  await git.cwd(localDirectory);
  log.info(`> Fetching ${ref}...`);
  await git.fetch('origin', ref);
  log.info(`> Checking out ${ref}@${checkout}...`);
  await git.checkout(checkout);
}

function UnsafeWebhookPayloadError(language) {
  const asJson = {
    error: {
      type: 'fatal',
      name: 'UNSAFE_WEBHOOK_PAYLOAD',
      message: `We could not cryptograhpically verify the payload sent to the stage-ci webhook from ${language.provider.name}. Make sure your ${language.provider.name} environment variable matches the Secret field in your ${language.provider.name} webhook config ${language.provider.webhookLocationInstructions}.`
    }
  };
  this.message = asJson.error.message;
  this.name = asJson.error.name;
  this.asJson = asJson;
}

function github({headers, body}) {
  // Don't log but give a very specific error. We don't want to fill the logs.
  if (!isGithubRequestCrypographicallySafe({headers, body, secret: GITHUB_WEBHOOK_SECRET}))
    throw new UnsafeWebhookPayloadError({
      provider: {
        name: 'Github',
        environmentVariable: 'GITHUB_WEBHOOK_SECRET',
        webhookLocationInstructions: 'at https://github.com/{OWNERNAME}/{REPONAME}/settings/hooks (swap in the path to your repo)'
      }
    });

  if (!['opened', 'synchronize'].includes(body.action)) return {success: false};

  const {repository, pull_request} = body;
  const {ref, sha} = pull_request.head;

  const githubApi = axios.create({
    headers: {
      'Authorization': `token ${GITHUB_TOKEN}`
    }
  });

  return {
    ref,
    sha,
    success: true,
    name: repository.full_name,
    alias: `https://${repository.name.replace(/[^A-Z0-9]/ig, '-')}-${ref.replace(INVALID_URI_CHARACTERS, '-')}.now.sh`,
    cloneUrl: url.format(Object.assign(
      url.parse(repository.clone_url),
      {auth: GITHUB_TOKEN}
    )),
    setStatus: (state, description, targetUrl) => {
      log.info(`> Setting GitHub status to "${state}"...`);
      return githubApi.post(pull_request.statuses_url, {
        state,
        description,
        target_url: targetUrl,
        context: 'ci/stage-ci'
      });
    }
  };
}

function gitlab({headers, body} = {}) {
  if (!isGitLabRequestSafe({headers}))
    throw new UnsafeWebhookPayloadError({
      provider: {
        name: 'Gitlab',
        environmentVariable: 'GITLAB_WEBHOOK_SECRET',
        webhookLocationInstructions: 'at https://gitlab.com/{OWNERNAME}/{REPONAME}/settings/integrations (swap in the path to your repo)'
      }
    });

  if (body.object_kind !== 'merge_request') return {success: false};
  if (!['opened', 'reopened'].includes(body.object_attributes.state)) return {success: false};

  const {object_attributes: {source, source_branch, last_commit: {id}, target, target_project_id}} = body;

  let {web_url} = source;
  web_url = url.parse(web_url);
  const statuses_url = `${web_url.protocol}//${web_url.hostname}/api/v4/projects/${target_project_id}/statuses/${id}`;

  const gitlabApi = axios.create({
    headers: {
      'PRIVATE-TOKEN': GITLAB_TOKEN
    }
  });

  return {
    ref: source_branch,
    sha: id,
    success: true,
    name: target.path_with_namespace,
    alias: `https://${source.name.replace(/[^A-Z0-9]/ig, '-')}-${source_branch.replace(INVALID_URI_CHARACTERS, '-')}.now.sh`,
    cloneUrl: url.format(Object.assign(
      url.parse(source.http_url),
      {auth: `gitlab-ci-token:${GITLAB_TOKEN}`}
    )),
    setStatus: (state, description, targetUrl) => {
      log.info(`> Setting GitLab status to "${state}"...`);
      return gitlabApi.post(statuses_url, {
        state,
        description,
        target_url: targetUrl,
        context: 'ci/stage-ci'
      });
    }
  };
}

function isGithubRequestCrypographicallySafe({headers, body, secret}) {
  const blob = JSON.stringify(body);
  const hmac = crypto.createHmac('sha1', secret);
  const ourSignature = `sha1=${hmac.update(blob).digest('hex')}`;
  const theirSignature = headers['x-hub-signature'];
  const bufferA = Buffer.from(ourSignature, 'utf8');
  const bufferB = Buffer.from(theirSignature, 'utf8');
  return crypto.timingSafeEqual(bufferA, bufferB);
}

function isGitLabRequestSafe({headers}) {
  return headers['x-gitlab-token'] === GITLAB_WEBHOOK_SECRET;
}

module.exports = {
  stage,
  sync,
  github,
  gitlab
};
<|endoftext|>


<commit_before>export { Core, ALL };
import EventEmitter from "../node_modules/event-e3/event-e3.js";

const ALL = Symbol();

const Core = class {
    constructor() {
        this.paused = false;
        this.moduleInstances = new Map();
        this.boundModuleEmit = this.moduleEmit.bind(this);
        EventEmitter(this);
    }

    register() {

    }

    start(module, { name = Symbol() } = {}) {
        if (this.moduleInstances.has(name)) {
            throw `module with name ${name} already started`;
        }

        const emitter = new EventEmitter();

        emitter.emit = this.boundModuleEmit;

        return Promise.resolve().then(() => {
            return module.start(emitter);
        }).then(instance => {
            this.moduleInstances.set(name, {
                module,
                instance,
                name,
                emitter,
            });
        }).then(() => {
            return name;
        });
    }

    stop(name) {
        const wrapper = this.moduleInstances.get(name);

        if (!wrapper) {
            return Promise.resolve(false);
        }

        wrapper.emitter.off();

        return Promise.resolve().then(() => {
            this.moduleInstances.delete(name);
            if (wrapper.module.stop) {
                wrapper.module.stop(wrapper.instance);
            }
        }).then(() => {
            return true;
        });
    }

    moduleEmit(name, data) {
        if (this.paused) {
            return;
        }
        this.moduleEmitDirect(name, data);
    }

    moduleEmitDirect(name, data) {
        this.emit(name, data);
        this.emit(ALL, { name, data, time: Date.now() });
        this.moduleInstances.forEach(({ emitter }) => {
            EventEmitter.prototype.emit.call(emitter, name, data);
        });
    }
};
<commit_msg>make core.start more consistent<commit_after>export { Core, ALL };
import EventEmitter from "../node_modules/event-e3/event-e3.js";

const ALL = Symbol();

const Core = class {
    constructor() {
        this.paused = false;
        this.moduleInstances = new Map();
        this.boundModuleEmit = this.moduleEmit.bind(this);
        EventEmitter(this);
    }

    register() {

    }

    start(module, { name = Symbol() } = {}) {
        if (this.moduleInstances.has(name)) {
            return Promise.reject(`module with name ${name} already started`);
        }

        const emitter = new EventEmitter();

        emitter.emit = this.boundModuleEmit;

        return Promise.resolve().then(() => {
            return module.start(emitter);
        }).then(instance => {
            this.moduleInstances.set(name, {
                module,
                instance,
                name,
                emitter,
            });
        }).then(() => {
            return name;
        });
    }

    stop(name) {
        const wrapper = this.moduleInstances.get(name);

        if (!wrapper) {
            return Promise.resolve(false);
        }

        wrapper.emitter.off();

        return Promise.resolve().then(() => {
            this.moduleInstances.delete(name);
            if (wrapper.module.stop) {
                wrapper.module.stop(wrapper.instance);
            }
        }).then(() => {
            return true;
        });
    }

    moduleEmit(name, data) {
        if (this.paused) {
            return;
        }
        this.moduleEmitDirect(name, data);
    }

    moduleEmitDirect(name, data) {
        this.emit(name, data);
        this.emit(ALL, { name, data, time: Date.now() });
        this.moduleInstances.forEach(({ emitter }) => {
            EventEmitter.prototype.emit.call(emitter, name, data);
        });
    }
};
<|endoftext|>


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

const p = () => new Promise((resolve, reject) => {
  fs.readFile('hello', (err, data) => {
    if (err) reject(err);
    console.log(data);
    resolve('hello');
  });
});

p().then(res => console.log(res)).catch(err => console.log(err));
<commit_msg>remove temp.js<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2013 André Bargull
 * Alle Rechte vorbehalten / All Rights Reserved.  Use is subject to license terms.
 *
 * <https://github.com/anba/es6draft>
 */

(function MathExtensions(global) {
"use strict";

const Object = global.Object,
      Math = global.Math;

Object.defineProperties(Object.assign(Math, {
  fround(v) {
    return Math.roundFloat32(v);
  }
}), {
  fround: {enumerable: false}
});

})(this);
<commit_msg>Math.roundFloat32() -> Math.fround() alias no longer needed (rev19)<commit_after>/*
 * Copyright (c) 2012-2013 André Bargull
 * Alle Rechte vorbehalten / All Rights Reserved.  Use is subject to license terms.
 *
 * <https://github.com/anba/es6draft>
 */

(function MathExtensions(global) {
"use strict";

})(this);
<|endoftext|>