From 73300cdcde10debb6d656c6c0d4f379bbcddf677 Mon Sep 17 00:00:00 2001 From: haad Date: Sun, 31 Jul 2016 11:11:48 +0200 Subject: [PATCH] Update examples --- .gitignore | 1 + examples/browser.html | 43 - examples/browser.js | 42 - examples/browser/browser.html | 49 + examples/browser/browser.js | 45 + examples/{ => browser}/index.html | 1 + examples/bundle.js | 178491 --------------------------- 7 files changed, 96 insertions(+), 178576 deletions(-) delete mode 100644 examples/browser.html delete mode 100644 examples/browser.js create mode 100644 examples/browser/browser.html create mode 100644 examples/browser/browser.js rename examples/{ => browser}/index.html (80%) delete mode 100644 examples/bundle.js diff --git a/.gitignore b/.gitignore index c54dc61..4cc30ee 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ node_modules/ dump.rdb Vagrantfile orbit-db-cache.json +examples/browser/bundle.js \ No newline at end of file diff --git a/examples/browser.html b/examples/browser.html deleted file mode 100644 index e4feb6d..0000000 --- a/examples/browser.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - diff --git a/examples/browser.js b/examples/browser.js deleted file mode 100644 index ec09b20..0000000 --- a/examples/browser.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -// const IpfsApi = require('ipfs-api'); -const IPFS = require('exports?Ipfs!ipfs/dist/index.js') -const Logger = require('logplease'); -const logger = Logger.create("orbit-db example", { color: Logger.Colors.Green, showTimestamp: false, showLevel: false }); -const OrbitDB = require('../src/OrbitDB'); - -const network = 'QmYPobvobKsyoCKTw476yTui611XABf927KxUPCf4gRLRr'; // 'localhost:3333' -const username = 'user1'; -const password = ''; -const channel = 'browsertest1'; -const key = 'greeting'; -const value = 'Hello world'; - -try { - const ipfs = new IPFS(); - OrbitDB.connect(network, username, password, ipfs).then((orbit) => { - orbit.kvstore(channel).then((db) => { - let count = 1; - const query = () => { - const startTime = new Date().getTime(); - db.put(key, value + " " + count).then((res) => { - const endTime = new Date().getTime(); - logger.debug(`db.put (#${count}) took ${(endTime - startTime)} ms\n`); - count ++; - - const result = db.get(key); - logger.debug("---------------------------------------------------") - logger.debug("Key | Value") - logger.debug("---------------------------------------------------") - logger.debug(`${key} | ${result}`); - logger.debug("---------------------------------------------------") - console.log('\n'); - }).catch((e) => logger.error(e.stack)); - }; - setInterval(query, 1000); - }); - }); -} catch(e) { - logger.error(e.stack); -} diff --git a/examples/browser/browser.html b/examples/browser/browser.html new file mode 100644 index 0000000..2f123d8 --- /dev/null +++ b/examples/browser/browser.html @@ -0,0 +1,49 @@ + + + + + +
Loading...
+ + + + + + + diff --git a/examples/browser/browser.js b/examples/browser/browser.js new file mode 100644 index 0000000..2c105e6 --- /dev/null +++ b/examples/browser/browser.js @@ -0,0 +1,45 @@ +'use strict'; + +const IPFS = require('exports?Ipfs!ipfs/dist/index.js') +const Logger = require('logplease') +const logger = Logger.create("orbit-db example", { color: Logger.Colors.Green, showTimestamp: false, showLevel: false }) +const OrbitDB = require('../../src/OrbitDB') + +const network = '178.62.241.75:3333' +const username = 'user1' +const password = '' +const channel = 'browsertest1' +const key = 'greeting' +const value = 'Hello world' + +try { + const elm = document.getElementById("result") + const ipfs = new IPFS() + OrbitDB.connect(network, username, password, ipfs).then((orbit) => { + orbit.kvstore(channel).then((db) => { + let count = 1 + const query = () => { + const startTime = new Date().getTime() + db.put(key, value + " " + count).then((res) => { + const endTime = new Date().getTime() + logger.debug(`db.put (#${count}) took ${(endTime - startTime)} ms\n`) + count ++ + + const result = db.get(key) + const output = ` + --------------------------------------------------- + Key | Value + --------------------------------------------------- + ${key} | ${result} + ---------------------------------------------------` + + elm.innerHTML = output.split("\n").join("
") + logger.debug(output) + }).catch((e) => logger.error(e.stack)) + } + setInterval(query, 1000) + }) + }) +} catch(e) { + logger.error(e.stack) +} diff --git a/examples/index.html b/examples/browser/index.html similarity index 80% rename from examples/index.html rename to examples/browser/index.html index 1d22b41..df945bd 100644 --- a/examples/index.html +++ b/examples/browser/index.html @@ -3,6 +3,7 @@ +
Loading...
diff --git a/examples/bundle.js b/examples/bundle.js deleted file mode 100644 index 8bbe394..0000000 --- a/examples/bundle.js +++ /dev/null @@ -1,178491 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.l = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 123); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ function(module, exports) { - - var g; - - // This works in non-strict mode - g = (function() { return this; })(); - - try { - // This works if eval is allowed (see CSP) - g = g || Function("return this")() || (1,eval)("this"); - } catch(e) { - // This works if the window reference is available - if(typeof window === "object") - g = window; - } - - // g can still be undefined, but nothing to do about it... - // We return undefined, instead of nothing here, so it's - // easier to handle this case. if(!global) { ...} - - module.exports = g; - - -/***/ }, -/* 1 */ -/***/ function(module, exports, __webpack_require__) { - - var store = __webpack_require__(64)('wks') - , uid = __webpack_require__(68) - , Symbol = __webpack_require__(2).Symbol - , USE_SYMBOL = typeof Symbol == 'function'; - - var $exports = module.exports = function(name){ - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); - }; - - $exports.store = store; - -/***/ }, -/* 2 */ -/***/ function(module, exports) { - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); - if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef - -/***/ }, -/* 3 */ -/***/ function(module, exports, __webpack_require__) { - - - /** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - - exports = module.exports = __webpack_require__(169); - exports.log = log; - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; - exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - - /** - * Colors. - */ - - exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' - ]; - - /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - - function useColors() { - // is webkit? http://stackoverflow.com/a/16459606/376773 - return ('WebkitAppearance' in document.documentElement.style) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (window.console && (console.firebug || (console.exception && console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); - } - - /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - - exports.formatters.j = function(v) { - return JSON.stringify(v); - }; - - - /** - * Colorize log arguments if enabled. - * - * @api public - */ - - function formatArgs() { - var args = arguments; - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return args; - - var c = 'color: ' + this.color; - args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); - return args; - } - - /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - - function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } - - /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - - function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} - } - - /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - - function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - return r; - } - - /** - * Enable namespaces listed in `localStorage.debug` initially. - */ - - exports.enable(load()); - - /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - - function localstorage(){ - try { - return window.localStorage; - } catch (e) {} - } - - -/***/ }, -/* 4 */ -/***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(12); - module.exports = function(it){ - if(!isObject(it))throw TypeError(it + ' is not an object!'); - return it; - }; - -/***/ }, -/* 5 */ -/***/ function(module, exports) { - - var core = module.exports = {version: '2.4.0'}; - if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef - -/***/ }, -/* 6 */ -/***/ function(module, exports, __webpack_require__) { - - // Thank's IE8 for his funny defineProperty - module.exports = !__webpack_require__(59)(function(){ - return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; - }); - -/***/ }, -/* 7 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(setImmediate, clearImmediate) {var nextTick = __webpack_require__(196).nextTick; - var apply = Function.prototype.apply; - var slice = Array.prototype.slice; - var immediateIds = {}; - var nextImmediateId = 0; - - // DOM APIs, for completeness - - exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); - }; - exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); - }; - exports.clearTimeout = - exports.clearInterval = function(timeout) { timeout.close(); }; - - function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; - } - Timeout.prototype.unref = Timeout.prototype.ref = function() {}; - Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); - }; - - // Does not start the time, just sets up the members needed. - exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; - }; - - exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; - }; - - exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } - }; - - // That's not how node.js implements it but the exposed api is the same. - exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; - }; - - exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; - }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7).setImmediate, __webpack_require__(7).clearImmediate)) - -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(14) - , createDesc = __webpack_require__(30); - module.exports = __webpack_require__(6) ? function(object, key, value){ - return dP.f(object, key, createDesc(1, value)); - } : function(object, key, value){ - object[key] = value; - return object; - }; - -/***/ }, -/* 9 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - */ - - var keys = __webpack_require__(176); - var hasBinary = __webpack_require__(177); - var sliceBuffer = __webpack_require__(120); - var base64encoder = __webpack_require__(127); - var after = __webpack_require__(119); - var utf8 = __webpack_require__(202); - - /** - * Check if we are running an android browser. That requires us to use - * ArrayBuffer with polling transports... - * - * http://ghinda.net/jpeg-blob-ajax-android/ - */ - - var isAndroid = navigator.userAgent.match(/Android/i); - - /** - * Check if we are running in PhantomJS. - * Uploading a Blob with PhantomJS does not work correctly, as reported here: - * https://github.com/ariya/phantomjs/issues/11395 - * @type boolean - */ - var isPhantomJS = /PhantomJS/i.test(navigator.userAgent); - - /** - * When true, avoids using Blobs to encode payloads. - * @type boolean - */ - var dontSendBlobs = isAndroid || isPhantomJS; - - /** - * Current protocol version. - */ - - exports.protocol = 3; - - /** - * Packet types. - */ - - var packets = exports.packets = { - open: 0 // non-ws - , close: 1 // non-ws - , ping: 2 - , pong: 3 - , message: 4 - , upgrade: 5 - , noop: 6 - }; - - var packetslist = keys(packets); - - /** - * Premade error packet. - */ - - var err = { type: 'error', data: 'parser error' }; - - /** - * Create a blob api even for blob builder when vendor prefixes exist - */ - - var Blob = __webpack_require__(129); - - /** - * Encodes a packet. - * - * [ ] - * - * Example: - * - * 5hello world - * 3 - * 4 - * - * Binary is encoded in an identical principle - * - * @api private - */ - - exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) { - if ('function' == typeof supportsBinary) { - callback = supportsBinary; - supportsBinary = false; - } - - if ('function' == typeof utf8encode) { - callback = utf8encode; - utf8encode = null; - } - - var data = (packet.data === undefined) - ? undefined - : packet.data.buffer || packet.data; - - if (global.ArrayBuffer && data instanceof ArrayBuffer) { - return encodeArrayBuffer(packet, supportsBinary, callback); - } else if (Blob && data instanceof global.Blob) { - return encodeBlob(packet, supportsBinary, callback); - } - - // might be an object with { base64: true, data: dataAsBase64String } - if (data && data.base64) { - return encodeBase64Object(packet, callback); - } - - // Sending data as a utf-8 string - var encoded = packets[packet.type]; - - // data fragment is optional - if (undefined !== packet.data) { - encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data); - } - - return callback('' + encoded); - - }; - - function encodeBase64Object(packet, callback) { - // packet data is an object { base64: true, data: dataAsBase64String } - var message = 'b' + exports.packets[packet.type] + packet.data.data; - return callback(message); - } - - /** - * Encode packet helpers for binary types - */ - - function encodeArrayBuffer(packet, supportsBinary, callback) { - if (!supportsBinary) { - return exports.encodeBase64Packet(packet, callback); - } - - var data = packet.data; - var contentArray = new Uint8Array(data); - var resultBuffer = new Uint8Array(1 + data.byteLength); - - resultBuffer[0] = packets[packet.type]; - for (var i = 0; i < contentArray.length; i++) { - resultBuffer[i+1] = contentArray[i]; - } - - return callback(resultBuffer.buffer); - } - - function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { - if (!supportsBinary) { - return exports.encodeBase64Packet(packet, callback); - } - - var fr = new FileReader(); - fr.onload = function() { - packet.data = fr.result; - exports.encodePacket(packet, supportsBinary, true, callback); - }; - return fr.readAsArrayBuffer(packet.data); - } - - function encodeBlob(packet, supportsBinary, callback) { - if (!supportsBinary) { - return exports.encodeBase64Packet(packet, callback); - } - - if (dontSendBlobs) { - return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); - } - - var length = new Uint8Array(1); - length[0] = packets[packet.type]; - var blob = new Blob([length.buffer, packet.data]); - - return callback(blob); - } - - /** - * Encodes a packet with binary data in a base64 string - * - * @param {Object} packet, has `type` and `data` - * @return {String} base64 encoded message - */ - - exports.encodeBase64Packet = function(packet, callback) { - var message = 'b' + exports.packets[packet.type]; - if (Blob && packet.data instanceof global.Blob) { - var fr = new FileReader(); - fr.onload = function() { - var b64 = fr.result.split(',')[1]; - callback(message + b64); - }; - return fr.readAsDataURL(packet.data); - } - - var b64data; - try { - b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); - } catch (e) { - // iPhone Safari doesn't let you apply with typed arrays - var typed = new Uint8Array(packet.data); - var basic = new Array(typed.length); - for (var i = 0; i < typed.length; i++) { - basic[i] = typed[i]; - } - b64data = String.fromCharCode.apply(null, basic); - } - message += global.btoa(b64data); - return callback(message); - }; - - /** - * Decodes a packet. Changes format to Blob if requested. - * - * @return {Object} with `type` and `data` (if any) - * @api private - */ - - exports.decodePacket = function (data, binaryType, utf8decode) { - // String data - if (typeof data == 'string' || data === undefined) { - if (data.charAt(0) == 'b') { - return exports.decodeBase64Packet(data.substr(1), binaryType); - } - - if (utf8decode) { - try { - data = utf8.decode(data); - } catch (e) { - return err; - } - } - var type = data.charAt(0); - - if (Number(type) != type || !packetslist[type]) { - return err; - } - - if (data.length > 1) { - return { type: packetslist[type], data: data.substring(1) }; - } else { - return { type: packetslist[type] }; - } - } - - var asArray = new Uint8Array(data); - var type = asArray[0]; - var rest = sliceBuffer(data, 1); - if (Blob && binaryType === 'blob') { - rest = new Blob([rest]); - } - return { type: packetslist[type], data: rest }; - }; - - /** - * Decodes a packet encoded in a base64 string - * - * @param {String} base64 encoded message - * @return {Object} with `type` and `data` (if any) - */ - - exports.decodeBase64Packet = function(msg, binaryType) { - var type = packetslist[msg.charAt(0)]; - if (!global.ArrayBuffer) { - return { type: type, data: { base64: true, data: msg.substr(1) } }; - } - - var data = base64encoder.decode(msg.substr(1)); - - if (binaryType === 'blob' && Blob) { - data = new Blob([data]); - } - - return { type: type, data: data }; - }; - - /** - * Encodes multiple messages (payload). - * - * :data - * - * Example: - * - * 11:hello world2:hi - * - * If any contents are binary, they will be encoded as base64 strings. Base64 - * encoded strings are marked with a b before the length specifier - * - * @param {Array} packets - * @api private - */ - - exports.encodePayload = function (packets, supportsBinary, callback) { - if (typeof supportsBinary == 'function') { - callback = supportsBinary; - supportsBinary = null; - } - - var isBinary = hasBinary(packets); - - if (supportsBinary && isBinary) { - if (Blob && !dontSendBlobs) { - return exports.encodePayloadAsBlob(packets, callback); - } - - return exports.encodePayloadAsArrayBuffer(packets, callback); - } - - if (!packets.length) { - return callback('0:'); - } - - function setLengthHeader(message) { - return message.length + ':' + message; - } - - function encodeOne(packet, doneCallback) { - exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) { - doneCallback(null, setLengthHeader(message)); - }); - } - - map(packets, encodeOne, function(err, results) { - return callback(results.join('')); - }); - }; - - /** - * Async array map using after - */ - - function map(ary, each, done) { - var result = new Array(ary.length); - var next = after(ary.length, done); - - var eachWithIndex = function(i, el, cb) { - each(el, function(error, msg) { - result[i] = msg; - cb(error, result); - }); - }; - - for (var i = 0; i < ary.length; i++) { - eachWithIndex(i, ary[i], next); - } - } - - /* - * Decodes data when a payload is maybe expected. Possible binary contents are - * decoded from their base64 representation - * - * @param {String} data, callback method - * @api public - */ - - exports.decodePayload = function (data, binaryType, callback) { - if (typeof data != 'string') { - return exports.decodePayloadAsBinary(data, binaryType, callback); - } - - if (typeof binaryType === 'function') { - callback = binaryType; - binaryType = null; - } - - var packet; - if (data == '') { - // parser error - ignoring payload - return callback(err, 0, 1); - } - - var length = '' - , n, msg; - - for (var i = 0, l = data.length; i < l; i++) { - var chr = data.charAt(i); - - if (':' != chr) { - length += chr; - } else { - if ('' == length || (length != (n = Number(length)))) { - // parser error - ignoring payload - return callback(err, 0, 1); - } - - msg = data.substr(i + 1, n); - - if (length != msg.length) { - // parser error - ignoring payload - return callback(err, 0, 1); - } - - if (msg.length) { - packet = exports.decodePacket(msg, binaryType, true); - - if (err.type == packet.type && err.data == packet.data) { - // parser error in individual packet - ignoring payload - return callback(err, 0, 1); - } - - var ret = callback(packet, i + n, l); - if (false === ret) return; - } - - // advance cursor - i += n; - length = ''; - } - } - - if (length != '') { - // parser error - ignoring payload - return callback(err, 0, 1); - } - - }; - - /** - * Encodes multiple messages (payload) as binary. - * - * <1 = binary, 0 = string>[...] - * - * Example: - * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers - * - * @param {Array} packets - * @return {ArrayBuffer} encoded payload - * @api private - */ - - exports.encodePayloadAsArrayBuffer = function(packets, callback) { - if (!packets.length) { - return callback(new ArrayBuffer(0)); - } - - function encodeOne(packet, doneCallback) { - exports.encodePacket(packet, true, true, function(data) { - return doneCallback(null, data); - }); - } - - map(packets, encodeOne, function(err, encodedPackets) { - var totalLength = encodedPackets.reduce(function(acc, p) { - var len; - if (typeof p === 'string'){ - len = p.length; - } else { - len = p.byteLength; - } - return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 - }, 0); - - var resultArray = new Uint8Array(totalLength); - - var bufferIndex = 0; - encodedPackets.forEach(function(p) { - var isString = typeof p === 'string'; - var ab = p; - if (isString) { - var view = new Uint8Array(p.length); - for (var i = 0; i < p.length; i++) { - view[i] = p.charCodeAt(i); - } - ab = view.buffer; - } - - if (isString) { // not true binary - resultArray[bufferIndex++] = 0; - } else { // true binary - resultArray[bufferIndex++] = 1; - } - - var lenStr = ab.byteLength.toString(); - for (var i = 0; i < lenStr.length; i++) { - resultArray[bufferIndex++] = parseInt(lenStr[i]); - } - resultArray[bufferIndex++] = 255; - - var view = new Uint8Array(ab); - for (var i = 0; i < view.length; i++) { - resultArray[bufferIndex++] = view[i]; - } - }); - - return callback(resultArray.buffer); - }); - }; - - /** - * Encode as Blob - */ - - exports.encodePayloadAsBlob = function(packets, callback) { - function encodeOne(packet, doneCallback) { - exports.encodePacket(packet, true, true, function(encoded) { - var binaryIdentifier = new Uint8Array(1); - binaryIdentifier[0] = 1; - if (typeof encoded === 'string') { - var view = new Uint8Array(encoded.length); - for (var i = 0; i < encoded.length; i++) { - view[i] = encoded.charCodeAt(i); - } - encoded = view.buffer; - binaryIdentifier[0] = 0; - } - - var len = (encoded instanceof ArrayBuffer) - ? encoded.byteLength - : encoded.size; - - var lenStr = len.toString(); - var lengthAry = new Uint8Array(lenStr.length + 1); - for (var i = 0; i < lenStr.length; i++) { - lengthAry[i] = parseInt(lenStr[i]); - } - lengthAry[lenStr.length] = 255; - - if (Blob) { - var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); - doneCallback(null, blob); - } - }); - } - - map(packets, encodeOne, function(err, results) { - return callback(new Blob(results)); - }); - }; - - /* - * Decodes data when a payload is maybe expected. Strings are decoded by - * interpreting each byte as a key code for entries marked to start with 0. See - * description of encodePayloadAsBinary - * - * @param {ArrayBuffer} data, callback method - * @api public - */ - - exports.decodePayloadAsBinary = function (data, binaryType, callback) { - if (typeof binaryType === 'function') { - callback = binaryType; - binaryType = null; - } - - var bufferTail = data; - var buffers = []; - - var numberTooLong = false; - while (bufferTail.byteLength > 0) { - var tailArray = new Uint8Array(bufferTail); - var isString = tailArray[0] === 0; - var msgLength = ''; - - for (var i = 1; ; i++) { - if (tailArray[i] == 255) break; - - if (msgLength.length > 310) { - numberTooLong = true; - break; - } - - msgLength += tailArray[i]; - } - - if(numberTooLong) return callback(err, 0, 1); - - bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); - msgLength = parseInt(msgLength); - - var msg = sliceBuffer(bufferTail, 0, msgLength); - if (isString) { - try { - msg = String.fromCharCode.apply(null, new Uint8Array(msg)); - } catch (e) { - // iPhone Safari doesn't let you apply to typed arrays - var typed = new Uint8Array(msg); - msg = ''; - for (var i = 0; i < typed.length; i++) { - msg += String.fromCharCode(typed[i]); - } - } - } - - buffers.push(msg); - bufferTail = sliceBuffer(bufferTail, msgLength); - } - - var total = buffers.length; - buffers.forEach(function(buffer, i) { - callback(exports.decodePacket(buffer, binaryType, true), i, total); - }); - }; - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) - -/***/ }, -/* 10 */ -/***/ function(module, exports, __webpack_require__) { - - // optional / simple context binding - var aFunction = __webpack_require__(26); - module.exports = function(fn, that, length){ - aFunction(fn); - if(that === undefined)return fn; - switch(length){ - case 1: return function(a){ - return fn.call(that, a); - }; - case 2: return function(a, b){ - return fn.call(that, a, b); - }; - case 3: return function(a, b, c){ - return fn.call(that, a, b, c); - }; - } - return function(/* ...args */){ - return fn.apply(that, arguments); - }; - }; - -/***/ }, -/* 11 */ -/***/ function(module, exports) { - - var hasOwnProperty = {}.hasOwnProperty; - module.exports = function(it, key){ - return hasOwnProperty.call(it, key); - }; - -/***/ }, -/* 12 */ -/***/ function(module, exports) { - - module.exports = function(it){ - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - -/***/ }, -/* 13 */ -/***/ function(module, exports) { - - module.exports = {}; - -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(4) - , IE8_DOM_DEFINE = __webpack_require__(61) - , toPrimitive = __webpack_require__(67) - , dP = Object.defineProperty; - - exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes){ - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if(IE8_DOM_DEFINE)try { - return dP(O, P, Attributes); - } catch(e){ /* empty */ } - if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); - if('value' in Attributes)O[P] = Attributes.value; - return O; - }; - -/***/ }, -/* 15 */ -/***/ function(module, exports) { - - var core = module.exports = {version: '2.4.0'}; - if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef - -/***/ }, -/* 16 */ -/***/ function(module, exports, __webpack_require__) { - - // Thank's IE8 for his funny defineProperty - module.exports = !__webpack_require__(22)(function(){ - return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; - }); - -/***/ }, -/* 17 */ -/***/ function(module, exports) { - - - module.exports = function(a, b){ - var fn = function(){}; - fn.prototype = b.prototype; - a.prototype = new fn; - a.prototype.constructor = a; - }; - -/***/ }, -/* 18 */ -/***/ function(module, exports) { - - var toString = {}.toString; - - module.exports = function(it){ - return toString.call(it).slice(8, -1); - }; - -/***/ }, -/* 19 */ -/***/ function(module, exports, __webpack_require__) { - - // to indexed object, toObject with fallback for non-array-like ES3 strings - var IObject = __webpack_require__(138) - , defined = __webpack_require__(27); - module.exports = function(it){ - return IObject(defined(it)); - }; - -/***/ }, -/* 20 */ -/***/ function(module, exports, __webpack_require__) { - - exports.nextTick = function nextTick(fn) { - setTimeout(fn, 0); - }; - - exports.platform = exports.arch = - exports.execPath = exports.title = 'browser'; - exports.pid = 1; - exports.browser = true; - exports.env = {}; - exports.argv = []; - - exports.binding = function (name) { - throw new Error('No such module. (Possibly not yet loaded)') - }; - - (function () { - var cwd = '/'; - var path; - exports.cwd = function () { return cwd }; - exports.chdir = function (dir) { - if (!path) path = __webpack_require__(77); - cwd = path.resolve(dir, cwd); - }; - })(); - - exports.exit = exports.kill = - exports.umask = exports.dlopen = - exports.uptime = exports.memoryUsage = - exports.uvCounters = function() {}; - exports.features = {}; - - -/***/ }, -/* 21 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - - const fs = __webpack_require__(73); - const format = __webpack_require__(204).format; - - let isNodejs = process.version ? true : false; - - const LogLevels = { - 'DEBUG': 'DEBUG', - 'INFO': 'INFO', - 'WARN': 'WARN', - 'ERROR': 'ERROR', - 'NONE': 'NONE', - }; - - // Global log level - let GlobalLogLevel = LogLevels.DEBUG; - - // Global log file name - let GlobalLogfile = null; - - // ANSI colors - let Colors = { - 'Black': 0, - 'Red': 1, - 'Green': 2, - 'Yellow': 3, - 'Blue': 4, - 'Magenta': 5, - 'Cyan': 6, - 'Grey': 7, - 'White': 9, - 'Default': 9, - }; - - // CSS colors - if(!isNodejs) { - Colors = { - 'Black': 'Black', - 'Red': 'IndianRed', - 'Green': 'LimeGreen', - 'Yellow': 'Orange', - 'Blue': 'RoyalBlue', - 'Magenta': 'Orchid', - 'Cyan': 'SkyBlue', - 'Grey': 'DimGrey', - 'White': 'White', - 'Default': 'Black', - }; - } - - const loglevelColors = [Colors.Cyan, Colors.Green, Colors.Yellow, Colors.Red, Colors.Default]; - - const defaultOptions = { - useColors: true, - color: Colors.Default, - showTimestamp: true, - showLevel: true, - filename: GlobalLogfile, - appendFile: true, - }; - - class Logger { - constructor(category, options) { - this.category = category; - let opts = {}; - Object.assign(opts, defaultOptions); - Object.assign(opts, options); - this.options = opts; - } - - debug() { - this._write(LogLevels.DEBUG, format.apply(null, arguments)); - } - - log() { - this.debug.apply(this, arguments); - } - - info() { - this._write(LogLevels.INFO, format.apply(null, arguments)); - } - - warn() { - this._write(LogLevels.WARN, format.apply(null, arguments)); - } - - error() { - this._write(LogLevels.ERROR, format.apply(null, arguments)); - } - - _write(level, text) { - if(!this._shouldLog(level)) - return; - - if((this.options.filename || GlobalLogfile) && !this.fileWriter) - this.fileWriter = fs.openSync(this.options.filename || GlobalLogfile, this.options.appendFile ? 'a+' : 'w+'); - - let format = this._format(level, text); - let unformattedText = this._createLogMessage(level, text); - let formattedText = this._createLogMessage(level, text, format.timestamp, format.level, format.category, format.text); - - if(this.fileWriter) - fs.writeSync(this.fileWriter, unformattedText + '\n', null, 'utf-8'); - - if(isNodejs) { - console.log(formattedText) - } else { - // TODO: clean this up - if(level === LogLevels.ERROR) { - if(this.options.showTimestamp && this.options.showLevel) { - console.error(formattedText, format.timestamp, format.level, format.category, format.text) - } else if(this.options.showTimestamp && !this.options.showLevel) { - console.error(formattedText, format.timestamp, format.category, format.text) - } else if(!this.options.showTimestamp && this.options.showLevel) { - console.error(formattedText, format.level, format.category, format.text) - } else { - console.error(formattedText, format.category, format.text) - } - } else { - if(this.options.showTimestamp && this.options.showLevel) { - console.log(formattedText, format.timestamp, format.level, format.category, format.text) - } else if(this.options.showTimestamp && !this.options.showLevel) { - console.log(formattedText, format.timestamp, format.category, format.text) - } else if(!this.options.showTimestamp && this.options.showLevel) { - console.log(formattedText, format.level, format.category, format.text) - } else { - console.log(formattedText, format.category, format.text) - } - } - } - } - - _format(level, text) { - let timestampFormat = ''; - let levelFormat = ''; - let categoryFormat = ''; - let textFormat = ': '; - - if(this.options.useColors) { - const levelColor = Object.keys(LogLevels).map((f) => LogLevels[f]).indexOf(level); - const categoryColor = this.options.color; - - if(isNodejs) { - if(this.options.showTimestamp) - timestampFormat = '\u001b[3' + Colors.Grey + 'm'; - - if(this.options.showLevel) - levelFormat = '\u001b[3' + loglevelColors[levelColor] + ';22m'; - - categoryFormat = '\u001b[3' + categoryColor + ';1m'; - textFormat = '\u001b[0m: '; - } else { - if(this.options.showTimestamp) - timestampFormat = 'color:' + Colors.Grey; - - if(this.options.showLevel) - levelFormat = 'color:' + loglevelColors[levelColor]; - - categoryFormat = 'color:' + categoryColor + '; font-weight: bold'; - } - } - - return { - timestamp: timestampFormat, - level: levelFormat, - category: categoryFormat, - text: textFormat - }; - } - - _createLogMessage(level, text, timestampFormat, levelFormat, categoryFormat, textFormat) { - timestampFormat = timestampFormat || ''; - levelFormat = levelFormat || ''; - categoryFormat = categoryFormat || ''; - textFormat = textFormat || ': '; - - if(!isNodejs) { - if(this.options.showTimestamp) - timestampFormat = '%c'; - - if(this.options.showLevel) - levelFormat = '%c'; - - categoryFormat = '%c'; - textFormat = ': %c'; - } - - let result = ''; - - if(this.options.showTimestamp) - result += '' + new Date().toISOString() + ' '; - - result = timestampFormat + result; - - if(this.options.showLevel) - result += levelFormat + '[' + level +']' + (level === LogLevels.INFO || level === LogLevels.WARN ? ' ' : '') + ' '; - - result += categoryFormat + this.category; - result += textFormat + text; - return result; - } - - _shouldLog(level) { - const levels = Object.keys(LogLevels).map((f) => LogLevels[f]); - const index = levels.indexOf(level); - const levelIdx = levels.indexOf(GlobalLogLevel); - return index >= levelIdx; - } - }; - - /* Public API */ - module.exports = { - Colors: Colors, - LogLevels: LogLevels, - setLogLevel: (level) => { - GlobalLogLevel = level; - }, - setLogfile: (filename) => { - GlobalLogfile = filename; - }, - create: (category, options) => { - const logger = new Logger(category, options); - return logger; - }, - forceBrowserMode: (force) => isNodejs = !force, // for testing - }; - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20))) - -/***/ }, -/* 22 */ -/***/ function(module, exports) { - - module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; - } - }; - -/***/ }, -/* 23 */ -/***/ function(module, exports) { - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); - if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef - -/***/ }, -/* 24 */ -/***/ function(module, exports) { - - module.exports = function(it){ - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - -/***/ }, -/* 25 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - 'use strict' - - var base64 = __webpack_require__(128) - var ieee754 = __webpack_require__(182) - var isArray = __webpack_require__(184) - - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - - /* - * Export kMaxLength after typed array support is determined. - */ - exports.kMaxLength = kMaxLength() - - function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.foo = function () { return 42 } - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } - } - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer.poolSize = 8192 // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr - } - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - } - - function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; i++) { - that[i] = 0 - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - } - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - } - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - that.write(string, encoding) - return that - } - - function fromArrayLike (that, array) { - var length = checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that - } - - function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) - } - - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'binary': - case 'base64': - case 'raw': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - } - - Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; i++) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; i++) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer - } - - function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'binary': - // Deprecated - case 'raw': - case 'raws': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - Buffer.byteLength = byteLength - - function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'binary': - return binarySlice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true - - function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i - } - - Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this - } - - Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this - } - - Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - } - - Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - } - - Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' - } - - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - function arrayIndexOf (arr, val, byteOffset, encoding) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var foundIndex = -1 - for (var i = 0; byteOffset + i < arrLength; i++) { - if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - return -1 - } - - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset >>= 0 - - if (this.length === 0) return -1 - if (byteOffset >= this.length) return -1 - - // Negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) - - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - if (Buffer.isBuffer(val)) { - // special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(this, val, byteOffset, encoding) - } - if (typeof val === 'number') { - if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { - return Uint8Array.prototype.indexOf.call(this, val, byteOffset) - } - return arrayIndexOf(this, [ val ], byteOffset, encoding) - } - - throw new TypeError('val must be string, number or Buffer') - } - - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - } - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new Error('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; i++) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function binaryWrite (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'binary': - return binaryWrite(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - } - - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000 - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret - } - - function binarySlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i]) - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; i++) { - out += toHex(buf[i]) - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res - } - - Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; i++) { - newBuf[i] = this[i + start] - } - } - - return newBuf - } - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val - } - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val - } - - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] - } - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) - } - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] - } - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - } - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - } - - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - } - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - } - - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - } - - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) - } - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) - } - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) - } - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) - } - - function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 - } - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 - } - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 - } - - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - } - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - } - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; i--) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; i++) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len - } - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; i++) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; i++) { - this[i + start] = bytes[i % len] - } - } - - return this - } - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str - } - - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; i++) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; i++) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray - } - - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; i++) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25).Buffer, __webpack_require__(0))) - -/***/ }, -/* 26 */ -/***/ function(module, exports) { - - module.exports = function(it){ - if(typeof it != 'function')throw TypeError(it + ' is not a function!'); - return it; - }; - -/***/ }, -/* 27 */ -/***/ function(module, exports) { - - // 7.2.1 RequireObjectCoercible(argument) - module.exports = function(it){ - if(it == undefined)throw TypeError("Can't call method on " + it); - return it; - }; - -/***/ }, -/* 28 */ -/***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(12) - , document = __webpack_require__(2).document - // in old IE typeof document.createElement is 'object' - , is = isObject(document) && isObject(document.createElement); - module.exports = function(it){ - return is ? document.createElement(it) : {}; - }; - -/***/ }, -/* 29 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(2) - , core = __webpack_require__(5) - , ctx = __webpack_require__(10) - , hide = __webpack_require__(8) - , PROTOTYPE = 'prototype'; - - var $export = function(type, name, source){ - var IS_FORCED = type & $export.F - , IS_GLOBAL = type & $export.G - , IS_STATIC = type & $export.S - , IS_PROTO = type & $export.P - , IS_BIND = type & $export.B - , IS_WRAP = type & $export.W - , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) - , expProto = exports[PROTOTYPE] - , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] - , key, own, out; - if(IS_GLOBAL)source = name; - for(key in source){ - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - if(own && key in exports)continue; - // export native or passed - out = own ? target[key] : source[key]; - // prevent global pollution for namespaces - exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] - // bind timers to global for call from export context - : IS_BIND && own ? ctx(out, global) - // wrap global constructors for prevent change them in library - : IS_WRAP && target[key] == out ? (function(C){ - var F = function(a, b, c){ - if(this instanceof C){ - switch(arguments.length){ - case 0: return new C; - case 1: return new C(a); - case 2: return new C(a, b); - } return new C(a, b, c); - } return C.apply(this, arguments); - }; - F[PROTOTYPE] = C[PROTOTYPE]; - return F; - // make static versions for prototype methods - })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% - if(IS_PROTO){ - (exports.virtual || (exports.virtual = {}))[key] = out; - // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% - if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); - } - } - }; - // type bitmap - $export.F = 1; // forced - $export.G = 2; // global - $export.S = 4; // static - $export.P = 8; // proto - $export.B = 16; // bind - $export.W = 32; // wrap - $export.U = 64; // safe - $export.R = 128; // real proto method for `library` - module.exports = $export; - -/***/ }, -/* 30 */ -/***/ function(module, exports) { - - module.exports = function(bitmap, value){ - return { - enumerable : !(bitmap & 1), - configurable: !(bitmap & 2), - writable : !(bitmap & 4), - value : value - }; - }; - -/***/ }, -/* 31 */ -/***/ function(module, exports, __webpack_require__) { - - var def = __webpack_require__(14).f - , has = __webpack_require__(11) - , TAG = __webpack_require__(1)('toStringTag'); - - module.exports = function(it, tag, stat){ - if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); - }; - -/***/ }, -/* 32 */ -/***/ function(module, exports, __webpack_require__) { - - var shared = __webpack_require__(64)('keys') - , uid = __webpack_require__(68); - module.exports = function(key){ - return shared[key] || (shared[key] = uid(key)); - }; - -/***/ }, -/* 33 */ -/***/ function(module, exports) { - - // 7.1.4 ToInteger - var ceil = Math.ceil - , floor = Math.floor; - module.exports = function(it){ - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); - }; - -/***/ }, -/* 34 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * Module dependencies. - */ - - var parser = __webpack_require__(9); - var Emitter = __webpack_require__(36); - - /** - * Module exports. - */ - - module.exports = Transport; - - /** - * Transport abstract constructor. - * - * @param {Object} options. - * @api private - */ - - function Transport (opts) { - this.path = opts.path; - this.hostname = opts.hostname; - this.port = opts.port; - this.secure = opts.secure; - this.query = opts.query; - this.timestampParam = opts.timestampParam; - this.timestampRequests = opts.timestampRequests; - this.readyState = ''; - this.agent = opts.agent || false; - this.socket = opts.socket; - this.enablesXDR = opts.enablesXDR; - - // SSL options for Node.js client - this.pfx = opts.pfx; - this.key = opts.key; - this.passphrase = opts.passphrase; - this.cert = opts.cert; - this.ca = opts.ca; - this.ciphers = opts.ciphers; - this.rejectUnauthorized = opts.rejectUnauthorized; - - // other options for Node.js client - this.extraHeaders = opts.extraHeaders; - } - - /** - * Mix in `Emitter`. - */ - - Emitter(Transport.prototype); - - /** - * Emits an error. - * - * @param {String} str - * @return {Transport} for chaining - * @api public - */ - - Transport.prototype.onError = function (msg, desc) { - var err = new Error(msg); - err.type = 'TransportError'; - err.description = desc; - this.emit('error', err); - return this; - }; - - /** - * Opens the transport. - * - * @api public - */ - - Transport.prototype.open = function () { - if ('closed' == this.readyState || '' == this.readyState) { - this.readyState = 'opening'; - this.doOpen(); - } - - return this; - }; - - /** - * Closes the transport. - * - * @api private - */ - - Transport.prototype.close = function () { - if ('opening' == this.readyState || 'open' == this.readyState) { - this.doClose(); - this.onClose(); - } - - return this; - }; - - /** - * Sends multiple packets. - * - * @param {Array} packets - * @api private - */ - - Transport.prototype.send = function(packets){ - if ('open' == this.readyState) { - this.write(packets); - } else { - throw new Error('Transport not open'); - } - }; - - /** - * Called upon open - * - * @api private - */ - - Transport.prototype.onOpen = function () { - this.readyState = 'open'; - this.writable = true; - this.emit('open'); - }; - - /** - * Called with data. - * - * @param {String} data - * @api private - */ - - Transport.prototype.onData = function(data){ - var packet = parser.decodePacket(data, this.socket.binaryType); - this.onPacket(packet); - }; - - /** - * Called with a decoded packet. - */ - - Transport.prototype.onPacket = function (packet) { - this.emit('packet', packet); - }; - - /** - * Called upon close. - * - * @api private - */ - - Transport.prototype.onClose = function () { - this.readyState = 'closed'; - this.emit('close'); - }; - - -/***/ }, -/* 35 */ -/***/ function(module, exports, __webpack_require__) { - - // browser shim for xmlhttprequest module - var hasCORS = __webpack_require__(181); - - module.exports = function(opts) { - var xdomain = opts.xdomain; - - // scheme must be same when usign XDomainRequest - // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx - var xscheme = opts.xscheme; - - // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default. - // https://github.com/Automattic/engine.io-client/pull/217 - var enablesXDR = opts.enablesXDR; - - // XMLHttpRequest can be disabled on IE - try { - if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) { - return new XMLHttpRequest(); - } - } catch (e) { } - - // Use XDomainRequest for IE8 if enablesXDR is true - // because loading bar keeps flashing when using jsonp-polling - // https://github.com/yujiosaka/socke.io-ie8-loading-example - try { - if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) { - return new XDomainRequest(); - } - } catch (e) { } - - if (!xdomain) { - try { - return new ActiveXObject('Microsoft.XMLHTTP'); - } catch(e) { } - } - } - - -/***/ }, -/* 36 */ -/***/ function(module, exports) { - - - /** - * Expose `Emitter`. - */ - - module.exports = Emitter; - - /** - * Initialize a new `Emitter`. - * - * @api public - */ - - function Emitter(obj) { - if (obj) return mixin(obj); - }; - - /** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - - function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; - } - - /** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.on = - Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks[event] = this._callbacks[event] || []) - .push(fn); - return this; - }; - - /** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.once = function(event, fn){ - var self = this; - this._callbacks = this._callbacks || {}; - - function on() { - self.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; - }; - - /** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.off = - Emitter.prototype.removeListener = - Emitter.prototype.removeAllListeners = - Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks[event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks[event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; - }; - - /** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - - Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks[event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; - }; - - /** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - - Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks[event] || []; - }; - - /** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - - Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; - }; - - -/***/ }, -/* 37 */ -/***/ function(module, exports) { - - // Copyright Joyent, Inc. and other Node contributors. - // - // 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 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 EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; - } - module.exports = EventEmitter; - - // Backwards-compat with node 0.10.x - EventEmitter.EventEmitter = EventEmitter; - - EventEmitter.prototype._events = undefined; - EventEmitter.prototype._maxListeners = undefined; - - // By default EventEmitters will print a warning if more than 10 listeners are - // added to it. This is a useful default which helps finding memory leaks. - EventEmitter.defaultMaxListeners = 10; - - // Obviously not all Emitters should be limited to 10. This function allows - // that to be increased. Set to zero for unlimited. - EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; - }; - - EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } - throw TypeError('Uncaught, unspecified "error" event.'); - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; - }; - - EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; - }; - - EventEmitter.prototype.on = EventEmitter.prototype.addListener; - - EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; - }; - - // emits a 'removeListener' event iff the listener was removed - EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; - }; - - EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; - }; - - EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; - }; - - EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; - }; - - EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); - }; - - function isFunction(arg) { - return typeof arg === 'function'; - } - - function isNumber(arg) { - return typeof arg === 'number'; - } - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - - function isUndefined(arg) { - return arg === void 0; - } - - -/***/ }, -/* 38 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - 'use strict'; - - const EventEmitter = __webpack_require__(37).EventEmitter; - const Log = __webpack_require__(121); - const Index = __webpack_require__(194); - const Cache = __webpack_require__(193); - - class Store { - constructor(ipfs, id, dbname, options) { - this.id = id; - this.dbname = dbname; - this.events = new EventEmitter(); - - if(!options) options = {}; - if(!options.Index) Object.assign(options, { Index: Index }); - if(!options.cacheFile) Object.assign(options, { cacheFile: null }); - - this.options = options; - this._index = new this.options.Index(this.id); - this._oplog = null; - this._ipfs = ipfs; - this._lastWrite = null; - } - - use() { - this.events.emit('load', this.dbname); - this._oplog = new Log(this._ipfs, this.id, this.dbname, this.options); - return Cache.loadCache(this.options.cacheFile).then(() => { - const cached = Cache.get(this.dbname); - if(cached) { - this._lastWrite = cached; - return Log.fromIpfsHash(this._ipfs, cached) - .then((log) => this._oplog.join(log)) - .then((merged) => this._index.updateIndex(this._oplog, merged)) - .then(() => this.events.emit('ready', this.dbname)) - .then(() => this) - } - - this.events.emit('ready', this.dbname) - return Promise.resolve(this); - }); - } - - close() { - this.events.emit('close', this.dbname); - } - - sync(hash) { - if(!hash || hash === this._lastWrite) { - this.events.emit('updated', this.dbname, []); - return Promise.resolve([]); - } - - const oldCount = this._oplog.items.length; - let newItems = []; - this.events.emit('sync', this.dbname); - this._lastWrite = hash; - return Log.fromIpfsHash(this._ipfs, hash) - .then((log) => this._oplog.join(log)) - .then((merged) => newItems = merged) - .then(() => Cache.set(this.dbname, hash)) - .then(() => this._index.updateIndex(this._oplog, newItems)) - .then(() => { - // if(newItems.length > 0) - this.events.emit('updated', this.dbname, newItems); - }) - .then(() => newItems) - } - - delete() { - this._index = new this.options.Index(this.id); - if(this._oplog) - this._oplog.clear(); - } - - _addOperation(data) { - let result, logHash; - if(this._oplog) { - return this._oplog.add(data) - .then((res) => result = res) - .then(() => Log.getIpfsHash(this._ipfs, this._oplog)) - .then((hash) => logHash = hash) - .then(() => this._lastWrite = logHash) - .then(() => Cache.set(this.dbname, logHash)) - .then(() => this._index.updateIndex(this._oplog, [result])) - .then(() => this.events.emit('data', this.dbname, logHash)) - .then(() => result.hash); - } - } - } - - module.exports = Store; - - -/***/ }, -/* 39 */ -/***/ function(module, exports) { - - /** - * Compiles a querystring - * Returns string representation of the object - * - * @param {Object} - * @api private - */ - - exports.encode = function (obj) { - var str = ''; - - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - if (str.length) str += '&'; - str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); - } - } - - return str; - }; - - /** - * Parses a simple querystring into an object - * - * @param {String} qs - * @api private - */ - - exports.decode = function(qs){ - var qry = {}; - var pairs = qs.split('&'); - for (var i = 0, l = pairs.length; i < l; i++) { - var pair = pairs[i].split('='); - qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); - } - return qry; - }; - - -/***/ }, -/* 40 */ -/***/ function(module, exports, __webpack_require__) { - - - /** - * Module dependencies. - */ - - var debug = __webpack_require__(3)('socket.io-parser'); - var json = __webpack_require__(185); - var isArray = __webpack_require__(82); - var Emitter = __webpack_require__(200); - var binary = __webpack_require__(199); - var isBuf = __webpack_require__(81); - - /** - * Protocol version. - * - * @api public - */ - - exports.protocol = 4; - - /** - * Packet types. - * - * @api public - */ - - exports.types = [ - 'CONNECT', - 'DISCONNECT', - 'EVENT', - 'ACK', - 'ERROR', - 'BINARY_EVENT', - 'BINARY_ACK' - ]; - - /** - * Packet type `connect`. - * - * @api public - */ - - exports.CONNECT = 0; - - /** - * Packet type `disconnect`. - * - * @api public - */ - - exports.DISCONNECT = 1; - - /** - * Packet type `event`. - * - * @api public - */ - - exports.EVENT = 2; - - /** - * Packet type `ack`. - * - * @api public - */ - - exports.ACK = 3; - - /** - * Packet type `error`. - * - * @api public - */ - - exports.ERROR = 4; - - /** - * Packet type 'binary event' - * - * @api public - */ - - exports.BINARY_EVENT = 5; - - /** - * Packet type `binary ack`. For acks with binary arguments. - * - * @api public - */ - - exports.BINARY_ACK = 6; - - /** - * Encoder constructor. - * - * @api public - */ - - exports.Encoder = Encoder; - - /** - * Decoder constructor. - * - * @api public - */ - - exports.Decoder = Decoder; - - /** - * A socket.io Encoder instance - * - * @api public - */ - - function Encoder() {} - - /** - * Encode a packet as a single string if non-binary, or as a - * buffer sequence, depending on packet type. - * - * @param {Object} obj - packet object - * @param {Function} callback - function to handle encodings (likely engine.write) - * @return Calls callback with Array of encodings - * @api public - */ - - Encoder.prototype.encode = function(obj, callback){ - debug('encoding packet %j', obj); - - if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) { - encodeAsBinary(obj, callback); - } - else { - var encoding = encodeAsString(obj); - callback([encoding]); - } - }; - - /** - * Encode packet as string. - * - * @param {Object} packet - * @return {String} encoded - * @api private - */ - - function encodeAsString(obj) { - var str = ''; - var nsp = false; - - // first is type - str += obj.type; - - // attachments if we have them - if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) { - str += obj.attachments; - str += '-'; - } - - // if we have a namespace other than `/` - // we append it followed by a comma `,` - if (obj.nsp && '/' != obj.nsp) { - nsp = true; - str += obj.nsp; - } - - // immediately followed by the id - if (null != obj.id) { - if (nsp) { - str += ','; - nsp = false; - } - str += obj.id; - } - - // json data - if (null != obj.data) { - if (nsp) str += ','; - str += json.stringify(obj.data); - } - - debug('encoded %j as %s', obj, str); - return str; - } - - /** - * Encode packet as 'buffer sequence' by removing blobs, and - * deconstructing packet into object with placeholders and - * a list of buffers. - * - * @param {Object} packet - * @return {Buffer} encoded - * @api private - */ - - function encodeAsBinary(obj, callback) { - - function writeEncoding(bloblessData) { - var deconstruction = binary.deconstructPacket(bloblessData); - var pack = encodeAsString(deconstruction.packet); - var buffers = deconstruction.buffers; - - buffers.unshift(pack); // add packet info to beginning of data list - callback(buffers); // write all the buffers - } - - binary.removeBlobs(obj, writeEncoding); - } - - /** - * A socket.io Decoder instance - * - * @return {Object} decoder - * @api public - */ - - function Decoder() { - this.reconstructor = null; - } - - /** - * Mix in `Emitter` with Decoder. - */ - - Emitter(Decoder.prototype); - - /** - * Decodes an ecoded packet string into packet JSON. - * - * @param {String} obj - encoded packet - * @return {Object} packet - * @api public - */ - - Decoder.prototype.add = function(obj) { - var packet; - if ('string' == typeof obj) { - packet = decodeString(obj); - if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json - this.reconstructor = new BinaryReconstructor(packet); - - // no attachments, labeled binary but no binary data to follow - if (this.reconstructor.reconPack.attachments === 0) { - this.emit('decoded', packet); - } - } else { // non-binary full packet - this.emit('decoded', packet); - } - } - else if (isBuf(obj) || obj.base64) { // raw binary data - if (!this.reconstructor) { - throw new Error('got binary data when not reconstructing a packet'); - } else { - packet = this.reconstructor.takeBinaryData(obj); - if (packet) { // received final buffer - this.reconstructor = null; - this.emit('decoded', packet); - } - } - } - else { - throw new Error('Unknown type: ' + obj); - } - }; - - /** - * Decode a packet String (JSON data) - * - * @param {String} str - * @return {Object} packet - * @api private - */ - - function decodeString(str) { - var p = {}; - var i = 0; - - // look up type - p.type = Number(str.charAt(0)); - if (null == exports.types[p.type]) return error(); - - // look up attachments if type binary - if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) { - var buf = ''; - while (str.charAt(++i) != '-') { - buf += str.charAt(i); - if (i == str.length) break; - } - if (buf != Number(buf) || str.charAt(i) != '-') { - throw new Error('Illegal attachments'); - } - p.attachments = Number(buf); - } - - // look up namespace (if any) - if ('/' == str.charAt(i + 1)) { - p.nsp = ''; - while (++i) { - var c = str.charAt(i); - if (',' == c) break; - p.nsp += c; - if (i == str.length) break; - } - } else { - p.nsp = '/'; - } - - // look up id - var next = str.charAt(i + 1); - if ('' !== next && Number(next) == next) { - p.id = ''; - while (++i) { - var c = str.charAt(i); - if (null == c || Number(c) != c) { - --i; - break; - } - p.id += str.charAt(i); - if (i == str.length) break; - } - p.id = Number(p.id); - } - - // look up json data - if (str.charAt(++i)) { - try { - p.data = json.parse(str.substr(i)); - } catch(e){ - return error(); - } - } - - debug('decoded %s as %j', str, p); - return p; - } - - /** - * Deallocates a parser's resources - * - * @api public - */ - - Decoder.prototype.destroy = function() { - if (this.reconstructor) { - this.reconstructor.finishedReconstruction(); - } - }; - - /** - * A manager of a binary event's 'buffer sequence'. Should - * be constructed whenever a packet of type BINARY_EVENT is - * decoded. - * - * @param {Object} packet - * @return {BinaryReconstructor} initialized reconstructor - * @api private - */ - - function BinaryReconstructor(packet) { - this.reconPack = packet; - this.buffers = []; - } - - /** - * Method to be called when binary data received from connection - * after a BINARY_EVENT packet. - * - * @param {Buffer | ArrayBuffer} binData - the raw binary data received - * @return {null | Object} returns null if more binary data is expected or - * a reconstructed packet object if all buffers have been received. - * @api private - */ - - BinaryReconstructor.prototype.takeBinaryData = function(binData) { - this.buffers.push(binData); - if (this.buffers.length == this.reconPack.attachments) { // done with buffer list - var packet = binary.reconstructPacket(this.reconPack, this.buffers); - this.finishedReconstruction(); - return packet; - } - return null; - }; - - /** - * Cleans up binary packet reconstruction variables. - * - * @api private - */ - - BinaryReconstructor.prototype.finishedReconstruction = function() { - this.reconPack = null; - this.buffers = []; - }; - - function error(data){ - return { - type: exports.ERROR, - data: 'parser error' - }; - } - - -/***/ }, -/* 41 */ -/***/ function(module, exports) { - - module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - configurable: false, - get: function() { return module.l; } - }); - Object.defineProperty(module, "id", { - enumerable: true, - configurable: false, - get: function() { return module.i; } - }); - module.webpackPolyfill = 1; - } - return module; - } - - -/***/ }, -/* 42 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = { "default": __webpack_require__(89), __esModule: true }; - -/***/ }, -/* 43 */ -/***/ function(module, exports) { - - "use strict"; - "use strict"; - - exports.__esModule = true; - - exports.default = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - }; - -/***/ }, -/* 44 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - "use strict"; - - exports.__esModule = true; - - var _defineProperty = __webpack_require__(87); - - var _defineProperty2 = _interopRequireDefault(_defineProperty); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - exports.default = function () { - function defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - (0, _defineProperty2.default)(target, descriptor.key, descriptor); - } - } - - return function (Constructor, protoProps, staticProps) { - if (protoProps) defineProperties(Constructor.prototype, protoProps); - if (staticProps) defineProperties(Constructor, staticProps); - return Constructor; - }; - }(); - -/***/ }, -/* 45 */ -/***/ function(module, exports) { - - // 7.2.1 RequireObjectCoercible(argument) - module.exports = function(it){ - if(it == undefined)throw TypeError("Can't call method on " + it); - return it; - }; - -/***/ }, -/* 46 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(23) - , core = __webpack_require__(15) - , ctx = __webpack_require__(96) - , hide = __webpack_require__(100) - , PROTOTYPE = 'prototype'; - - var $export = function(type, name, source){ - var IS_FORCED = type & $export.F - , IS_GLOBAL = type & $export.G - , IS_STATIC = type & $export.S - , IS_PROTO = type & $export.P - , IS_BIND = type & $export.B - , IS_WRAP = type & $export.W - , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) - , expProto = exports[PROTOTYPE] - , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] - , key, own, out; - if(IS_GLOBAL)source = name; - for(key in source){ - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - if(own && key in exports)continue; - // export native or passed - out = own ? target[key] : source[key]; - // prevent global pollution for namespaces - exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] - // bind timers to global for call from export context - : IS_BIND && own ? ctx(out, global) - // wrap global constructors for prevent change them in library - : IS_WRAP && target[key] == out ? (function(C){ - var F = function(a, b, c){ - if(this instanceof C){ - switch(arguments.length){ - case 0: return new C; - case 1: return new C(a); - case 2: return new C(a, b); - } return new C(a, b, c); - } return C.apply(this, arguments); - }; - F[PROTOTYPE] = C[PROTOTYPE]; - return F; - // make static versions for prototype methods - })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% - if(IS_PROTO){ - (exports.virtual || (exports.virtual = {}))[key] = out; - // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% - if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); - } - } - }; - // type bitmap - $export.F = 1; // forced - $export.G = 2; // global - $export.S = 4; // static - $export.P = 8; // proto - $export.B = 16; // bind - $export.W = 32; // wrap - $export.U = 64; // safe - $export.R = 128; // real proto method for `library` - module.exports = $export; - -/***/ }, -/* 47 */ -/***/ function(module, exports, __webpack_require__) { - - // fallback for non-array-like ES3 and non-enumerable old V8 strings - var cof = __webpack_require__(95); - module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ - return cof(it) == 'String' ? it.split('') : Object(it); - }; - -/***/ }, -/* 48 */ -/***/ function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(93) - , IE8_DOM_DEFINE = __webpack_require__(101) - , toPrimitive = __webpack_require__(113) - , dP = Object.defineProperty; - - exports.f = __webpack_require__(16) ? Object.defineProperty : function defineProperty(O, P, Attributes){ - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if(IE8_DOM_DEFINE)try { - return dP(O, P, Attributes); - } catch(e){ /* empty */ } - if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); - if('value' in Attributes)O[P] = Attributes.value; - return O; - }; - -/***/ }, -/* 49 */ -/***/ function(module, exports) { - - // 7.1.4 ToInteger - var ceil = Math.ceil - , floor = Math.floor; - module.exports = function(it){ - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); - }; - -/***/ }, -/* 50 */ -/***/ function(module, exports, __webpack_require__) { - - // to indexed object, toObject with fallback for non-array-like ES3 strings - var IObject = __webpack_require__(47) - , defined = __webpack_require__(45); - module.exports = function(it){ - return IObject(defined(it)); - }; - -/***/ }, -/* 51 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = { "default": __webpack_require__(130), __esModule: true }; - -/***/ }, -/* 52 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = { "default": __webpack_require__(132), __esModule: true }; - -/***/ }, -/* 53 */ -/***/ function(module, exports) { - - "use strict"; - "use strict"; - - exports.__esModule = true; - - exports.default = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - }; - -/***/ }, -/* 54 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - "use strict"; - - exports.__esModule = true; - - var _defineProperty = __webpack_require__(125); - - var _defineProperty2 = _interopRequireDefault(_defineProperty); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - exports.default = function () { - function defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - (0, _defineProperty2.default)(target, descriptor.key, descriptor); - } - } - - return function (Constructor, protoProps, staticProps) { - if (protoProps) defineProperties(Constructor.prototype, protoProps); - if (staticProps) defineProperties(Constructor, staticProps); - return Constructor; - }; - }(); - -/***/ }, -/* 55 */ -/***/ function(module, exports) { - - /** - * Slice reference. - */ - - var slice = [].slice; - - /** - * Bind `obj` to `fn`. - * - * @param {Object} obj - * @param {Function|String} fn or string - * @return {Function} - * @api public - */ - - module.exports = function(obj, fn){ - if ('string' == typeof fn) fn = obj[fn]; - if ('function' != typeof fn) throw new Error('bind() requires a function'); - var args = slice.call(arguments, 2); - return function(){ - return fn.apply(obj, args.concat(slice.call(arguments))); - } - }; - - -/***/ }, -/* 56 */ -/***/ function(module, exports) { - - - /** - * Expose `Emitter`. - */ - - module.exports = Emitter; - - /** - * Initialize a new `Emitter`. - * - * @api public - */ - - function Emitter(obj) { - if (obj) return mixin(obj); - }; - - /** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - - function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; - } - - /** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.on = - Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; - }; - - /** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; - }; - - /** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.off = - Emitter.prototype.removeListener = - Emitter.prototype.removeAllListeners = - Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; - }; - - /** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - - Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks['$' + event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; - }; - - /** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - - Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; - }; - - /** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - - Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; - }; - - -/***/ }, -/* 57 */ -/***/ function(module, exports, __webpack_require__) { - - // getting tag from 19.1.3.6 Object.prototype.toString() - var cof = __webpack_require__(18) - , TAG = __webpack_require__(1)('toStringTag') - // ES3 wrong here - , ARG = cof(function(){ return arguments; }()) == 'Arguments'; - - // fallback for IE11 Script Access Denied error - var tryGet = function(it, key){ - try { - return it[key]; - } catch(e){ /* empty */ } - }; - - module.exports = function(it){ - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; - }; - -/***/ }, -/* 58 */ -/***/ function(module, exports) { - - // IE 8- don't enum bug keys - module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' - ).split(','); - -/***/ }, -/* 59 */ -/***/ function(module, exports) { - - module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; - } - }; - -/***/ }, -/* 60 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = __webpack_require__(2).document && document.documentElement; - -/***/ }, -/* 61 */ -/***/ function(module, exports, __webpack_require__) { - - module.exports = !__webpack_require__(6) && !__webpack_require__(59)(function(){ - return Object.defineProperty(__webpack_require__(28)('div'), 'a', {get: function(){ return 7; }}).a != 7; - }); - -/***/ }, -/* 62 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - 'use strict'; - var LIBRARY = __webpack_require__(63) - , $export = __webpack_require__(29) - , redefine = __webpack_require__(153) - , hide = __webpack_require__(8) - , has = __webpack_require__(11) - , Iterators = __webpack_require__(13) - , $iterCreate = __webpack_require__(141) - , setToStringTag = __webpack_require__(31) - , getPrototypeOf = __webpack_require__(148) - , ITERATOR = __webpack_require__(1)('iterator') - , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` - , FF_ITERATOR = '@@iterator' - , KEYS = 'keys' - , VALUES = 'values'; - - var returnThis = function(){ return this; }; - - module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ - $iterCreate(Constructor, NAME, next); - var getMethod = function(kind){ - if(!BUGGY && kind in proto)return proto[kind]; - switch(kind){ - case KEYS: return function keys(){ return new Constructor(this, kind); }; - case VALUES: return function values(){ return new Constructor(this, kind); }; - } return function entries(){ return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator' - , DEF_VALUES = DEFAULT == VALUES - , VALUES_BUG = false - , proto = Base.prototype - , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] - , $default = $native || getMethod(DEFAULT) - , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined - , $anyNative = NAME == 'Array' ? proto.entries || $native : $native - , methods, key, IteratorPrototype; - // Fix native - if($anyNative){ - IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); - if(IteratorPrototype !== Object.prototype){ - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if(DEF_VALUES && $native && $native.name !== VALUES){ - VALUES_BUG = true; - $default = function values(){ return $native.call(this); }; - } - // Define iterator - if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if(DEFAULT){ - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if(FORCED)for(key in methods){ - if(!(key in proto))redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; - }; - -/***/ }, -/* 63 */ -/***/ function(module, exports) { - - module.exports = true; - -/***/ }, -/* 64 */ -/***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(2) - , SHARED = '__core-js_shared__' - , store = global[SHARED] || (global[SHARED] = {}); - module.exports = function(key){ - return store[key] || (store[key] = {}); - }; - -/***/ }, -/* 65 */ -/***/ function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(10) - , invoke = __webpack_require__(137) - , html = __webpack_require__(60) - , cel = __webpack_require__(28) - , global = __webpack_require__(2) - , process = global.process - , setTask = global.setImmediate - , clearTask = global.clearImmediate - , MessageChannel = global.MessageChannel - , counter = 0 - , queue = {} - , ONREADYSTATECHANGE = 'onreadystatechange' - , defer, channel, port; - var run = function(){ - var id = +this; - if(queue.hasOwnProperty(id)){ - var fn = queue[id]; - delete queue[id]; - fn(); - } - }; - var listener = function(event){ - run.call(event.data); - }; - // Node.js 0.9+ & IE10+ has setImmediate, otherwise: - if(!setTask || !clearTask){ - setTask = function setImmediate(fn){ - var args = [], i = 1; - while(arguments.length > i)args.push(arguments[i++]); - queue[++counter] = function(){ - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id){ - delete queue[id]; - }; - // Node.js 0.8- - if(__webpack_require__(18)(process) == 'process'){ - defer = function(id){ - process.nextTick(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if(MessageChannel){ - channel = new MessageChannel; - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ - defer = function(id){ - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if(ONREADYSTATECHANGE in cel('script')){ - defer = function(id){ - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function(id){ - setTimeout(ctx(run, id, 1), 0); - }; - } - } - module.exports = { - set: setTask, - clear: clearTask - }; - -/***/ }, -/* 66 */ -/***/ function(module, exports, __webpack_require__) { - - // 7.1.15 ToLength - var toInteger = __webpack_require__(33) - , min = Math.min; - module.exports = function(it){ - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 - }; - -/***/ }, -/* 67 */ -/***/ function(module, exports, __webpack_require__) { - - // 7.1.1 ToPrimitive(input [, PreferredType]) - var isObject = __webpack_require__(12); - // instead of the ES6 spec version, we didn't implement @@toPrimitive case - // and the second argument - flag - preferred type is a string - module.exports = function(it, S){ - if(!isObject(it))return it; - var fn, val; - if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; - if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - throw TypeError("Can't convert object to primitive value"); - }; - -/***/ }, -/* 68 */ -/***/ function(module, exports) { - - var id = 0 - , px = Math.random(); - module.exports = function(key){ - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); - }; - -/***/ }, -/* 69 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies - */ - - var XMLHttpRequest = __webpack_require__(35); - var XHR = __webpack_require__(174); - var JSONP = __webpack_require__(173); - var websocket = __webpack_require__(175); - - /** - * Export transports. - */ - - exports.polling = polling; - exports.websocket = websocket; - - /** - * Polling transport polymorphic constructor. - * Decides on xhr vs jsonp based on feature detection. - * - * @api private - */ - - function polling(opts){ - var xhr; - var xd = false; - var xs = false; - var jsonp = false !== opts.jsonp; - - if (global.location) { - var isSSL = 'https:' == location.protocol; - var port = location.port; - - // some user agents have empty `location.port` - if (!port) { - port = isSSL ? 443 : 80; - } - - xd = opts.hostname != location.hostname || port != opts.port; - xs = opts.secure != isSSL; - } - - opts.xdomain = xd; - opts.xscheme = xs; - xhr = new XMLHttpRequest(opts); - - if ('open' in xhr && !opts.forceJSONP) { - return new XHR(opts); - } else { - if (!jsonp) throw new Error('JSONP disabled'); - return new JSONP(opts); - } - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) - -/***/ }, -/* 70 */ -/***/ function(module, exports, __webpack_require__) { - - /** - * Module dependencies. - */ - - var Transport = __webpack_require__(34); - var parseqs = __webpack_require__(39); - var parser = __webpack_require__(9); - var inherit = __webpack_require__(17); - var yeast = __webpack_require__(83); - var debug = __webpack_require__(3)('engine.io-client:polling'); - - /** - * Module exports. - */ - - module.exports = Polling; - - /** - * Is XHR2 supported? - */ - - var hasXHR2 = (function() { - var XMLHttpRequest = __webpack_require__(35); - var xhr = new XMLHttpRequest({ xdomain: false }); - return null != xhr.responseType; - })(); - - /** - * Polling interface. - * - * @param {Object} opts - * @api private - */ - - function Polling(opts){ - var forceBase64 = (opts && opts.forceBase64); - if (!hasXHR2 || forceBase64) { - this.supportsBinary = false; - } - Transport.call(this, opts); - } - - /** - * Inherits from Transport. - */ - - inherit(Polling, Transport); - - /** - * Transport name. - */ - - Polling.prototype.name = 'polling'; - - /** - * Opens the socket (triggers polling). We write a PING message to determine - * when the transport is open. - * - * @api private - */ - - Polling.prototype.doOpen = function(){ - this.poll(); - }; - - /** - * Pauses polling. - * - * @param {Function} callback upon buffers are flushed and transport is paused - * @api private - */ - - Polling.prototype.pause = function(onPause){ - var pending = 0; - var self = this; - - this.readyState = 'pausing'; - - function pause(){ - debug('paused'); - self.readyState = 'paused'; - onPause(); - } - - if (this.polling || !this.writable) { - var total = 0; - - if (this.polling) { - debug('we are currently polling - waiting to pause'); - total++; - this.once('pollComplete', function(){ - debug('pre-pause polling complete'); - --total || pause(); - }); - } - - if (!this.writable) { - debug('we are currently writing - waiting to pause'); - total++; - this.once('drain', function(){ - debug('pre-pause writing complete'); - --total || pause(); - }); - } - } else { - pause(); - } - }; - - /** - * Starts polling cycle. - * - * @api public - */ - - Polling.prototype.poll = function(){ - debug('polling'); - this.polling = true; - this.doPoll(); - this.emit('poll'); - }; - - /** - * Overloads onData to detect payloads. - * - * @api private - */ - - Polling.prototype.onData = function(data){ - var self = this; - debug('polling got data %s', data); - var callback = function(packet, index, total) { - // if its the first message we consider the transport open - if ('opening' == self.readyState) { - self.onOpen(); - } - - // if its a close packet, we close the ongoing requests - if ('close' == packet.type) { - self.onClose(); - return false; - } - - // otherwise bypass onData and handle the message - self.onPacket(packet); - }; - - // decode payload - parser.decodePayload(data, this.socket.binaryType, callback); - - // if an event did not trigger closing - if ('closed' != this.readyState) { - // if we got data we're not polling - this.polling = false; - this.emit('pollComplete'); - - if ('open' == this.readyState) { - this.poll(); - } else { - debug('ignoring poll - transport state "%s"', this.readyState); - } - } - }; - - /** - * For polling, send a close packet. - * - * @api private - */ - - Polling.prototype.doClose = function(){ - var self = this; - - function close(){ - debug('writing close packet'); - self.write([{ type: 'close' }]); - } - - if ('open' == this.readyState) { - debug('transport open - closing'); - close(); - } else { - // in case we're trying to close while - // handshaking is in progress (GH-164) - debug('transport not open - deferring close'); - this.once('open', close); - } - }; - - /** - * Writes a packets payload. - * - * @param {Array} data packets - * @param {Function} drain callback - * @api private - */ - - Polling.prototype.write = function(packets){ - var self = this; - this.writable = false; - var callbackfn = function() { - self.writable = true; - self.emit('drain'); - }; - - var self = this; - parser.encodePayload(packets, this.supportsBinary, function(data) { - self.doWrite(data, callbackfn); - }); - }; - - /** - * Generates uri for connection. - * - * @api private - */ - - Polling.prototype.uri = function(){ - var query = this.query || {}; - var schema = this.secure ? 'https' : 'http'; - var port = ''; - - // cache busting is forced - if (false !== this.timestampRequests) { - query[this.timestampParam] = yeast(); - } - - if (!this.supportsBinary && !query.sid) { - query.b64 = 1; - } - - query = parseqs.encode(query); - - // avoid port if default for schema - if (this.port && (('https' == schema && this.port != 443) || - ('http' == schema && this.port != 80))) { - port = ':' + this.port; - } - - // prepend ? to query - if (query.length) { - query = '?' + query; - } - - var ipv6 = this.hostname.indexOf(':') !== -1; - return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; - }; - - -/***/ }, -/* 71 */ -/***/ function(module, exports) { - - - var indexOf = [].indexOf; - - module.exports = function(arr, obj){ - if (indexOf) return arr.indexOf(obj); - for (var i = 0; i < arr.length; ++i) { - if (arr[i] === obj) return i; - } - return -1; - }; - -/***/ }, -/* 72 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(setImmediate, clearImmediate) {var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/* - * @name Lazy.js - * - * @fileOverview - * Lazy.js is a lazy evaluation library for JavaScript. - * - * This has been done before. For examples see: - * - * - [wu.js](http://fitzgen.github.io/wu.js/) - * - [Linq.js](http://linqjs.codeplex.com/) - * - [from.js](https://github.com/suckgamoni/fromjs/) - * - [IxJS](http://rx.codeplex.com/) - * - [sloth.js](http://rfw.name/sloth.js/) - * - * However, at least at present, Lazy.js is faster (on average) than any of - * those libraries. It is also more complete, with nearly all of the - * functionality of [Underscore](http://underscorejs.org/) and - * [Lo-Dash](http://lodash.com/). - * - * Finding your way around the code - * -------------------------------- - * - * At the heart of Lazy.js is the {@link Sequence} object. You create an initial - * sequence using {@link Lazy}, which can accept an array, object, or string. - * You can then "chain" together methods from this sequence, creating a new - * sequence with each call. - * - * Here's an example: - * - * var data = getReallyBigArray(); - * - * var statistics = Lazy(data) - * .map(transform) - * .filter(validate) - * .reduce(aggregate); - * - * {@link Sequence} is the foundation of other, more specific sequence types. - * - * An {@link ArrayLikeSequence} provides indexed access to its elements. - * - * An {@link ObjectLikeSequence} consists of key/value pairs. - * - * A {@link StringLikeSequence} is like a string (duh): actually, it is an - * {@link ArrayLikeSequence} whose elements happen to be characters. - * - * An {@link AsyncSequence} is special: it iterates over its elements - * asynchronously (so calling `each` generally begins an asynchronous loop and - * returns immediately). - * - * For more information - * -------------------- - * - * I wrote a blog post that explains a little bit more about Lazy.js, which you - * can read [here](http://philosopherdeveloper.com/posts/introducing-lazy-js.html). - * - * You can also [create an issue on GitHub](https://github.com/dtao/lazy.js/issues) - * if you have any issues with the library. I work through them eventually. - * - * [@dtao](https://github.com/dtao) - */ - - (function(root, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (typeof exports === 'object') { - module.exports = factory(); - } else { - root.Lazy = factory(); - } - })(this, function(context) { - /** - * Wraps an object and returns a {@link Sequence}. For `null` or `undefined`, - * simply returns an empty sequence (see {@link Lazy.strict} for a stricter - * implementation). - * - * - For **arrays**, Lazy will create a sequence comprising the elements in - * the array (an {@link ArrayLikeSequence}). - * - For **objects**, Lazy will create a sequence of key/value pairs - * (an {@link ObjectLikeSequence}). - * - For **strings**, Lazy will create a sequence of characters (a - * {@link StringLikeSequence}). - * - * @public - * @param {Array|Object|string} source An array, object, or string to wrap. - * @returns {Sequence} The wrapped lazy object. - * - * @exampleHelpers - * // Utility functions to provide to all examples - * function increment(x) { return x + 1; } - * function isEven(x) { return x % 2 === 0; } - * function isPositive(x) { return x > 0; } - * function isNegative(x) { return x < 0; } - * - * @examples - * Lazy([1, 2, 4]) // instanceof Lazy.ArrayLikeSequence - * Lazy({ foo: "bar" }) // instanceof Lazy.ObjectLikeSequence - * Lazy("hello, world!") // instanceof Lazy.StringLikeSequence - * Lazy() // sequence: [] - * Lazy(null) // sequence: [] - */ - function Lazy(source) { - if (source instanceof Array) { - return new ArrayWrapper(source); - - } else if (typeof source === "string") { - return new StringWrapper(source); - - } else if (source instanceof Sequence) { - return source; - } - - if (Lazy.extensions) { - var extensions = Lazy.extensions, length = extensions.length, result; - while (!result && length--) { - result = extensions[length](source); - } - if (result) { - return result; - } - } - - return new ObjectWrapper(source); - } - - Lazy.VERSION = '0.4.2'; - - /*** Utility methods of questionable value ***/ - - Lazy.noop = function noop() {}; - Lazy.identity = function identity(x) { return x; }; - - /** - * Provides a stricter version of {@link Lazy} which throws an error when - * attempting to wrap `null`, `undefined`, or numeric or boolean values as a - * sequence. - * - * @public - * @returns {Function} A stricter version of the {@link Lazy} helper function. - * - * @examples - * var Strict = Lazy.strict(); - * - * Strict() // throws - * Strict(null) // throws - * Strict(true) // throws - * Strict(5) // throws - * Strict([1, 2, 3]) // instanceof Lazy.ArrayLikeSequence - * Strict({ foo: "bar" }) // instanceof Lazy.ObjectLikeSequence - * Strict("hello, world!") // instanceof Lazy.StringLikeSequence - * - * // Let's also ensure the static functions are still there. - * Strict.range(3) // sequence: [0, 1, 2] - * Strict.generate(Date.now) // instanceof Lazy.GeneratedSequence - */ - Lazy.strict = function strict() { - function StrictLazy(source) { - if (source == null) { - throw new Error("You cannot wrap null or undefined using Lazy."); - } - - if (typeof source === "number" || typeof source === "boolean") { - throw new Error("You cannot wrap primitive values using Lazy."); - } - - return Lazy(source); - }; - - Lazy(Lazy).each(function(property, name) { - StrictLazy[name] = property; - }); - - return StrictLazy; - }; - - /** - * The `Sequence` object provides a unified API encapsulating the notion of - * zero or more consecutive elements in a collection, stream, etc. - * - * Lazy evaluation - * --------------- - * - * Generally speaking, creating a sequence should not be an expensive operation, - * and should not iterate over an underlying source or trigger any side effects. - * This means that chaining together methods that return sequences incurs only - * the cost of creating the `Sequence` objects themselves and not the cost of - * iterating an underlying data source multiple times. - * - * The following code, for example, creates 4 sequences and does nothing with - * `source`: - * - * var seq = Lazy(source) // 1st sequence - * .map(func) // 2nd - * .filter(pred) // 3rd - * .reverse(); // 4th - * - * Lazy's convention is to hold off on iterating or otherwise *doing* anything - * (aside from creating `Sequence` objects) until you call `each`: - * - * seq.each(function(x) { console.log(x); }); - * - * Defining custom sequences - * ------------------------- - * - * Defining your own type of sequence is relatively simple: - * - * 1. Pass a *method name* and an object containing *function overrides* to - * {@link Sequence.define}. If the object includes a function called `init`, - * this function will be called upon initialization. - * 2. The object should include at least either a `getIterator` method or an - * `each` method. The former supports both asynchronous and synchronous - * iteration, but is slightly more cumbersome to implement. The latter - * supports synchronous iteration and can be automatically implemented in - * terms of the former. You can also implement both if you want, e.g. to - * optimize performance. For more info, see {@link Iterator} and - * {@link AsyncSequence}. - * - * As a trivial example, the following code defines a new method, `sample`, - * which randomly may or may not include each element from its parent. - * - * Lazy.Sequence.define("sample", { - * each: function(fn) { - * return this.parent.each(function(e) { - * // 50/50 chance of including this element. - * if (Math.random() > 0.5) { - * return fn(e); - * } - * }); - * } - * }); - * - * (Of course, the above could also easily have been implemented using - * {@link #filter} instead of creating a custom sequence. But I *did* say this - * was a trivial example, to be fair.) - * - * Now it will be possible to create this type of sequence from any parent - * sequence by calling the method name you specified. In other words, you can - * now do this: - * - * Lazy(arr).sample(); - * Lazy(arr).map(func).sample(); - * Lazy(arr).map(func).filter(pred).sample(); - * - * Etc., etc. - * - * @public - * @constructor - */ - function Sequence() {} - - /** - * Create a new constructor function for a type inheriting from `Sequence`. - * - * @public - * @param {string|Array.} methodName The name(s) of the method(s) to be - * used for constructing the new sequence. The method will be attached to - * the `Sequence` prototype so that it can be chained with any other - * sequence methods, like {@link #map}, {@link #filter}, etc. - * @param {Object} overrides An object containing function overrides for this - * new sequence type. **Must** include either `getIterator` or `each` (or - * both). *May* include an `init` method as well. For these overrides, - * `this` will be the new sequence, and `this.parent` will be the base - * sequence from which the new sequence was constructed. - * @returns {Function} A constructor for a new type inheriting from `Sequence`. - * - * @examples - * // This sequence type logs every element to the specified logger as it - * // iterates over it. - * Lazy.Sequence.define("verbose", { - * init: function(logger) { - * this.logger = logger; - * }, - * - * each: function(fn) { - * var logger = this.logger; - * return this.parent.each(function(e, i) { - * logger(e); - * return fn(e, i); - * }); - * } - * }); - * - * Lazy([1, 2, 3]).verbose(logger).each(Lazy.noop) // calls logger 3 times - */ - Sequence.define = function define(methodName, overrides) { - if (!overrides || (!overrides.getIterator && !overrides.each)) { - throw new Error("A custom sequence must implement *at least* getIterator or each!"); - } - - return defineSequenceType(Sequence, methodName, overrides); - }; - - /** - * Gets the number of elements in the sequence. In some cases, this may - * require eagerly evaluating the sequence. - * - * @public - * @returns {number} The number of elements in the sequence. - * - * @examples - * Lazy([1, 2, 3]).size(); // => 3 - * Lazy([1, 2]).map(Lazy.identity).size(); // => 2 - * Lazy([1, 2, 3]).reject(isEven).size(); // => 2 - * Lazy([1, 2, 3]).take(1).size(); // => 1 - * Lazy({ foo: 1, bar: 2 }).size(); // => 2 - * Lazy('hello').size(); // => 5 - */ - Sequence.prototype.size = function size() { - return this.getIndex().length(); - }; - - /** - * Creates an {@link Iterator} object with two methods, `moveNext` -- returning - * true or false -- and `current` -- returning the current value. - * - * This method is used when asynchronously iterating over sequences. Any type - * inheriting from `Sequence` must implement this method or it can't support - * asynchronous iteration. - * - * Note that **this method is not intended to be used directly by application - * code.** Rather, it is intended as a means for implementors to potentially - * define custom sequence types that support either synchronous or - * asynchronous iteration. - * - * @public - * @returns {Iterator} An iterator object. - * - * @examples - * var iterator = Lazy([1, 2]).getIterator(); - * - * iterator.moveNext(); // => true - * iterator.current(); // => 1 - * iterator.moveNext(); // => true - * iterator.current(); // => 2 - * iterator.moveNext(); // => false - */ - Sequence.prototype.getIterator = function getIterator() { - return new Iterator(this); - }; - - /** - * Gets the root sequence underlying the current chain of sequences. - */ - Sequence.prototype.root = function root() { - return this.parent.root(); - }; - - /** - * Whether or not the current sequence is an asynchronous one. This is more - * accurate than checking `instanceof {@link AsyncSequence}` because, for - * example, `Lazy([1, 2, 3]).async().map(Lazy.identity)` returns a sequence - * that iterates asynchronously even though it's not an instance of - * `AsyncSequence`. - * - * @returns {boolean} Whether or not the current sequence is an asynchronous one. - */ - Sequence.prototype.isAsync = function isAsync() { - return this.parent ? this.parent.isAsync() : false; - }; - - /** - * Evaluates the sequence and produces the appropriate value (an array in most - * cases, an object for {@link ObjectLikeSequence}s or a string for - * {@link StringLikeSequence}s). - * - * @returns {Array|string|Object} The value resulting from fully evaluating - * the sequence. - */ - Sequence.prototype.value = function value() { - return this.toArray(); - }; - - /** - * Applies the current transformation chain to a given source, returning the - * resulting value. - * - * @examples - * var sequence = Lazy([]) - * .map(function(x) { return x * -1; }) - * .filter(function(x) { return x % 2 === 0; }); - * - * sequence.apply([1, 2, 3, 4]); // => [-2, -4] - */ - Sequence.prototype.apply = function apply(source) { - var root = this.root(), - previousSource = root.source, - result; - - try { - root.source = source; - result = this.value(); - } finally { - root.source = previousSource; - } - - return result; - }; - - /** - * The Iterator object provides an API for iterating over a sequence. - * - * The purpose of the `Iterator` type is mainly to offer an agnostic way of - * iterating over a sequence -- either synchronous (i.e. with a `while` loop) - * or asynchronously (with recursive calls to either `setTimeout` or --- if - * available --- `setImmediate`). It is not intended to be used directly by - * application code. - * - * @public - * @constructor - * @param {Sequence} sequence The sequence to iterate over. - */ - function Iterator(sequence) { - this.sequence = sequence; - this.index = -1; - } - - /** - * Gets the current item this iterator is pointing to. - * - * @public - * @returns {*} The current item. - */ - Iterator.prototype.current = function current() { - return this.cachedIndex && this.cachedIndex.get(this.index); - }; - - /** - * Moves the iterator to the next item in a sequence, if possible. - * - * @public - * @returns {boolean} True if the iterator is able to move to a new item, or else - * false. - */ - Iterator.prototype.moveNext = function moveNext() { - var cachedIndex = this.cachedIndex; - - if (!cachedIndex) { - cachedIndex = this.cachedIndex = this.sequence.getIndex(); - } - - if (this.index >= cachedIndex.length() - 1) { - return false; - } - - ++this.index; - return true; - }; - - /** - * Creates an array snapshot of a sequence. - * - * Note that for indefinite sequences, this method may raise an exception or - * (worse) cause the environment to hang. - * - * @public - * @returns {Array} An array containing the current contents of the sequence. - * - * @examples - * Lazy([1, 2, 3]).toArray() // => [1, 2, 3] - */ - Sequence.prototype.toArray = function toArray() { - return this.reduce(function(arr, element) { - arr.push(element); - return arr; - }, []); - }; - - /** - * Provides an indexed view into the sequence. - * - * For sequences that are already indexed, this will simply return the - * sequence. For non-indexed sequences, this will eagerly evaluate the - * sequence. - * - * @returns {ArrayLikeSequence} A sequence containing the current contents of - * the sequence. - * - * @examples - * Lazy([1, 2, 3]).filter(isEven) // instanceof Lazy.Sequence - * Lazy([1, 2, 3]).filter(isEven).getIndex() // instanceof Lazy.ArrayLikeSequence - */ - Sequence.prototype.getIndex = function getIndex() { - return new ArrayWrapper(this.toArray()); - }; - - /** - * Returns the element at the specified index. Note that, for sequences that - * are not {@link ArrayLikeSequence}s, this may require partially evaluating - * the sequence, iterating to reach the result. (In other words for such - * sequences this method is not O(1).) - * - * @public - * @param {number} i The index to access. - * @returns {*} The element. - * - */ - Sequence.prototype.get = function get(i) { - var element; - this.each(function(e, index) { - if (index === i) { - element = e; - return false; - } - }); - return element; - }; - - /** - * Provides an indexed, memoized view into the sequence. This will cache the - * result whenever the sequence is first iterated, so that subsequent - * iterations will access the same element objects. - * - * @public - * @returns {ArrayLikeSequence} An indexed, memoized sequence containing this - * sequence's elements, cached after the first iteration. - * - * @example - * function createObject() { return new Object(); } - * - * var plain = Lazy.generate(createObject, 10), - * memoized = Lazy.generate(createObject, 10).memoize(); - * - * plain.toArray()[0] === plain.toArray()[0]; // => false - * memoized.toArray()[0] === memoized.toArray()[0]; // => true - */ - Sequence.prototype.memoize = function memoize() { - return new MemoizedSequence(this); - }; - - /** - * @constructor - */ - function MemoizedSequence(parent) { - this.parent = parent; - } - - // MemoizedSequence needs to have its prototype set up after ArrayLikeSequence - - /** - * Creates an object from a sequence of key/value pairs. - * - * @public - * @returns {Object} An object with keys and values corresponding to the pairs - * of elements in the sequence. - * - * @examples - * var details = [ - * ["first", "Dan"], - * ["last", "Tao"], - * ["age", 29] - * ]; - * - * Lazy(details).toObject() // => { first: "Dan", last: "Tao", age: 29 } - */ - Sequence.prototype.toObject = function toObject() { - return this.reduce(function(object, pair) { - object[pair[0]] = pair[1]; - return object; - }, {}); - }; - - /** - * Iterates over this sequence and executes a function for every element. - * - * @public - * @aka forEach - * @param {Function} fn The function to call on each element in the sequence. - * Return false from the function to end the iteration. - * @returns {boolean} `true` if the iteration evaluated the entire sequence, - * or `false` if iteration was ended early. - * - * @examples - * Lazy([1, 2, 3, 4]).each(fn) // calls fn 4 times - */ - Sequence.prototype.each = function each(fn) { - var iterator = this.getIterator(), - i = -1; - - while (iterator.moveNext()) { - if (fn(iterator.current(), ++i) === false) { - return false; - } - } - - return true; - }; - - Sequence.prototype.forEach = function forEach(fn) { - return this.each(fn); - }; - - /** - * Creates a new sequence whose values are calculated by passing this sequence's - * elements through some mapping function. - * - * @public - * @aka collect - * @param {Function} mapFn The mapping function used to project this sequence's - * elements onto a new sequence. This function takes up to two arguments: - * the element, and the current index. - * @returns {Sequence} The new sequence. - * - * @examples - * function addIndexToValue(e, i) { return e + i; } - * - * Lazy([]).map(increment) // sequence: [] - * Lazy([1, 2, 3]).map(increment) // sequence: [2, 3, 4] - * Lazy([1, 2, 3]).map(addIndexToValue) // sequence: [1, 3, 5] - * - * @benchmarks - * function increment(x) { return x + 1; } - * - * var smArr = Lazy.range(10).toArray(), - * lgArr = Lazy.range(100).toArray(); - * - * Lazy(smArr).map(increment).each(Lazy.noop) // lazy - 10 elements - * Lazy(lgArr).map(increment).each(Lazy.noop) // lazy - 100 elements - * _.each(_.map(smArr, increment), _.noop) // lodash - 10 elements - * _.each(_.map(lgArr, increment), _.noop) // lodash - 100 elements - */ - Sequence.prototype.map = function map(mapFn) { - return new MappedSequence(this, createCallback(mapFn)); - }; - - Sequence.prototype.collect = function collect(mapFn) { - return this.map(mapFn); - }; - - /** - * @constructor - */ - function MappedSequence(parent, mapFn) { - this.parent = parent; - this.mapFn = mapFn; - } - - MappedSequence.prototype = new Sequence(); - - MappedSequence.prototype.getIterator = function getIterator() { - return new MappingIterator(this.parent, this.mapFn); - }; - - MappedSequence.prototype.each = function each(fn) { - var mapFn = this.mapFn; - return this.parent.each(function(e, i) { - return fn(mapFn(e, i), i); - }); - }; - - /** - * @constructor - */ - function MappingIterator(sequence, mapFn) { - this.iterator = sequence.getIterator(); - this.mapFn = mapFn; - this.index = -1; - } - - MappingIterator.prototype.current = function current() { - return this.mapFn(this.iterator.current(), this.index); - }; - - MappingIterator.prototype.moveNext = function moveNext() { - if (this.iterator.moveNext()) { - ++this.index; - return true; - } - - return false; - }; - - /** - * Creates a new sequence whose values are calculated by accessing the specified - * property from each element in this sequence. - * - * @public - * @param {string} propertyName The name of the property to access for every - * element in this sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * var people = [ - * { first: "Dan", last: "Tao" }, - * { first: "Bob", last: "Smith" } - * ]; - * - * Lazy(people).pluck("last") // sequence: ["Tao", "Smith"] - */ - Sequence.prototype.pluck = function pluck(property) { - return this.map(property); - }; - - /** - * Creates a new sequence whose values are calculated by invoking the specified - * function on each element in this sequence. - * - * @public - * @param {string} methodName The name of the method to invoke for every element - * in this sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * function Person(first, last) { - * this.fullName = function fullName() { - * return first + " " + last; - * }; - * } - * - * var people = [ - * new Person("Dan", "Tao"), - * new Person("Bob", "Smith") - * ]; - * - * Lazy(people).invoke("fullName") // sequence: ["Dan Tao", "Bob Smith"] - */ - Sequence.prototype.invoke = function invoke(methodName) { - return this.map(function(e) { - return e[methodName](); - }); - }; - - /** - * Creates a new sequence whose values are the elements of this sequence which - * satisfy the specified predicate. - * - * @public - * @aka select - * @param {Function} filterFn The predicate to call on each element in this - * sequence, which returns true if the element should be included. - * @returns {Sequence} The new sequence. - * - * @examples - * var numbers = [1, 2, 3, 4, 5, 6]; - * - * Lazy(numbers).filter(isEven) // sequence: [2, 4, 6] - * - * @benchmarks - * function isEven(x) { return x % 2 === 0; } - * - * var smArr = Lazy.range(10).toArray(), - * lgArr = Lazy.range(100).toArray(); - * - * Lazy(smArr).filter(isEven).each(Lazy.noop) // lazy - 10 elements - * Lazy(lgArr).filter(isEven).each(Lazy.noop) // lazy - 100 elements - * _.each(_.filter(smArr, isEven), _.noop) // lodash - 10 elements - * _.each(_.filter(lgArr, isEven), _.noop) // lodash - 100 elements - */ - Sequence.prototype.filter = function filter(filterFn) { - return new FilteredSequence(this, createCallback(filterFn)); - }; - - Sequence.prototype.select = function select(filterFn) { - return this.filter(filterFn); - }; - - /** - * @constructor - */ - function FilteredSequence(parent, filterFn) { - this.parent = parent; - this.filterFn = filterFn; - } - - FilteredSequence.prototype = new Sequence(); - - FilteredSequence.prototype.getIterator = function getIterator() { - return new FilteringIterator(this.parent, this.filterFn); - }; - - FilteredSequence.prototype.each = function each(fn) { - var filterFn = this.filterFn, - j = 0; - - return this.parent.each(function(e, i) { - if (filterFn(e, i)) { - return fn(e, j++); - } - }); - }; - - FilteredSequence.prototype.reverse = function reverse() { - return this.parent.reverse().filter(this.filterFn); - }; - - /** - * @constructor - */ - function FilteringIterator(sequence, filterFn) { - this.iterator = sequence.getIterator(); - this.filterFn = filterFn; - this.index = 0; - } - - FilteringIterator.prototype.current = function current() { - return this.value; - }; - - FilteringIterator.prototype.moveNext = function moveNext() { - var iterator = this.iterator, - filterFn = this.filterFn, - value; - - while (iterator.moveNext()) { - value = iterator.current(); - if (filterFn(value, this.index++)) { - this.value = value; - return true; - } - } - - this.value = undefined; - return false; - }; - - /** - * Creates a new sequence whose values exclude the elements of this sequence - * identified by the specified predicate. - * - * @public - * @param {Function} rejectFn The predicate to call on each element in this - * sequence, which returns true if the element should be omitted. - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([1, 2, 3, 4, 5]).reject(isEven) // sequence: [1, 3, 5] - * Lazy([{ foo: 1 }, { bar: 2 }]).reject('foo') // sequence: [{ bar: 2 }] - * Lazy([{ foo: 1 }, { foo: 2 }]).reject({ foo: 2 }) // sequence: [{ foo: 1 }] - */ - Sequence.prototype.reject = function reject(rejectFn) { - rejectFn = createCallback(rejectFn); - return this.filter(function(e) { return !rejectFn(e); }); - }; - - /** - * Creates a new sequence whose values have the specified type, as determined - * by the `typeof` operator. - * - * @public - * @param {string} type The type of elements to include from the underlying - * sequence, i.e. where `typeof [element] === [type]`. - * @returns {Sequence} The new sequence, comprising elements of the specified - * type. - * - * @examples - * Lazy([1, 2, 'foo', 'bar']).ofType('number') // sequence: [1, 2] - * Lazy([1, 2, 'foo', 'bar']).ofType('string') // sequence: ['foo', 'bar'] - * Lazy([1, 2, 'foo', 'bar']).ofType('boolean') // sequence: [] - */ - Sequence.prototype.ofType = function ofType(type) { - return this.filter(function(e) { return typeof e === type; }); - }; - - /** - * Creates a new sequence whose values are the elements of this sequence with - * property names and values matching those of the specified object. - * - * @public - * @param {Object} properties The properties that should be found on every - * element that is to be included in this sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * var people = [ - * { first: "Dan", last: "Tao" }, - * { first: "Bob", last: "Smith" } - * ]; - * - * Lazy(people).where({ first: "Dan" }) // sequence: [{ first: "Dan", last: "Tao" }] - * - * @benchmarks - * var animals = ["dog", "cat", "mouse", "horse", "pig", "snake"]; - * - * Lazy(animals).where({ length: 3 }).each(Lazy.noop) // lazy - * _.each(_.where(animals, { length: 3 }), _.noop) // lodash - */ - Sequence.prototype.where = function where(properties) { - return this.filter(properties); - }; - - /** - * Creates a new sequence with the same elements as this one, but to be iterated - * in the opposite order. - * - * Note that in some (but not all) cases, the only way to create such a sequence - * may require iterating the entire underlying source when `each` is called. - * - * @public - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([1, 2, 3]).reverse() // sequence: [3, 2, 1] - * Lazy([]).reverse() // sequence: [] - */ - Sequence.prototype.reverse = function reverse() { - return new ReversedSequence(this); - }; - - /** - * @constructor - */ - function ReversedSequence(parent) { - this.parent = parent; - } - - ReversedSequence.prototype = new Sequence(); - - ReversedSequence.prototype.getIterator = function getIterator() { - return new ReversedIterator(this.parent); - }; - - /** - * @constuctor - */ - function ReversedIterator(sequence) { - this.sequence = sequence; - } - - ReversedIterator.prototype.current = function current() { - return this.getIndex().get(this.index); - }; - - ReversedIterator.prototype.moveNext = function moveNext() { - var index = this.getIndex(), - length = index.length(); - - if (typeof this.index === "undefined") { - this.index = length; - } - - return (--this.index >= 0); - }; - - ReversedIterator.prototype.getIndex = function getIndex() { - if (!this.cachedIndex) { - this.cachedIndex = this.sequence.getIndex(); - } - - return this.cachedIndex; - }; - - /** - * Creates a new sequence with all of the elements of this one, plus those of - * the given array(s). - * - * @public - * @param {...*} var_args One or more values (or arrays of values) to use for - * additional items after this sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * var left = [1, 2, 3]; - * var right = [4, 5, 6]; - * - * Lazy(left).concat(right) // sequence: [1, 2, 3, 4, 5, 6] - * Lazy(left).concat(Lazy(right)) // sequence: [1, 2, 3, 4, 5, 6] - * Lazy(left).concat(right, [7, 8]) // sequence: [1, 2, 3, 4, 5, 6, 7, 8] - */ - Sequence.prototype.concat = function concat(var_args) { - return new ConcatenatedSequence(this, arraySlice.call(arguments, 0)); - }; - - /** - * @constructor - */ - function ConcatenatedSequence(parent, arrays) { - this.parent = parent; - this.arrays = arrays; - } - - ConcatenatedSequence.prototype = new Sequence(); - - ConcatenatedSequence.prototype.each = function each(fn) { - var done = false, - i = 0; - - this.parent.each(function(e) { - if (fn(e, i++) === false) { - done = true; - return false; - } - }); - - if (!done) { - Lazy(this.arrays).flatten().each(function(e) { - if (fn(e, i++) === false) { - return false; - } - }); - } - }; - - /** - * Creates a new sequence comprising the first N elements from this sequence, OR - * (if N is `undefined`) simply returns the first element of this sequence. - * - * @public - * @aka head, take - * @param {number=} count The number of elements to take from this sequence. If - * this value exceeds the length of the sequence, the resulting sequence - * will be essentially the same as this one. - * @returns {*} The new sequence (or the first element from this sequence if - * no count was given). - * - * @examples - * function powerOfTwo(exp) { - * return Math.pow(2, exp); - * } - * - * Lazy.generate(powerOfTwo).first() // => 1 - * Lazy.generate(powerOfTwo).first(5) // sequence: [1, 2, 4, 8, 16] - * Lazy.generate(powerOfTwo).skip(2).first() // => 4 - * Lazy.generate(powerOfTwo).skip(2).first(2) // sequence: [4, 8] - */ - Sequence.prototype.first = function first(count) { - if (typeof count === "undefined") { - return getFirst(this); - } - return new TakeSequence(this, count); - }; - - Sequence.prototype.head = - Sequence.prototype.take = function (count) { - return this.first(count); - }; - - /** - * @constructor - */ - function TakeSequence(parent, count) { - this.parent = parent; - this.count = count; - } - - TakeSequence.prototype = new Sequence(); - - TakeSequence.prototype.getIterator = function getIterator() { - return new TakeIterator(this.parent, this.count); - }; - - TakeSequence.prototype.each = function each(fn) { - var count = this.count, - i = 0; - - var result; - var handle = this.parent.each(function(e) { - if (i < count) { result = fn(e, i++); } - if (i >= count) { return false; } - return result; - }); - - if (handle instanceof AsyncHandle) { - return handle; - } - - return i === count && result !== false; - }; - - /** - * @constructor - */ - function TakeIterator(sequence, count) { - this.iterator = sequence.getIterator(); - this.count = count; - } - - TakeIterator.prototype.current = function current() { - return this.iterator.current(); - }; - - TakeIterator.prototype.moveNext = function moveNext() { - return ((--this.count >= 0) && this.iterator.moveNext()); - }; - - /** - * Creates a new sequence comprising the elements from the head of this sequence - * that satisfy some predicate. Once an element is encountered that doesn't - * satisfy the predicate, iteration will stop. - * - * @public - * @param {Function} predicate - * @returns {Sequence} The new sequence - * - * @examples - * function lessThan(x) { - * return function(y) { - * return y < x; - * }; - * } - * - * Lazy([1, 2, 3, 4]).takeWhile(lessThan(3)) // sequence: [1, 2] - * Lazy([1, 2, 3, 4]).takeWhile(lessThan(0)) // sequence: [] - */ - Sequence.prototype.takeWhile = function takeWhile(predicate) { - return new TakeWhileSequence(this, predicate); - }; - - /** - * @constructor - */ - function TakeWhileSequence(parent, predicate) { - this.parent = parent; - this.predicate = predicate; - } - - TakeWhileSequence.prototype = new Sequence(); - - TakeWhileSequence.prototype.each = function each(fn) { - var predicate = this.predicate, - finished = false, - j = 0; - - var result = this.parent.each(function(e, i) { - if (!predicate(e, i)) { - finished = true; - return false; - } - - return fn(e, j++); - }); - - if (result instanceof AsyncHandle) { - return result; - } - - return finished; - }; - - /** - * Creates a new sequence comprising all but the last N elements of this - * sequence. - * - * @public - * @param {number=} count The number of items to omit from the end of the - * sequence (defaults to 1). - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([1, 2, 3, 4]).initial() // sequence: [1, 2, 3] - * Lazy([1, 2, 3, 4]).initial(2) // sequence: [1, 2] - * Lazy([1, 2, 3]).filter(Lazy.identity).initial() // sequence: [1, 2] - */ - Sequence.prototype.initial = function initial(count) { - return new InitialSequence(this, count); - }; - - function InitialSequence(parent, count) { - this.parent = parent; - this.count = typeof count === "number" ? count : 1; - } - - InitialSequence.prototype = new Sequence(); - - InitialSequence.prototype.each = function each(fn) { - var index = this.parent.getIndex(); - return index.take(index.length() - this.count).each(fn); - }; - - /** - * Creates a new sequence comprising the last N elements of this sequence, OR - * (if N is `undefined`) simply returns the last element of this sequence. - * - * @public - * @param {number=} count The number of items to take from the end of the - * sequence. - * @returns {*} The new sequence (or the last element from this sequence - * if no count was given). - * - * @examples - * Lazy([1, 2, 3]).last() // => 3 - * Lazy([1, 2, 3]).last(2) // sequence: [2, 3] - * Lazy([1, 2, 3]).filter(isEven).last(2) // sequence: [2] - */ - Sequence.prototype.last = function last(count) { - if (typeof count === "undefined") { - return this.reverse().first(); - } - return this.reverse().take(count).reverse(); - }; - - /** - * Returns the first element in this sequence with property names and values - * matching those of the specified object. - * - * @public - * @param {Object} properties The properties that should be found on some - * element in this sequence. - * @returns {*} The found element, or `undefined` if none exists in this - * sequence. - * - * @examples - * var words = ["foo", "bar"]; - * - * Lazy(words).findWhere({ 0: "f" }); // => "foo" - * Lazy(words).findWhere({ 0: "z" }); // => undefined - */ - Sequence.prototype.findWhere = function findWhere(properties) { - return this.where(properties).first(); - }; - - /** - * Creates a new sequence comprising all but the first N elements of this - * sequence. - * - * @public - * @aka skip, tail, rest - * @param {number=} count The number of items to omit from the beginning of the - * sequence (defaults to 1). - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([1, 2, 3, 4]).rest() // sequence: [2, 3, 4] - * Lazy([1, 2, 3, 4]).rest(0) // sequence: [1, 2, 3, 4] - * Lazy([1, 2, 3, 4]).rest(2) // sequence: [3, 4] - * Lazy([1, 2, 3, 4]).rest(5) // sequence: [] - */ - Sequence.prototype.rest = function rest(count) { - return new DropSequence(this, count); - }; - - Sequence.prototype.skip = - Sequence.prototype.tail = - Sequence.prototype.drop = function drop(count) { - return this.rest(count); - }; - - /** - * @constructor - */ - function DropSequence(parent, count) { - this.parent = parent; - this.count = typeof count === "number" ? count : 1; - } - - DropSequence.prototype = new Sequence(); - - DropSequence.prototype.each = function each(fn) { - var count = this.count, - dropped = 0, - i = 0; - - return this.parent.each(function(e) { - if (dropped++ < count) { return; } - return fn(e, i++); - }); - }; - - /** - * Creates a new sequence comprising the elements from this sequence *after* - * those that satisfy some predicate. The sequence starts with the first - * element that does not match the predicate. - * - * @public - * @aka skipWhile - * @param {Function} predicate - * @returns {Sequence} The new sequence - */ - Sequence.prototype.dropWhile = function dropWhile(predicate) { - return new DropWhileSequence(this, predicate); - }; - - Sequence.prototype.skipWhile = function skipWhile(predicate) { - return this.dropWhile(predicate); - }; - - /** - * @constructor - */ - function DropWhileSequence(parent, predicate) { - this.parent = parent; - this.predicate = predicate; - } - - DropWhileSequence.prototype = new Sequence(); - - DropWhileSequence.prototype.each = function each(fn) { - var predicate = this.predicate, - done = false; - - return this.parent.each(function(e) { - if (!done) { - if (predicate(e)) { - return; - } - - done = true; - } - - return fn(e); - }); - }; - - /** - * Creates a new sequence with the same elements as this one, but ordered - * using the specified comparison function. - * - * This has essentially the same behavior as calling - * [`Array#sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), - * but obviously instead of modifying the collection it returns a new - * {@link Sequence} object. - * - * @public - * @param {Function=} sortFn The function used to compare elements in the - * sequence. The function will be passed two elements and should return: - * - 1 if the first is greater - * - -1 if the second is greater - * - 0 if the two values are the same - * @param {boolean} descending Whether or not the resulting sequence should be - * in descending order (defaults to `false`). - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([5, 10, 1]).sort() // sequence: [1, 5, 10] - * Lazy(['foo', 'bar']).sort() // sequence: ['bar', 'foo'] - * Lazy(['b', 'c', 'a']).sort(null, true) // sequence: ['c', 'b', 'a'] - * Lazy([5, 10, 1]).sort(null, true) // sequence: [10, 5, 1] - * - * // Sorting w/ custom comparison function - * Lazy(['a', 'ab', 'aa', 'ba', 'b', 'abc']).sort(function compare(x, y) { - * if (x.length && (x.length !== y.length)) { return compare(x.length, y.length); } - * if (x === y) { return 0; } - * return x > y ? 1 : -1; - * }); - * // => sequence: ['a', 'b', 'aa', 'ab', 'ba', 'abc'] - */ - Sequence.prototype.sort = function sort(sortFn, descending) { - sortFn || (sortFn = compare); - if (descending) { sortFn = reverseArguments(sortFn); } - return new SortedSequence(this, sortFn); - }; - - /** - * Creates a new sequence with the same elements as this one, but ordered by - * the results of the given function. - * - * You can pass: - * - * - a *string*, to sort by the named property - * - a function, to sort by the result of calling the function on each element - * - * @public - * @param {Function} sortFn The function to call on the elements in this - * sequence, in order to sort them. - * @param {boolean} descending Whether or not the resulting sequence should be - * in descending order (defaults to `false`). - * @returns {Sequence} The new sequence. - * - * @examples - * function population(country) { - * return country.pop; - * } - * - * function area(country) { - * return country.sqkm; - * } - * - * var countries = [ - * { name: "USA", pop: 320000000, sqkm: 9600000 }, - * { name: "Brazil", pop: 194000000, sqkm: 8500000 }, - * { name: "Nigeria", pop: 174000000, sqkm: 924000 }, - * { name: "China", pop: 1350000000, sqkm: 9700000 }, - * { name: "Russia", pop: 143000000, sqkm: 17000000 }, - * { name: "Australia", pop: 23000000, sqkm: 7700000 } - * ]; - * - * Lazy(countries).sortBy(population).last(3).pluck('name') // sequence: ["Brazil", "USA", "China"] - * Lazy(countries).sortBy(area).last(3).pluck('name') // sequence: ["USA", "China", "Russia"] - * Lazy(countries).sortBy(area, true).first(3).pluck('name') // sequence: ["Russia", "China", "USA"] - * - * @benchmarks - * var randoms = Lazy.generate(Math.random).take(100).toArray(); - * - * Lazy(randoms).sortBy(Lazy.identity).each(Lazy.noop) // lazy - * _.each(_.sortBy(randoms, Lazy.identity), _.noop) // lodash - */ - Sequence.prototype.sortBy = function sortBy(sortFn, descending) { - sortFn = createComparator(sortFn); - if (descending) { sortFn = reverseArguments(sortFn); } - return new SortedSequence(this, sortFn); - }; - - /** - * @constructor - */ - function SortedSequence(parent, sortFn) { - this.parent = parent; - this.sortFn = sortFn; - } - - SortedSequence.prototype = new Sequence(); - - SortedSequence.prototype.each = function each(fn) { - var sortFn = this.sortFn, - result = this.parent.toArray(); - - result.sort(sortFn); - - return forEach(result, fn); - }; - - /** - * @examples - * var items = [{ a: 4 }, { a: 3 }, { a: 5 }]; - * - * Lazy(items).sortBy('a').reverse(); - * // => sequence: [{ a: 5 }, { a: 4 }, { a: 3 }] - * - * Lazy(items).sortBy('a').reverse().reverse(); - * // => sequence: [{ a: 3 }, { a: 4 }, { a: 5 }] - */ - SortedSequence.prototype.reverse = function reverse() { - return new SortedSequence(this.parent, reverseArguments(this.sortFn)); - }; - - /** - * Creates a new {@link ObjectLikeSequence} comprising the elements in this - * one, grouped together according to some key. The value associated with each - * key in the resulting object-like sequence is an array containing all of - * the elements in this sequence with that key. - * - * @public - * @param {Function|string} keyFn The function to call on the elements in this - * sequence to obtain a key by which to group them, or a string representing - * a parameter to read from all the elements in this sequence. - * @param {Function|string} valFn (Optional) The function to call on the elements - * in this sequence to assign to the value for each instance to appear in the - * group, or a string representing a parameter to read from all the elements - * in this sequence. - * @returns {ObjectLikeSequence} The new sequence. - * - * @examples - * function oddOrEven(x) { - * return x % 2 === 0 ? 'even' : 'odd'; - * } - * function square(x) { - * return x*x; - * } - * - * var numbers = [1, 2, 3, 4, 5]; - * - * Lazy(numbers).groupBy(oddOrEven) // sequence: { odd: [1, 3, 5], even: [2, 4] } - * Lazy(numbers).groupBy(oddOrEven).get("odd") // => [1, 3, 5] - * Lazy(numbers).groupBy(oddOrEven).get("foo") // => undefined - * Lazy(numbers).groupBy(oddOrEven, square).get("even") // => [4, 16] - * - * Lazy([ - * { name: 'toString' }, - * { name: 'toString' } - * ]).groupBy('name'); - * // => sequence: { - * 'toString': [ - * { name: 'toString' }, - * { name: 'toString' } - * ] - * } - */ - Sequence.prototype.groupBy = function groupBy(keyFn, valFn) { - return new GroupedSequence(this, keyFn, valFn); - }; - - /** - * @constructor - */ - function GroupedSequence(parent, keyFn, valFn) { - this.parent = parent; - this.keyFn = keyFn; - this.valFn = valFn; - } - - // GroupedSequence must have its prototype set after ObjectLikeSequence has - // been fully initialized. - - /** - * Creates a new {@link ObjectLikeSequence} comprising the elements in this - * one, indexed according to some key. - * - * @public - * @param {Function|string} keyFn The function to call on the elements in this - * sequence to obtain a key by which to index them, or a string - * representing a property to read from all the elements in this sequence. - * @param {Function|string} valFn (Optional) The function to call on the elements - * in this sequence to assign to the value of the indexed object, or a string - * representing a parameter to read from all the elements in this sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * var people = [ - * { name: 'Bob', age: 25 }, - * { name: 'Fred', age: 34 } - * ]; - * - * var bob = people[0], - * fred = people[1]; - * - * Lazy(people).indexBy('name') // sequence: { 'Bob': bob, 'Fred': fred } - * Lazy(people).indexBy('name', 'age') // sequence: { 'Bob': 25, 'Fred': 34 } - */ - Sequence.prototype.indexBy = function(keyFn, valFn) { - return new IndexedSequence(this, keyFn, valFn); - }; - - /** - * @constructor - */ - function IndexedSequence(parent, keyFn, valFn) { - this.parent = parent; - this.keyFn = keyFn; - this.valFn = valFn; - } - - // IndexedSequence must have its prototype set after ObjectLikeSequence has - // been fully initialized. - - /** - * Creates a new {@link ObjectLikeSequence} containing the unique keys of all - * the elements in this sequence, each paired with the number of elements - * in this sequence having that key. - * - * @public - * @param {Function|string} keyFn The function to call on the elements in this - * sequence to obtain a key by which to count them, or a string representing - * a parameter to read from all the elements in this sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * function oddOrEven(x) { - * return x % 2 === 0 ? 'even' : 'odd'; - * } - * - * var numbers = [1, 2, 3, 4, 5]; - * - * Lazy(numbers).countBy(oddOrEven) // sequence: { odd: 3, even: 2 } - * Lazy(numbers).countBy(oddOrEven).get("odd") // => 3 - * Lazy(numbers).countBy(oddOrEven).get("foo") // => undefined - */ - Sequence.prototype.countBy = function countBy(keyFn) { - return new CountedSequence(this, keyFn); - }; - - /** - * @constructor - */ - function CountedSequence(parent, keyFn) { - this.parent = parent; - this.keyFn = keyFn; - } - - // CountedSequence, like GroupedSequence, must have its prototype set after - // ObjectLikeSequence has been fully initialized. - - /** - * Creates a new sequence with every unique element from this one appearing - * exactly once (i.e., with duplicates removed). - * - * @public - * @aka unique - * @param {Function} keyFn An optional function to produce the key for each - * object. This key is then tested for uniqueness as opposed to the - * object reference. - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([1, 2, 2, 3, 3, 3]).uniq() // sequence: [1, 2, 3] - * Lazy([{ name: 'mike' }, - * { name: 'sarah' }, - * { name: 'mike' } - * ]).uniq('name') - * // sequence: [{ name: 'mike' }, { name: 'sarah' }] - * - * @benchmarks - * function randomOf(array) { - * return function() { - * return array[Math.floor(Math.random() * array.length)]; - * }; - * } - * - * var mostUnique = Lazy.generate(randomOf(_.range(100)), 100).toArray(), - * someUnique = Lazy.generate(randomOf(_.range(50)), 100).toArray(), - * mostDupes = Lazy.generate(randomOf(_.range(5)), 100).toArray(); - * - * Lazy(mostUnique).uniq().each(Lazy.noop) // lazy - mostly unique elements - * Lazy(someUnique).uniq().each(Lazy.noop) // lazy - some unique elements - * Lazy(mostDupes).uniq().each(Lazy.noop) // lazy - mostly duplicate elements - * _.each(_.uniq(mostUnique), _.noop) // lodash - mostly unique elements - * _.each(_.uniq(someUnique), _.noop) // lodash - some unique elements - * _.each(_.uniq(mostDupes), _.noop) // lodash - mostly duplicate elements - */ - Sequence.prototype.uniq = function uniq(keyFn) { - return new UniqueSequence(this, keyFn); - }; - - Sequence.prototype.unique = function unique(keyFn) { - return this.uniq(keyFn); - }; - - /** - * @constructor - */ - function UniqueSequence(parent, keyFn) { - this.parent = parent; - this.keyFn = keyFn; - } - - UniqueSequence.prototype = new Sequence(); - - UniqueSequence.prototype.each = function each(fn) { - var cache = new Set(), - keyFn = this.keyFn, - i = 0; - - if (keyFn) { - keyFn = createCallback(keyFn); - return this.parent.each(function(e) { - if (cache.add(keyFn(e))) { - return fn(e, i++); - } - }); - - } else { - return this.parent.each(function(e) { - if (cache.add(e)) { - return fn(e, i++); - } - }); - } - }; - - /** - * Creates a new sequence by combining the elements from this sequence with - * corresponding elements from the specified array(s). - * - * @public - * @param {...Array} var_args One or more arrays of elements to combine with - * those of this sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([1, 2]).zip([3, 4]) // sequence: [[1, 3], [2, 4]] - * - * @benchmarks - * var smArrL = Lazy.range(10).toArray(), - * smArrR = Lazy.range(10, 20).toArray(), - * lgArrL = Lazy.range(100).toArray(), - * lgArrR = Lazy.range(100, 200).toArray(); - * - * Lazy(smArrL).zip(smArrR).each(Lazy.noop) // lazy - zipping 10-element arrays - * Lazy(lgArrL).zip(lgArrR).each(Lazy.noop) // lazy - zipping 100-element arrays - * _.each(_.zip(smArrL, smArrR), _.noop) // lodash - zipping 10-element arrays - * _.each(_.zip(lgArrL, lgArrR), _.noop) // lodash - zipping 100-element arrays - */ - Sequence.prototype.zip = function zip(var_args) { - if (arguments.length === 1) { - return new SimpleZippedSequence(this, (/** @type {Array} */ var_args)); - } else { - return new ZippedSequence(this, arraySlice.call(arguments, 0)); - } - }; - - /** - * @constructor - */ - function ZippedSequence(parent, arrays) { - this.parent = parent; - this.arrays = arrays; - } - - ZippedSequence.prototype = new Sequence(); - - ZippedSequence.prototype.each = function each(fn) { - var arrays = this.arrays, - i = 0; - this.parent.each(function(e) { - var group = [e]; - for (var j = 0; j < arrays.length; ++j) { - if (arrays[j].length > i) { - group.push(arrays[j][i]); - } - } - return fn(group, i++); - }); - }; - - /** - * Creates a new sequence with the same elements as this one, in a randomized - * order. - * - * @public - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([1, 2, 3, 4, 5]).shuffle().value() // =~ [1, 2, 3, 4, 5] - */ - Sequence.prototype.shuffle = function shuffle() { - return new ShuffledSequence(this); - }; - - /** - * @constructor - */ - function ShuffledSequence(parent) { - this.parent = parent; - } - - ShuffledSequence.prototype = new Sequence(); - - ShuffledSequence.prototype.each = function each(fn) { - var shuffled = this.parent.toArray(), - floor = Math.floor, - random = Math.random, - j = 0; - - for (var i = shuffled.length - 1; i > 0; --i) { - swap(shuffled, i, floor(random() * (i + 1))); - if (fn(shuffled[i], j++) === false) { - return; - } - } - fn(shuffled[0], j); - }; - - /** - * Creates a new sequence with every element from this sequence, and with arrays - * exploded so that a sequence of arrays (of arrays) becomes a flat sequence of - * values. - * - * @public - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([1, [2, 3], [4, [5]]]).flatten() // sequence: [1, 2, 3, 4, 5] - * Lazy([1, Lazy([2, 3])]).flatten() // sequence: [1, 2, 3] - */ - Sequence.prototype.flatten = function flatten() { - return new FlattenedSequence(this); - }; - - /** - * @constructor - */ - function FlattenedSequence(parent) { - this.parent = parent; - } - - FlattenedSequence.prototype = new Sequence(); - - FlattenedSequence.prototype.each = function each(fn) { - var index = 0; - - return this.parent.each(function recurseVisitor(e) { - if (e instanceof Array) { - return forEach(e, recurseVisitor); - } - - if (e instanceof Sequence) { - return e.each(recurseVisitor); - } - - return fn(e, index++); - }); - }; - - /** - * Creates a new sequence with the same elements as this one, except for all - * falsy values (`false`, `0`, `""`, `null`, and `undefined`). - * - * @public - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy(["foo", null, "bar", undefined]).compact() // sequence: ["foo", "bar"] - */ - Sequence.prototype.compact = function compact() { - return this.filter(function(e) { return !!e; }); - }; - - /** - * Creates a new sequence with all the elements of this sequence that are not - * also among the specified arguments. - * - * @public - * @aka difference - * @param {...*} var_args The values, or array(s) of values, to be excluded from the - * resulting sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy([1, 2, 3, 4, 5]).without(2, 3) // sequence: [1, 4, 5] - * Lazy([1, 2, 3, 4, 5]).without([4, 5]) // sequence: [1, 2, 3] - */ - Sequence.prototype.without = function without(var_args) { - return new WithoutSequence(this, arraySlice.call(arguments, 0)); - }; - - Sequence.prototype.difference = function difference(var_args) { - return this.without.apply(this, arguments); - }; - - /** - * @constructor - */ - function WithoutSequence(parent, values) { - this.parent = parent; - this.values = values; - } - - WithoutSequence.prototype = new Sequence(); - - WithoutSequence.prototype.each = function each(fn) { - var set = createSet(this.values), - i = 0; - return this.parent.each(function(e) { - if (!set.contains(e)) { - return fn(e, i++); - } - }); - }; - - /** - * Creates a new sequence with all the unique elements either in this sequence - * or among the specified arguments. - * - * @public - * @param {...*} var_args The values, or array(s) of values, to be additionally - * included in the resulting sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy(["foo", "bar"]).union([]) // sequence: ["foo", "bar"] - * Lazy(["foo", "bar"]).union(["bar", "baz"]) // sequence: ["foo", "bar", "baz"] - */ - Sequence.prototype.union = function union(var_args) { - return this.concat(var_args).uniq(); - }; - - /** - * Creates a new sequence with all the elements of this sequence that also - * appear among the specified arguments. - * - * @public - * @param {...*} var_args The values, or array(s) of values, in which elements - * from this sequence must also be included to end up in the resulting sequence. - * @returns {Sequence} The new sequence. - * - * @examples - * Lazy(["foo", "bar"]).intersection([]) // sequence: [] - * Lazy(["foo", "bar"]).intersection(["bar", "baz"]) // sequence: ["bar"] - */ - Sequence.prototype.intersection = function intersection(var_args) { - if (arguments.length === 1 && arguments[0] instanceof Array) { - return new SimpleIntersectionSequence(this, (/** @type {Array} */ var_args)); - } else { - return new IntersectionSequence(this, arraySlice.call(arguments, 0)); - } - }; - - /** - * @constructor - */ - function IntersectionSequence(parent, arrays) { - this.parent = parent; - this.arrays = arrays; - } - - IntersectionSequence.prototype = new Sequence(); - - IntersectionSequence.prototype.each = function each(fn) { - var sets = Lazy(this.arrays).map(function(values) { - return new UniqueMemoizer(Lazy(values).getIterator()); - }); - - var setIterator = new UniqueMemoizer(sets.getIterator()), - i = 0; - - return this.parent.each(function(e) { - var includedInAll = true; - setIterator.each(function(set) { - if (!set.contains(e)) { - includedInAll = false; - return false; - } - }); - - if (includedInAll) { - return fn(e, i++); - } - }); - }; - - /** - * @constructor - */ - function UniqueMemoizer(iterator) { - this.iterator = iterator; - this.set = new Set(); - this.memo = []; - this.currentValue = undefined; - } - - UniqueMemoizer.prototype.current = function current() { - return this.currentValue; - }; - - UniqueMemoizer.prototype.moveNext = function moveNext() { - var iterator = this.iterator, - set = this.set, - memo = this.memo, - current; - - while (iterator.moveNext()) { - current = iterator.current(); - if (set.add(current)) { - memo.push(current); - this.currentValue = current; - return true; - } - } - return false; - }; - - UniqueMemoizer.prototype.each = function each(fn) { - var memo = this.memo, - length = memo.length, - i = -1; - - while (++i < length) { - if (fn(memo[i], i) === false) { - return false; - } - } - - while (this.moveNext()) { - if (fn(this.currentValue, i++) === false) { - break; - } - } - }; - - UniqueMemoizer.prototype.contains = function contains(e) { - if (this.set.contains(e)) { - return true; - } - - while (this.moveNext()) { - if (this.currentValue === e) { - return true; - } - } - - return false; - }; - - /** - * Checks whether every element in this sequence satisfies a given predicate. - * - * @public - * @aka all - * @param {Function} predicate A function to call on (potentially) every element - * in this sequence. - * @returns {boolean} True if `predicate` returns true for every element in the - * sequence (or the sequence is empty). False if `predicate` returns false - * for at least one element. - * - * @examples - * var numbers = [1, 2, 3, 4, 5]; - * - * var objects = [{ foo: true }, { foo: false, bar: true }]; - * - * Lazy(numbers).every(isEven) // => false - * Lazy(numbers).every(isPositive) // => true - * Lazy(objects).all('foo') // => false - * Lazy(objects).all('bar') // => false - */ - Sequence.prototype.every = function every(predicate) { - predicate = createCallback(predicate); - - return this.each(function(e, i) { - return !!predicate(e, i); - }); - }; - - Sequence.prototype.all = function all(predicate) { - return this.every(predicate); - }; - - /** - * Checks whether at least one element in this sequence satisfies a given - * predicate (or, if no predicate is specified, whether the sequence contains at - * least one element). - * - * @public - * @aka any - * @param {Function=} predicate A function to call on (potentially) every element - * in this sequence. - * @returns {boolean} True if `predicate` returns true for at least one element - * in the sequence. False if `predicate` returns false for every element (or - * the sequence is empty). - * - * @examples - * var numbers = [1, 2, 3, 4, 5]; - * - * Lazy(numbers).some() // => true - * Lazy(numbers).some(isEven) // => true - * Lazy(numbers).some(isNegative) // => false - * Lazy([]).some() // => false - */ - Sequence.prototype.some = function some(predicate) { - predicate = createCallback(predicate, true); - - var success = false; - this.each(function(e) { - if (predicate(e)) { - success = true; - return false; - } - }); - return success; - }; - - Sequence.prototype.any = function any(predicate) { - return this.some(predicate); - }; - - /** - * Checks whether NO elements in this sequence satisfy the given predicate - * (the opposite of {@link Sequence#all}, basically). - * - * @public - * @param {Function=} predicate A function to call on (potentially) every element - * in this sequence. - * @returns {boolean} True if `predicate` does not return true for any element - * in the sequence. False if `predicate` returns true for at least one - * element. - * - * @examples - * var numbers = [1, 2, 3, 4, 5]; - * - * Lazy(numbers).none() // => false - * Lazy(numbers).none(isEven) // => false - * Lazy(numbers).none(isNegative) // => true - * Lazy([]).none(isEven) // => true - * Lazy([]).none(isNegative) // => true - * Lazy([]).none() // => true - */ - Sequence.prototype.none = function none(predicate) { - return !this.any(predicate); - }; - - /** - * Checks whether the sequence has no elements. - * - * @public - * @returns {boolean} True if the sequence is empty, false if it contains at - * least one element. - * - * @examples - * Lazy([]).isEmpty() // => true - * Lazy([1, 2, 3]).isEmpty() // => false - */ - Sequence.prototype.isEmpty = function isEmpty() { - return !this.any(); - }; - - /** - * Performs (at worst) a linear search from the head of this sequence, - * returning the first index at which the specified value is found. - * - * @public - * @param {*} value The element to search for in the sequence. - * @returns {number} The index within this sequence where the given value is - * located, or -1 if the sequence doesn't contain the value. - * - * @examples - * function reciprocal(x) { return 1 / x; } - * - * Lazy(["foo", "bar", "baz"]).indexOf("bar") // => 1 - * Lazy([1, 2, 3]).indexOf(4) // => -1 - * Lazy([1, 2, 3]).map(reciprocal).indexOf(0.5) // => 1 - */ - Sequence.prototype.indexOf = function indexOf(value) { - var foundIndex = -1; - this.each(function(e, i) { - if (e === value) { - foundIndex = i; - return false; - } - }); - return foundIndex; - }; - - /** - * Performs (at worst) a linear search from the tail of this sequence, - * returning the last index at which the specified value is found. - * - * @public - * @param {*} value The element to search for in the sequence. - * @returns {number} The last index within this sequence where the given value - * is located, or -1 if the sequence doesn't contain the value. - * - * @examples - * Lazy(["a", "b", "c", "b", "a"]).lastIndexOf("b") // => 3 - * Lazy([1, 2, 3]).lastIndexOf(0) // => -1 - * Lazy([2, 2, 1, 2, 4]).filter(isEven).lastIndexOf(2) // 2 - */ - Sequence.prototype.lastIndexOf = function lastIndexOf(value) { - var reversed = this.getIndex().reverse(), - index = reversed.indexOf(value); - if (index !== -1) { - index = reversed.length() - index - 1; - } - return index; - }; - - /** - * Performs a binary search of this sequence, returning the lowest index where - * the given value is either found, or where it belongs (if it is not already - * in the sequence). - * - * This method assumes the sequence is in sorted order and will fail otherwise. - * - * @public - * @param {*} value The element to search for in the sequence. - * @returns {number} An index within this sequence where the given value is - * located, or where it belongs in sorted order. - * - * @examples - * Lazy([1, 3, 6, 9]).sortedIndex(3) // => 1 - * Lazy([1, 3, 6, 9]).sortedIndex(7) // => 3 - * Lazy([5, 10, 15, 20]).filter(isEven).sortedIndex(10) // => 0 - * Lazy([5, 10, 15, 20]).filter(isEven).sortedIndex(12) // => 1 - */ - Sequence.prototype.sortedIndex = function sortedIndex(value) { - var indexed = this.getIndex(), - lower = 0, - upper = indexed.length(), - i; - - while (lower < upper) { - i = (lower + upper) >>> 1; - if (compare(indexed.get(i), value) === -1) { - lower = i + 1; - } else { - upper = i; - } - } - return lower; - }; - - /** - * Checks whether the given value is in this sequence. - * - * @public - * @param {*} value The element to search for in the sequence. - * @returns {boolean} True if the sequence contains the value, false if not. - * - * @examples - * var numbers = [5, 10, 15, 20]; - * - * Lazy(numbers).contains(15) // => true - * Lazy(numbers).contains(13) // => false - */ - Sequence.prototype.contains = function contains(value) { - return this.indexOf(value) !== -1; - }; - - /** - * Aggregates a sequence into a single value according to some accumulator - * function. - * - * For an asynchronous sequence, instead of immediately returning a result - * (which it can't, obviously), this method returns an {@link AsyncHandle} - * whose `onComplete` method can be called to supply a callback to handle the - * final result once iteration has completed. - * - * @public - * @aka inject, foldl - * @param {Function} aggregator The function through which to pass every element - * in the sequence. For every element, the function will be passed the total - * aggregated result thus far and the element itself, and should return a - * new aggregated result. - * @param {*=} memo The starting value to use for the aggregated result - * (defaults to the first element in the sequence). - * @returns {*} The result of the aggregation, or, for asynchronous sequences, - * an {@link AsyncHandle} whose `onComplete` method accepts a callback to - * handle the final result. - * - * @examples - * function multiply(x, y) { return x * y; } - * - * var numbers = [1, 2, 3, 4]; - * - * Lazy(numbers).reduce(multiply) // => 24 - * Lazy(numbers).reduce(multiply, 5) // => 120 - */ - Sequence.prototype.reduce = function reduce(aggregator, memo) { - if (arguments.length < 2) { - return this.tail().reduce(aggregator, this.head()); - } - - var eachResult = this.each(function(e, i) { - memo = aggregator(memo, e, i); - }); - - // TODO: Think of a way more efficient solution to this problem. - if (eachResult instanceof AsyncHandle) { - return eachResult.then(function() { return memo; }); - } - - return memo; - }; - - Sequence.prototype.inject = - Sequence.prototype.foldl = function foldl(aggregator, memo) { - return this.reduce(aggregator, memo); - }; - - /** - * Aggregates a sequence, from the tail, into a single value according to some - * accumulator function. - * - * @public - * @aka foldr - * @param {Function} aggregator The function through which to pass every element - * in the sequence. For every element, the function will be passed the total - * aggregated result thus far and the element itself, and should return a - * new aggregated result. - * @param {*} memo The starting value to use for the aggregated result. - * @returns {*} The result of the aggregation. - * - * @examples - * function append(s1, s2) { - * return s1 + s2; - * } - * - * function isVowel(str) { - * return "aeiou".indexOf(str) !== -1; - * } - * - * Lazy("abcde").reduceRight(append) // => "edcba" - * Lazy("abcde").filter(isVowel).reduceRight(append) // => "ea" - */ - Sequence.prototype.reduceRight = function reduceRight(aggregator, memo) { - if (arguments.length < 2) { - return this.initial(1).reduceRight(aggregator, this.last()); - } - - // This bothers me... but frankly, calling reverse().reduce() is potentially - // going to eagerly evaluate the sequence anyway; so it's really not an issue. - var indexed = this.getIndex(), - i = indexed.length() - 1; - return indexed.reverse().reduce(function(m, e) { - return aggregator(m, e, i--); - }, memo); - }; - - Sequence.prototype.foldr = function foldr(aggregator, memo) { - return this.reduceRight(aggregator, memo); - }; - - /** - * Groups this sequence into consecutive (overlapping) segments of a specified - * length. If the underlying sequence has fewer elements than the specfied - * length, then this sequence will be empty. - * - * @public - * @param {number} length The length of each consecutive segment. - * @returns {Sequence} The resulting sequence of consecutive segments. - * - * @examples - * Lazy([]).consecutive(2) // => sequence: [] - * Lazy([1]).consecutive(2) // => sequence: [] - * Lazy([1, 2]).consecutive(2) // => sequence: [[1, 2]] - * Lazy([1, 2, 3]).consecutive(2) // => sequence: [[1, 2], [2, 3]] - * Lazy([1, 2, 3]).consecutive(0) // => sequence: [[]] - * Lazy([1, 2, 3]).consecutive(1) // => sequence: [[1], [2], [3]] - */ - Sequence.prototype.consecutive = function consecutive(count) { - var queue = new Queue(count); - var segments = this.map(function(element) { - if (queue.add(element).count === count) { - return queue.toArray(); - } - }); - return segments.compact(); - }; - - /** - * Breaks this sequence into chunks (arrays) of a specified length. - * - * @public - * @param {number} size The size of each chunk. - * @returns {Sequence} The resulting sequence of chunks. - * - * @examples - * Lazy([]).chunk(2) // sequence: [] - * Lazy([1, 2, 3]).chunk(2) // sequence: [[1, 2], [3]] - * Lazy([1, 2, 3]).chunk(1) // sequence: [[1], [2], [3]] - * Lazy([1, 2, 3]).chunk(4) // sequence: [[1, 2, 3]] - * Lazy([1, 2, 3]).chunk(0) // throws - */ - Sequence.prototype.chunk = function chunk(size) { - if (size < 1) { - throw new Error("You must specify a positive chunk size."); - } - - return new ChunkedSequence(this, size); - }; - - /** - * @constructor - */ - function ChunkedSequence(parent, size) { - this.parent = parent; - this.chunkSize = size; - } - - ChunkedSequence.prototype = new Sequence(); - - ChunkedSequence.prototype.getIterator = function getIterator() { - return new ChunkedIterator(this.parent, this.chunkSize); - }; - - /** - * @constructor - */ - function ChunkedIterator(sequence, size) { - this.iterator = sequence.getIterator(); - this.size = size; - } - - ChunkedIterator.prototype.current = function current() { - return this.currentChunk; - }; - - ChunkedIterator.prototype.moveNext = function moveNext() { - var iterator = this.iterator, - chunkSize = this.size, - chunk = []; - - while (chunk.length < chunkSize && iterator.moveNext()) { - chunk.push(iterator.current()); - } - - if (chunk.length === 0) { - return false; - } - - this.currentChunk = chunk; - return true; - }; - - /** - * Passes each element in the sequence to the specified callback during - * iteration. This is like {@link Sequence#each}, except that it can be - * inserted anywhere in the middle of a chain of methods to "intercept" the - * values in the sequence at that point. - * - * @public - * @param {Function} callback A function to call on every element in the - * sequence during iteration. The return value of this function does not - * matter. - * @returns {Sequence} A sequence comprising the same elements as this one. - * - * @examples - * Lazy([1, 2, 3]).tap(fn).each(Lazy.noop); // calls fn 3 times - */ - Sequence.prototype.tap = function tap(callback) { - return new TappedSequence(this, callback); - }; - - /** - * @constructor - */ - function TappedSequence(parent, callback) { - this.parent = parent; - this.callback = callback; - } - - TappedSequence.prototype = new Sequence(); - - TappedSequence.prototype.each = function each(fn) { - var callback = this.callback; - return this.parent.each(function(e, i) { - callback(e, i); - return fn(e, i); - }); - }; - - /** - * Seaches for the first element in the sequence satisfying a given predicate. - * - * @public - * @aka detect - * @param {Function} predicate A function to call on (potentially) every element - * in the sequence. - * @returns {*} The first element in the sequence for which `predicate` returns - * `true`, or `undefined` if no such element is found. - * - * @examples - * function divisibleBy3(x) { - * return x % 3 === 0; - * } - * - * var numbers = [5, 6, 7, 8, 9, 10]; - * - * Lazy(numbers).find(divisibleBy3) // => 6 - * Lazy(numbers).find(isNegative) // => undefined - */ - Sequence.prototype.find = function find(predicate) { - return this.filter(predicate).first(); - }; - - Sequence.prototype.detect = function detect(predicate) { - return this.find(predicate); - }; - - /** - * Gets the minimum value in the sequence. - * - * @public - * @param {Function=} valueFn The function by which the value for comparison is - * calculated for each element in the sequence. - * @returns {*} The element with the lowest value in the sequence, or - * `Infinity` if the sequence is empty. - * - * @examples - * function negate(x) { return x * -1; } - * - * Lazy([]).min() // => Infinity - * Lazy([6, 18, 2, 49, 34]).min() // => 2 - * Lazy([6, 18, 2, 49, 34]).min(negate) // => 49 - */ - Sequence.prototype.min = function min(valueFn) { - if (typeof valueFn !== "undefined") { - return this.minBy(valueFn); - } - - return this.reduce(function(x, y) { return y < x ? y : x; }, Infinity); - }; - - Sequence.prototype.minBy = function minBy(valueFn) { - valueFn = createCallback(valueFn); - return this.reduce(function(x, y) { return valueFn(y) < valueFn(x) ? y : x; }); - }; - - /** - * Gets the maximum value in the sequence. - * - * @public - * @param {Function=} valueFn The function by which the value for comparison is - * calculated for each element in the sequence. - * @returns {*} The element with the highest value in the sequence, or - * `-Infinity` if the sequence is empty. - * - * @examples - * function reverseDigits(x) { - * return Number(String(x).split('').reverse().join('')); - * } - * - * Lazy([]).max() // => -Infinity - * Lazy([6, 18, 2, 48, 29]).max() // => 48 - * Lazy([6, 18, 2, 48, 29]).max(reverseDigits) // => 29 - */ - Sequence.prototype.max = function max(valueFn) { - if (typeof valueFn !== "undefined") { - return this.maxBy(valueFn); - } - - return this.reduce(function(x, y) { return y > x ? y : x; }, -Infinity); - }; - - Sequence.prototype.maxBy = function maxBy(valueFn) { - valueFn = createCallback(valueFn); - return this.reduce(function(x, y) { return valueFn(y) > valueFn(x) ? y : x; }); - }; - - /** - * Gets the sum of the values in the sequence. - * - * @public - * @param {Function=} valueFn The function used to select the values that will - * be summed up. - * @returns {*} The sum. - * - * @examples - * Lazy([]).sum() // => 0 - * Lazy([1, 2, 3, 4]).sum() // => 10 - * Lazy([1.2, 3.4]).sum(Math.floor) // => 4 - * Lazy(['foo', 'bar']).sum('length') // => 6 - */ - Sequence.prototype.sum = function sum(valueFn) { - if (typeof valueFn !== "undefined") { - return this.sumBy(valueFn); - } - - return this.reduce(function(x, y) { return x + y; }, 0); - }; - - Sequence.prototype.sumBy = function sumBy(valueFn) { - valueFn = createCallback(valueFn); - return this.reduce(function(x, y) { return x + valueFn(y); }, 0); - }; - - /** - * Creates a string from joining together all of the elements in this sequence, - * separated by the given delimiter. - * - * @public - * @aka toString - * @param {string=} delimiter The separator to insert between every element from - * this sequence in the resulting string (defaults to `","`). - * @returns {string} The delimited string. - * - * @examples - * Lazy([6, 29, 1984]).join("/") // => "6/29/1984" - * Lazy(["a", "b", "c"]).join() // => "a,b,c" - * Lazy(["a", "b", "c"]).join("") // => "abc" - * Lazy([1, 2, 3]).join() // => "1,2,3" - * Lazy([1, 2, 3]).join("") // => "123" - * Lazy(["", "", ""]).join(",") // => ",," - */ - Sequence.prototype.join = function join(delimiter) { - delimiter = typeof delimiter === "string" ? delimiter : ","; - - return this.reduce(function(str, e, i) { - if (i > 0) { - str += delimiter; - } - return str + e; - }, ""); - }; - - Sequence.prototype.toString = function toString(delimiter) { - return this.join(delimiter); - }; - - /** - * Creates a sequence, with the same elements as this one, that will be iterated - * over asynchronously when calling `each`. - * - * @public - * @param {number=} interval The approximate period, in milliseconds, that - * should elapse between each element in the resulting sequence. Omitting - * this argument will result in the fastest possible asynchronous iteration. - * @returns {AsyncSequence} The new asynchronous sequence. - * - * @examples - * Lazy([1, 2, 3]).async(100).each(fn) // calls fn 3 times asynchronously - */ - Sequence.prototype.async = function async(interval) { - return new AsyncSequence(this, interval); - }; - - /** - * @constructor - */ - function SimpleIntersectionSequence(parent, array) { - this.parent = parent; - this.array = array; - this.each = getEachForIntersection(array); - } - - SimpleIntersectionSequence.prototype = new Sequence(); - - SimpleIntersectionSequence.prototype.eachMemoizerCache = function eachMemoizerCache(fn) { - var iterator = new UniqueMemoizer(Lazy(this.array).getIterator()), - i = 0; - - return this.parent.each(function(e) { - if (iterator.contains(e)) { - return fn(e, i++); - } - }); - }; - - SimpleIntersectionSequence.prototype.eachArrayCache = function eachArrayCache(fn) { - var array = this.array, - find = arrayContains, - i = 0; - - return this.parent.each(function(e) { - if (find(array, e)) { - return fn(e, i++); - } - }); - }; - - function getEachForIntersection(source) { - if (source.length < 40) { - return SimpleIntersectionSequence.prototype.eachArrayCache; - } else { - return SimpleIntersectionSequence.prototype.eachMemoizerCache; - } - } - - /** - * An optimized version of {@link ZippedSequence}, when zipping a sequence with - * only one array. - * - * @param {Sequence} parent The underlying sequence. - * @param {Array} array The array with which to zip the sequence. - * @constructor - */ - function SimpleZippedSequence(parent, array) { - this.parent = parent; - this.array = array; - } - - SimpleZippedSequence.prototype = new Sequence(); - - SimpleZippedSequence.prototype.each = function each(fn) { - var array = this.array; - return this.parent.each(function(e, i) { - return fn([e, array[i]], i); - }); - }; - - /** - * An `ArrayLikeSequence` is a {@link Sequence} that provides random access to - * its elements. This extends the API for iterating with the additional methods - * {@link #get} and {@link #length}, allowing a sequence to act as a "view" into - * a collection or other indexed data source. - * - * The initial sequence created by wrapping an array with `Lazy(array)` is an - * `ArrayLikeSequence`. - * - * All methods of `ArrayLikeSequence` that conceptually should return - * something like a array (with indexed access) return another - * `ArrayLikeSequence`, for example: - * - * - {@link Sequence#map} - * - {@link ArrayLikeSequence#slice} - * - {@link Sequence#take} and {@link Sequence#drop} - * - {@link Sequence#reverse} - * - * The above is not an exhaustive list. There are also certain other cases - * where it might be possible to return an `ArrayLikeSequence` (e.g., calling - * {@link Sequence#concat} with a single array argument), but this is not - * guaranteed by the API. - * - * Note that in many cases, it is not possible to provide indexed access - * without first performing at least a partial iteration of the underlying - * sequence. In these cases an `ArrayLikeSequence` will not be returned: - * - * - {@link Sequence#filter} - * - {@link Sequence#uniq} - * - {@link Sequence#union} - * - {@link Sequence#intersect} - * - * etc. The above methods only return ordinary {@link Sequence} objects. - * - * Defining custom array-like sequences - * ------------------------------------ - * - * Creating a custom `ArrayLikeSequence` is essentially the same as creating a - * custom {@link Sequence}. You just have a couple more methods you need to - * implement: `get` and (optionally) `length`. - * - * Here's an example. Let's define a sequence type called `OffsetSequence` that - * offsets each of its parent's elements by a set distance, and circles back to - * the beginning after reaching the end. **Remember**: the initialization - * function you pass to {@link #define} should always accept a `parent` as its - * first parameter. - * - * ArrayLikeSequence.define("offset", { - * init: function(parent, offset) { - * this.offset = offset; - * }, - * - * get: function(i) { - * return this.parent.get((i + this.offset) % this.parent.length()); - * } - * }); - * - * It's worth noting a couple of things here. - * - * First, Lazy's default implementation of `length` simply returns the parent's - * length. In this case, since an `OffsetSequence` will always have the same - * number of elements as its parent, that implementation is fine; so we don't - * need to override it. - * - * Second, the default implementation of `each` uses `get` and `length` to - * essentially create a `for` loop, which is fine here. If you want to implement - * `each` your own way, you can do that; but in most cases (as here), you can - * probably just stick with the default. - * - * So we're already done, after only implementing `get`! Pretty easy, huh? - * - * Now the `offset` method will be chainable from any `ArrayLikeSequence`. So - * for example: - * - * Lazy([1, 2, 3]).map(mapFn).offset(3); - * - * ...will work, but: - * - * Lazy([1, 2, 3]).filter(mapFn).offset(3); - * - * ...will not (because `filter` does not return an `ArrayLikeSequence`). - * - * (Also, as with the example provided for defining custom {@link Sequence} - * types, this example really could have been implemented using a function - * already available as part of Lazy.js: in this case, {@link Sequence#map}.) - * - * @public - * @constructor - * - * @examples - * Lazy([1, 2, 3]) // instanceof Lazy.ArrayLikeSequence - * Lazy([1, 2, 3]).map(Lazy.identity) // instanceof Lazy.ArrayLikeSequence - * Lazy([1, 2, 3]).take(2) // instanceof Lazy.ArrayLikeSequence - * Lazy([1, 2, 3]).drop(2) // instanceof Lazy.ArrayLikeSequence - * Lazy([1, 2, 3]).reverse() // instanceof Lazy.ArrayLikeSequence - * Lazy([1, 2, 3]).slice(1, 2) // instanceof Lazy.ArrayLikeSequence - */ - function ArrayLikeSequence() {} - - ArrayLikeSequence.prototype = new Sequence(); - - /** - * Create a new constructor function for a type inheriting from - * `ArrayLikeSequence`. - * - * @public - * @param {string|Array.} methodName The name(s) of the method(s) to be - * used for constructing the new sequence. The method will be attached to - * the `ArrayLikeSequence` prototype so that it can be chained with any other - * methods that return array-like sequences. - * @param {Object} overrides An object containing function overrides for this - * new sequence type. **Must** include `get`. *May* include `init`, - * `length`, `getIterator`, and `each`. For each function, `this` will be - * the new sequence and `this.parent` will be the source sequence. - * @returns {Function} A constructor for a new type inheriting from - * `ArrayLikeSequence`. - * - * @examples - * Lazy.ArrayLikeSequence.define("offset", { - * init: function(offset) { - * this.offset = offset; - * }, - * - * get: function(i) { - * return this.parent.get((i + this.offset) % this.parent.length()); - * } - * }); - * - * Lazy([1, 2, 3]).offset(1) // sequence: [2, 3, 1] - */ - ArrayLikeSequence.define = function define(methodName, overrides) { - if (!overrides || typeof overrides.get !== 'function') { - throw new Error("A custom array-like sequence must implement *at least* get!"); - } - - return defineSequenceType(ArrayLikeSequence, methodName, overrides); - }; - - /** - * Returns the element at the specified index. - * - * @public - * @param {number} i The index to access. - * @returns {*} The element. - * - * @examples - * function increment(x) { return x + 1; } - * - * Lazy([1, 2, 3]).get(1) // => 2 - * Lazy([1, 2, 3]).get(-1) // => undefined - * Lazy([1, 2, 3]).map(increment).get(1) // => 3 - */ - ArrayLikeSequence.prototype.get = function get(i) { - return this.parent.get(i); - }; - - /** - * Returns the length of the sequence. - * - * @public - * @returns {number} The length. - * - * @examples - * function increment(x) { return x + 1; } - * - * Lazy([]).length() // => 0 - * Lazy([1, 2, 3]).length() // => 3 - * Lazy([1, 2, 3]).map(increment).length() // => 3 - */ - ArrayLikeSequence.prototype.length = function length() { - return this.parent.length(); - }; - - /** - * Returns the current sequence (since it is already indexed). - */ - ArrayLikeSequence.prototype.getIndex = function getIndex() { - return this; - }; - - /** - * An optimized version of {@link Sequence#getIterator}. - */ - ArrayLikeSequence.prototype.getIterator = function getIterator() { - return new IndexedIterator(this); - }; - - /** - * An optimized version of {@link Iterator} meant to work with already-indexed - * sequences. - * - * @param {ArrayLikeSequence} sequence The sequence to iterate over. - * @constructor - */ - function IndexedIterator(sequence) { - this.sequence = sequence; - this.index = -1; - } - - IndexedIterator.prototype.current = function current() { - return this.sequence.get(this.index); - }; - - IndexedIterator.prototype.moveNext = function moveNext() { - if (this.index >= this.sequence.length() - 1) { - return false; - } - - ++this.index; - return true; - }; - - /** - * An optimized version of {@link Sequence#each}. - */ - ArrayLikeSequence.prototype.each = function each(fn) { - var length = this.length(), - i = -1; - - while (++i < length) { - if (fn(this.get(i), i) === false) { - return false; - } - } - - return true; - }; - - /** - * Returns a new sequence with the same elements as this one, minus the last - * element. - * - * @public - * @returns {ArrayLikeSequence} The new array-like sequence. - * - * @examples - * Lazy([1, 2, 3]).pop() // sequence: [1, 2] - * Lazy([]).pop() // sequence: [] - */ - ArrayLikeSequence.prototype.pop = function pop() { - return this.initial(); - }; - - /** - * Returns a new sequence with the same elements as this one, minus the first - * element. - * - * @public - * @returns {ArrayLikeSequence} The new array-like sequence. - * - * @examples - * Lazy([1, 2, 3]).shift() // sequence: [2, 3] - * Lazy([]).shift() // sequence: [] - */ - ArrayLikeSequence.prototype.shift = function shift() { - return this.drop(); - }; - - /** - * Returns a new sequence comprising the portion of this sequence starting - * from the specified starting index and continuing until the specified ending - * index or to the end of the sequence. - * - * @public - * @param {number} begin The index at which the new sequence should start. - * @param {number=} end The index at which the new sequence should end. - * @returns {ArrayLikeSequence} The new array-like sequence. - * - * @examples - * Lazy([1, 2, 3, 4, 5]).slice(0) // sequence: [1, 2, 3, 4, 5] - * Lazy([1, 2, 3, 4, 5]).slice(2) // sequence: [3, 4, 5] - * Lazy([1, 2, 3, 4, 5]).slice(2, 4) // sequence: [3, 4] - * Lazy([1, 2, 3, 4, 5]).slice(-1) // sequence: [5] - * Lazy([1, 2, 3, 4, 5]).slice(1, -1) // sequence: [2, 3, 4] - * Lazy([1, 2, 3, 4, 5]).slice(0, 10) // sequence: [1, 2, 3, 4, 5] - */ - ArrayLikeSequence.prototype.slice = function slice(begin, end) { - var length = this.length(); - - if (begin < 0) { - begin = length + begin; - } - - var result = this.drop(begin); - - if (typeof end === "number") { - if (end < 0) { - end = length + end; - } - result = result.take(end - begin); - } - - return result; - }; - - /** - * An optimized version of {@link Sequence#map}, which creates an - * {@link ArrayLikeSequence} so that the result still provides random access. - * - * @public - * - * @examples - * Lazy([1, 2, 3]).map(Lazy.identity) // instanceof Lazy.ArrayLikeSequence - */ - ArrayLikeSequence.prototype.map = function map(mapFn) { - return new IndexedMappedSequence(this, createCallback(mapFn)); - }; - - /** - * @constructor - */ - function IndexedMappedSequence(parent, mapFn) { - this.parent = parent; - this.mapFn = mapFn; - } - - IndexedMappedSequence.prototype = new ArrayLikeSequence(); - - IndexedMappedSequence.prototype.get = function get(i) { - if (i < 0 || i >= this.parent.length()) { - return undefined; - } - - return this.mapFn(this.parent.get(i), i); - }; - - /** - * An optimized version of {@link Sequence#filter}. - */ - ArrayLikeSequence.prototype.filter = function filter(filterFn) { - return new IndexedFilteredSequence(this, createCallback(filterFn)); - }; - - /** - * @constructor - */ - function IndexedFilteredSequence(parent, filterFn) { - this.parent = parent; - this.filterFn = filterFn; - } - - IndexedFilteredSequence.prototype = new FilteredSequence(); - - IndexedFilteredSequence.prototype.each = function each(fn) { - var parent = this.parent, - filterFn = this.filterFn, - length = this.parent.length(), - i = -1, - j = 0, - e; - - while (++i < length) { - e = parent.get(i); - if (filterFn(e, i) && fn(e, j++) === false) { - return false; - } - } - - return true; - }; - - /** - * An optimized version of {@link Sequence#reverse}, which creates an - * {@link ArrayLikeSequence} so that the result still provides random access. - * - * @public - * - * @examples - * Lazy([1, 2, 3]).reverse() // instanceof Lazy.ArrayLikeSequence - */ - ArrayLikeSequence.prototype.reverse = function reverse() { - return new IndexedReversedSequence(this); - }; - - /** - * @constructor - */ - function IndexedReversedSequence(parent) { - this.parent = parent; - } - - IndexedReversedSequence.prototype = new ArrayLikeSequence(); - - IndexedReversedSequence.prototype.get = function get(i) { - return this.parent.get(this.length() - i - 1); - }; - - /** - * An optimized version of {@link Sequence#first}, which creates an - * {@link ArrayLikeSequence} so that the result still provides random access. - * - * @public - * - * @examples - * Lazy([1, 2, 3]).first(2) // instanceof Lazy.ArrayLikeSequence - */ - ArrayLikeSequence.prototype.first = function first(count) { - if (typeof count === "undefined") { - return this.get(0); - } - - return new IndexedTakeSequence(this, count); - }; - - /** - * @constructor - */ - function IndexedTakeSequence(parent, count) { - this.parent = parent; - this.count = count; - } - - IndexedTakeSequence.prototype = new ArrayLikeSequence(); - - IndexedTakeSequence.prototype.length = function length() { - var parentLength = this.parent.length(); - return this.count <= parentLength ? this.count : parentLength; - }; - - /** - * An optimized version of {@link Sequence#rest}, which creates an - * {@link ArrayLikeSequence} so that the result still provides random access. - * - * @public - * - * @examples - * Lazy([1, 2, 3]).rest() // instanceof Lazy.ArrayLikeSequence - */ - ArrayLikeSequence.prototype.rest = function rest(count) { - return new IndexedDropSequence(this, count); - }; - - /** - * @constructor - */ - function IndexedDropSequence(parent, count) { - this.parent = parent; - this.count = typeof count === "number" ? count : 1; - } - - IndexedDropSequence.prototype = new ArrayLikeSequence(); - - IndexedDropSequence.prototype.get = function get(i) { - return this.parent.get(this.count + i); - }; - - IndexedDropSequence.prototype.length = function length() { - var parentLength = this.parent.length(); - return this.count <= parentLength ? parentLength - this.count : 0; - }; - - /** - * An optimized version of {@link Sequence#concat} that returns another - * {@link ArrayLikeSequence} *if* the argument is an array. - * - * @public - * @param {...*} var_args - * - * @examples - * Lazy([1, 2]).concat([3, 4]) // instanceof Lazy.ArrayLikeSequence - * Lazy([1, 2]).concat([3, 4]) // sequence: [1, 2, 3, 4] - */ - ArrayLikeSequence.prototype.concat = function concat(var_args) { - if (arguments.length === 1 && arguments[0] instanceof Array) { - return new IndexedConcatenatedSequence(this, (/** @type {Array} */ var_args)); - } else { - return Sequence.prototype.concat.apply(this, arguments); - } - }; - - /** - * @constructor - */ - function IndexedConcatenatedSequence(parent, other) { - this.parent = parent; - this.other = other; - } - - IndexedConcatenatedSequence.prototype = new ArrayLikeSequence(); - - IndexedConcatenatedSequence.prototype.get = function get(i) { - var parentLength = this.parent.length(); - if (i < parentLength) { - return this.parent.get(i); - } else { - return this.other[i - parentLength]; - } - }; - - IndexedConcatenatedSequence.prototype.length = function length() { - return this.parent.length() + this.other.length; - }; - - /** - * An optimized version of {@link Sequence#uniq}. - */ - ArrayLikeSequence.prototype.uniq = function uniq(keyFn) { - return new IndexedUniqueSequence(this, createCallback(keyFn)); - }; - - /** - * @param {ArrayLikeSequence} parent - * @constructor - */ - function IndexedUniqueSequence(parent, keyFn) { - this.parent = parent; - this.each = getEachForParent(parent); - this.keyFn = keyFn; - } - - IndexedUniqueSequence.prototype = new Sequence(); - - IndexedUniqueSequence.prototype.eachArrayCache = function eachArrayCache(fn) { - // Basically the same implementation as w/ the set, but using an array because - // it's cheaper for smaller sequences. - var parent = this.parent, - keyFn = this.keyFn, - length = parent.length(), - cache = [], - find = arrayContains, - key, value, - i = -1, - j = 0; - - while (++i < length) { - value = parent.get(i); - key = keyFn(value); - if (!find(cache, key)) { - cache.push(key); - if (fn(value, j++) === false) { - return false; - } - } - } - }; - - IndexedUniqueSequence.prototype.eachSetCache = UniqueSequence.prototype.each; - - function getEachForParent(parent) { - if (parent.length() < 100) { - return IndexedUniqueSequence.prototype.eachArrayCache; - } else { - return UniqueSequence.prototype.each; - } - } - - // Now that we've fully initialized the ArrayLikeSequence prototype, we can - // set the prototype for MemoizedSequence. - - MemoizedSequence.prototype = new ArrayLikeSequence(); - - MemoizedSequence.prototype.cache = function cache() { - return this.cachedResult || (this.cachedResult = this.parent.toArray()); - }; - - MemoizedSequence.prototype.get = function get(i) { - return this.cache()[i]; - }; - - MemoizedSequence.prototype.length = function length() { - return this.cache().length; - }; - - MemoizedSequence.prototype.slice = function slice(begin, end) { - return this.cache().slice(begin, end); - }; - - MemoizedSequence.prototype.toArray = function toArray() { - return this.cache().slice(0); - }; - - /** - * ArrayWrapper is the most basic {@link Sequence}. It directly wraps an array - * and implements the same methods as {@link ArrayLikeSequence}, but more - * efficiently. - * - * @constructor - */ - function ArrayWrapper(source) { - this.source = source; - } - - ArrayWrapper.prototype = new ArrayLikeSequence(); - - ArrayWrapper.prototype.root = function root() { - return this; - }; - - ArrayWrapper.prototype.isAsync = function isAsync() { - return false; - }; - - /** - * Returns the element at the specified index in the source array. - * - * @param {number} i The index to access. - * @returns {*} The element. - */ - ArrayWrapper.prototype.get = function get(i) { - return this.source[i]; - }; - - /** - * Returns the length of the source array. - * - * @returns {number} The length. - */ - ArrayWrapper.prototype.length = function length() { - return this.source.length; - }; - - /** - * An optimized version of {@link Sequence#each}. - */ - ArrayWrapper.prototype.each = function each(fn) { - return forEach(this.source, fn); - }; - - /** - * An optimized version of {@link Sequence#map}. - */ - ArrayWrapper.prototype.map = function map(mapFn) { - return new MappedArrayWrapper(this, createCallback(mapFn)); - }; - - /** - * An optimized version of {@link Sequence#filter}. - */ - ArrayWrapper.prototype.filter = function filter(filterFn) { - return new FilteredArrayWrapper(this, createCallback(filterFn)); - }; - - /** - * An optimized version of {@link Sequence#uniq}. - */ - ArrayWrapper.prototype.uniq = function uniq(keyFn) { - return new UniqueArrayWrapper(this, keyFn); - }; - - /** - * An optimized version of {@link ArrayLikeSequence#concat}. - * - * @param {...*} var_args - */ - ArrayWrapper.prototype.concat = function concat(var_args) { - if (arguments.length === 1 && arguments[0] instanceof Array) { - return new ConcatArrayWrapper(this, (/** @type {Array} */ var_args)); - } else { - return ArrayLikeSequence.prototype.concat.apply(this, arguments); - } - }; - - /** - * An optimized version of {@link Sequence#toArray}. - */ - ArrayWrapper.prototype.toArray = function toArray() { - return this.source.slice(0); - }; - - /** - * @constructor - */ - function MappedArrayWrapper(parent, mapFn) { - this.parent = parent; - this.mapFn = mapFn; - } - - MappedArrayWrapper.prototype = new ArrayLikeSequence(); - - MappedArrayWrapper.prototype.get = function get(i) { - var source = this.parent.source; - - if (i < 0 || i >= source.length) { - return undefined; - } - - return this.mapFn(source[i]); - }; - - MappedArrayWrapper.prototype.length = function length() { - return this.parent.source.length; - }; - - MappedArrayWrapper.prototype.each = function each(fn) { - var source = this.parent.source, - length = source.length, - mapFn = this.mapFn, - i = -1; - - while (++i < length) { - if (fn(mapFn(source[i], i), i) === false) { - return false; - } - } - - return true; - }; - - /** - * @constructor - */ - function FilteredArrayWrapper(parent, filterFn) { - this.parent = parent; - this.filterFn = filterFn; - } - - FilteredArrayWrapper.prototype = new FilteredSequence(); - - FilteredArrayWrapper.prototype.each = function each(fn) { - var source = this.parent.source, - filterFn = this.filterFn, - length = source.length, - i = -1, - j = 0, - e; - - while (++i < length) { - e = source[i]; - if (filterFn(e, i) && fn(e, j++) === false) { - return false; - } - } - - return true; - }; - - /** - * @constructor - */ - function UniqueArrayWrapper(parent, keyFn) { - this.parent = parent; - this.each = getEachForSource(parent.source); - this.keyFn = keyFn; - } - - UniqueArrayWrapper.prototype = new Sequence(); - - UniqueArrayWrapper.prototype.eachNoCache = function eachNoCache(fn) { - var source = this.parent.source, - keyFn = this.keyFn, - length = source.length, - find = arrayContainsBefore, - value, - - // Yes, this is hideous. - // Trying to get performance first, will refactor next! - i = -1, - k = 0; - - while (++i < length) { - value = source[i]; - if (!find(source, value, i, keyFn) && fn(value, k++) === false) { - return false; - } - } - - return true; - }; - - UniqueArrayWrapper.prototype.eachArrayCache = function eachArrayCache(fn) { - // Basically the same implementation as w/ the set, but using an array because - // it's cheaper for smaller sequences. - var source = this.parent.source, - keyFn = this.keyFn, - length = source.length, - cache = [], - find = arrayContains, - key, value, - i = -1, - j = 0; - - if (keyFn) { - keyFn = createCallback(keyFn); - while (++i < length) { - value = source[i]; - key = keyFn(value); - if (!find(cache, key)) { - cache.push(key); - if (fn(value, j++) === false) { - return false; - } - } - } - - } else { - while (++i < length) { - value = source[i]; - if (!find(cache, value)) { - cache.push(value); - if (fn(value, j++) === false) { - return false; - } - } - } - } - - return true; - }; - - UniqueArrayWrapper.prototype.eachSetCache = UniqueSequence.prototype.each; - - /** - * My latest findings here... - * - * So I hadn't really given the set-based approach enough credit. The main issue - * was that my Set implementation was totally not optimized at all. After pretty - * heavily optimizing it (just take a look; it's a monstrosity now!), it now - * becomes the fastest option for much smaller values of N. - */ - function getEachForSource(source) { - if (source.length < 40) { - return UniqueArrayWrapper.prototype.eachNoCache; - } else if (source.length < 100) { - return UniqueArrayWrapper.prototype.eachArrayCache; - } else { - return UniqueArrayWrapper.prototype.eachSetCache; - } - } - - /** - * @constructor - */ - function ConcatArrayWrapper(parent, other) { - this.parent = parent; - this.other = other; - } - - ConcatArrayWrapper.prototype = new ArrayLikeSequence(); - - ConcatArrayWrapper.prototype.get = function get(i) { - var source = this.parent.source, - sourceLength = source.length; - - if (i < sourceLength) { - return source[i]; - } else { - return this.other[i - sourceLength]; - } - }; - - ConcatArrayWrapper.prototype.length = function length() { - return this.parent.source.length + this.other.length; - }; - - ConcatArrayWrapper.prototype.each = function each(fn) { - var source = this.parent.source, - sourceLength = source.length, - other = this.other, - otherLength = other.length, - i = 0, - j = -1; - - while (++j < sourceLength) { - if (fn(source[j], i++) === false) { - return false; - } - } - - j = -1; - while (++j < otherLength) { - if (fn(other[j], i++) === false) { - return false; - } - } - - return true; - }; - - /** - * An `ObjectLikeSequence` object represents a sequence of key/value pairs. - * - * The initial sequence you get by wrapping an object with `Lazy(object)` is - * an `ObjectLikeSequence`. - * - * All methods of `ObjectLikeSequence` that conceptually should return - * something like an object return another `ObjectLikeSequence`. - * - * @public - * @constructor - * - * @examples - * var obj = { foo: 'bar' }; - * - * Lazy(obj).assign({ bar: 'baz' }) // instanceof Lazy.ObjectLikeSequence - * Lazy(obj).defaults({ bar: 'baz' }) // instanceof Lazy.ObjectLikeSequence - * Lazy(obj).invert() // instanceof Lazy.ObjectLikeSequence - */ - function ObjectLikeSequence() {} - - ObjectLikeSequence.prototype = new Sequence(); - - /** - * Create a new constructor function for a type inheriting from - * `ObjectLikeSequence`. - * - * @public - * @param {string|Array.} methodName The name(s) of the method(s) to be - * used for constructing the new sequence. The method will be attached to - * the `ObjectLikeSequence` prototype so that it can be chained with any other - * methods that return object-like sequences. - * @param {Object} overrides An object containing function overrides for this - * new sequence type. **Must** include `each`. *May* include `init` and - * `get` (for looking up an element by key). - * @returns {Function} A constructor for a new type inheriting from - * `ObjectLikeSequence`. - * - * @examples - * function downcaseKey(value, key) { - * return [key.toLowerCase(), value]; - * } - * - * Lazy.ObjectLikeSequence.define("caseInsensitive", { - * init: function() { - * var downcased = this.parent - * .map(downcaseKey) - * .toObject(); - * this.downcased = Lazy(downcased); - * }, - * - * get: function(key) { - * return this.downcased.get(key.toLowerCase()); - * }, - * - * each: function(fn) { - * return this.downcased.each(fn); - * } - * }); - * - * Lazy({ Foo: 'bar' }).caseInsensitive() // sequence: { foo: 'bar' } - * Lazy({ FOO: 'bar' }).caseInsensitive().get('foo') // => 'bar' - * Lazy({ FOO: 'bar' }).caseInsensitive().get('FOO') // => 'bar' - */ - ObjectLikeSequence.define = function define(methodName, overrides) { - if (!overrides || typeof overrides.each !== 'function') { - throw new Error("A custom object-like sequence must implement *at least* each!"); - } - - return defineSequenceType(ObjectLikeSequence, methodName, overrides); - }; - - ObjectLikeSequence.prototype.value = function value() { - return this.toObject(); - }; - - /** - * Gets the element at the specified key in this sequence. - * - * @public - * @param {string} key The key. - * @returns {*} The element. - * - * @examples - * Lazy({ foo: "bar" }).get("foo") // => "bar" - * Lazy({ foo: "bar" }).extend({ foo: "baz" }).get("foo") // => "baz" - * Lazy({ foo: "bar" }).defaults({ bar: "baz" }).get("bar") // => "baz" - * Lazy({ foo: "bar" }).invert().get("bar") // => "foo" - * Lazy({ foo: 1, bar: 2 }).pick(["foo"]).get("foo") // => 1 - * Lazy({ foo: 1, bar: 2 }).pick(["foo"]).get("bar") // => undefined - * Lazy({ foo: 1, bar: 2 }).omit(["foo"]).get("bar") // => 2 - * Lazy({ foo: 1, bar: 2 }).omit(["foo"]).get("foo") // => undefined - */ - ObjectLikeSequence.prototype.get = function get(key) { - var pair = this.pairs().find(function(pair) { - return pair[0] === key; - }); - - return pair ? pair[1] : undefined; - }; - - /** - * Returns a {@link Sequence} whose elements are the keys of this object-like - * sequence. - * - * @public - * @returns {Sequence} The sequence based on this sequence's keys. - * - * @examples - * Lazy({ hello: "hola", goodbye: "hasta luego" }).keys() // sequence: ["hello", "goodbye"] - */ - ObjectLikeSequence.prototype.keys = function keys() { - return this.map(function(v, k) { return k; }); - }; - - /** - * Returns a {@link Sequence} whose elements are the values of this object-like - * sequence. - * - * @public - * @returns {Sequence} The sequence based on this sequence's values. - * - * @examples - * Lazy({ hello: "hola", goodbye: "hasta luego" }).values() // sequence: ["hola", "hasta luego"] - */ - ObjectLikeSequence.prototype.values = function values() { - return this.map(function(v, k) { return v; }); - }; - - /** - * Throws an exception. Asynchronous iteration over object-like sequences is - * not supported. - * - * @public - * @examples - * Lazy({ foo: 'bar' }).async() // throws - */ - ObjectLikeSequence.prototype.async = function async() { - throw new Error('An ObjectLikeSequence does not support asynchronous iteration.'); - }; - - ObjectLikeSequence.prototype.filter = function filter(filterFn) { - return new FilteredObjectLikeSequence(this, createCallback(filterFn)); - }; - - function FilteredObjectLikeSequence(parent, filterFn) { - this.parent = parent; - this.filterFn = filterFn; - } - - FilteredObjectLikeSequence.prototype = new ObjectLikeSequence(); - - FilteredObjectLikeSequence.prototype.each = function each(fn) { - var filterFn = this.filterFn; - - return this.parent.each(function(v, k) { - if (filterFn(v, k)) { - return fn(v, k); - } - }); - }; - - /** - * Returns this same sequence. (Reversing an object-like sequence doesn't make - * any sense.) - */ - ObjectLikeSequence.prototype.reverse = function reverse() { - return this; - }; - - /** - * Returns an {@link ObjectLikeSequence} whose elements are the combination of - * this sequence and another object. In the case of a key appearing in both this - * sequence and the given object, the other object's value will override the - * one in this sequence. - * - * @public - * @aka extend - * @param {Object} other The other object to assign to this sequence. - * @returns {ObjectLikeSequence} A new sequence comprising elements from this - * sequence plus the contents of `other`. - * - * @examples - * Lazy({ "uno": 1, "dos": 2 }).assign({ "tres": 3 }) // sequence: { uno: 1, dos: 2, tres: 3 } - * Lazy({ foo: "bar" }).assign({ foo: "baz" }); // sequence: { foo: "baz" } - */ - ObjectLikeSequence.prototype.assign = function assign(other) { - return new AssignSequence(this, other); - }; - - ObjectLikeSequence.prototype.extend = function extend(other) { - return this.assign(other); - }; - - /** - * @constructor - */ - function AssignSequence(parent, other) { - this.parent = parent; - this.other = other; - } - - AssignSequence.prototype = new ObjectLikeSequence(); - - AssignSequence.prototype.get = function get(key) { - return this.other[key] || this.parent.get(key); - }; - - AssignSequence.prototype.each = function each(fn) { - var merged = new Set(), - done = false; - - Lazy(this.other).each(function(value, key) { - if (fn(value, key) === false) { - done = true; - return false; - } - - merged.add(key); - }); - - if (!done) { - return this.parent.each(function(value, key) { - if (!merged.contains(key) && fn(value, key) === false) { - return false; - } - }); - } - }; - - /** - * Returns an {@link ObjectLikeSequence} whose elements are the combination of - * this sequence and a 'default' object. In the case of a key appearing in both - * this sequence and the given object, this sequence's value will override the - * default object's. - * - * @public - * @param {Object} defaults The 'default' object to use for missing keys in this - * sequence. - * @returns {ObjectLikeSequence} A new sequence comprising elements from this - * sequence supplemented by the contents of `defaults`. - * - * @examples - * Lazy({ name: "Dan" }).defaults({ name: "User", password: "passw0rd" }) // sequence: { name: "Dan", password: "passw0rd" } - */ - ObjectLikeSequence.prototype.defaults = function defaults(defaults) { - return new DefaultsSequence(this, defaults); - }; - - /** - * @constructor - */ - function DefaultsSequence(parent, defaults) { - this.parent = parent; - this.defaults = defaults; - } - - DefaultsSequence.prototype = new ObjectLikeSequence(); - - DefaultsSequence.prototype.get = function get(key) { - return this.parent.get(key) || this.defaults[key]; - }; - - DefaultsSequence.prototype.each = function each(fn) { - var merged = new Set(), - done = false; - - this.parent.each(function(value, key) { - if (fn(value, key) === false) { - done = true; - return false; - } - - if (typeof value !== "undefined") { - merged.add(key); - } - }); - - if (!done) { - Lazy(this.defaults).each(function(value, key) { - if (!merged.contains(key) && fn(value, key) === false) { - return false; - } - }); - } - }; - - /** - * Returns an {@link ObjectLikeSequence} whose values are this sequence's keys, - * and whose keys are this sequence's values. - * - * @public - * @returns {ObjectLikeSequence} A new sequence comprising the inverted keys and - * values from this sequence. - * - * @examples - * Lazy({ first: "Dan", last: "Tao" }).invert() // sequence: { Dan: "first", Tao: "last" } - */ - ObjectLikeSequence.prototype.invert = function invert() { - return new InvertedSequence(this); - }; - - /** - * @constructor - */ - function InvertedSequence(parent) { - this.parent = parent; - } - - InvertedSequence.prototype = new ObjectLikeSequence(); - - InvertedSequence.prototype.each = function each(fn) { - this.parent.each(function(value, key) { - return fn(key, value); - }); - }; - - /** - * Produces an {@link ObjectLikeSequence} consisting of all the recursively - * merged values from this and the given object(s) or sequence(s). - * - * Note that by default this method only merges "vanilla" objects (bags of - * key/value pairs), not arrays or any other custom object types. To customize - * how merging works, you can provide the mergeFn argument, e.g. to handling - * merging arrays, strings, or other types of objects. - * - * @public - * @param {...Object|ObjectLikeSequence} others The other object(s) or - * sequence(s) whose values will be merged into this one. - * @param {Function=} mergeFn An optional function used to customize merging - * behavior. The function should take two values as parameters and return - * whatever the "merged" form of those values is. If the function returns - * undefined then the new value will simply replace the old one in the - * final result. - * @returns {ObjectLikeSequence} The new sequence consisting of merged values. - * - * @examples - * // These examples are completely stolen from Lo-Dash's documentation: - * // lodash.com/docs#merge - * - * var names = { - * 'characters': [ - * { 'name': 'barney' }, - * { 'name': 'fred' } - * ] - * }; - * - * var ages = { - * 'characters': [ - * { 'age': 36 }, - * { 'age': 40 } - * ] - * }; - * - * var food = { - * 'fruits': ['apple'], - * 'vegetables': ['beet'] - * }; - * - * var otherFood = { - * 'fruits': ['banana'], - * 'vegetables': ['carrot'] - * }; - * - * function mergeArrays(a, b) { - * return Array.isArray(a) ? a.concat(b) : undefined; - * } - * - * Lazy(names).merge(ages); // => sequence: { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } - * Lazy(food).merge(otherFood, mergeArrays); // => sequence: { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } - * - * // ----- Now for my own tests: ----- - * - * // merges objects - * Lazy({ foo: 1 }).merge({ foo: 2 }); // => sequence: { foo: 2 } - * Lazy({ foo: 1 }).merge({ bar: 2 }); // => sequence: { foo: 1, bar: 2 } - * - * // goes deep - * Lazy({ foo: { bar: 1 } }).merge({ foo: { bar: 2 } }); // => sequence: { foo: { bar: 2 } } - * Lazy({ foo: { bar: 1 } }).merge({ foo: { baz: 2 } }); // => sequence: { foo: { bar: 1, baz: 2 } } - * Lazy({ foo: { bar: 1 } }).merge({ foo: { baz: 2 } }); // => sequence: { foo: { bar: 1, baz: 2 } } - * - * // gives precedence to later sources - * Lazy({ foo: 1 }).merge({ bar: 2 }, { bar: 3 }); // => sequence: { foo: 1, bar: 3 } - * - * // undefined gets passed over - * Lazy({ foo: 1 }).merge({ foo: undefined }); // => sequence: { foo: 1 } - * - * // null doesn't get passed over - * Lazy({ foo: 1 }).merge({ foo: null }); // => sequence: { foo: null } - * - * // array contents get merged as well - * Lazy({ foo: [{ bar: 1 }] }).merge({ foo: [{ baz: 2 }] }); // => sequence: { foo: [{ bar: 1, baz: 2}] } - */ - ObjectLikeSequence.prototype.merge = function merge(var_args) { - var mergeFn = arguments.length > 1 && typeof arguments[arguments.length - 1] === "function" ? - arrayPop.call(arguments) : null; - return new MergedSequence(this, arraySlice.call(arguments, 0), mergeFn); - }; - - /** - * @constructor - */ - function MergedSequence(parent, others, mergeFn) { - this.parent = parent; - this.others = others; - this.mergeFn = mergeFn; - } - - MergedSequence.prototype = new ObjectLikeSequence(); - - MergedSequence.prototype.each = function each(fn) { - var others = this.others, - mergeFn = this.mergeFn || mergeObjects, - keys = {}; - - var iteratedFullSource = this.parent.each(function(value, key) { - var merged = value; - - forEach(others, function(other) { - if (key in other) { - merged = mergeFn(merged, other[key]); - } - }); - - keys[key] = true; - - return fn(merged, key); - }); - - if (iteratedFullSource === false) { - return false; - } - - var remaining = {}; - - forEach(others, function(other) { - for (var k in other) { - if (!keys[k]) { - remaining[k] = mergeFn(remaining[k], other[k]); - } - } - }); - - return Lazy(remaining).each(fn); - }; - - /** - * @private - * @examples - * mergeObjects({ foo: 1 }, { bar: 2 }); // => { foo: 1, bar: 2 } - * mergeObjects({ foo: { bar: 1 } }, { foo: { baz: 2 } }); // => { foo: { bar: 1, baz: 2 } } - * mergeObjects({ foo: { bar: 1 } }, { foo: undefined }); // => { foo: { bar: 1 } } - * mergeObjects({ foo: { bar: 1 } }, { foo: null }); // => { foo: null } - * mergeObjects({ array: [0, 1, 2] }, { array: [3, 4, 5] }).array; // instanceof Array - * mergeObjects({ date: new Date() }, { date: new Date() }).date; // instanceof Date - * mergeObjects([{ foo: 1 }], [{ bar: 2 }]); // => [{ foo: 1, bar: 2 }] - */ - function mergeObjects(a, b) { - var merged, prop; - - if (typeof b === 'undefined') { - return a; - } - - // Check that we're dealing with two objects or two arrays. - if (isVanillaObject(a) && isVanillaObject(b)) { - merged = {}; - } else if (a instanceof Array && b instanceof Array) { - merged = []; - } else { - // Otherwise there's no merging to do -- just replace a w/ b. - return b; - } - - for (prop in a) { - merged[prop] = mergeObjects(a[prop], b[prop]); - } - for (prop in b) { - if (!merged[prop]) { - merged[prop] = b[prop]; - } - } - return merged; - } - - /** - * Checks whether an object is a "vanilla" object, i.e. {'foo': 'bar'} as - * opposed to an array, date, etc. - * - * @private - * @examples - * isVanillaObject({foo: 'bar'}); // => true - * isVanillaObject(new Date()); // => false - * isVanillaObject([1, 2, 3]); // => false - */ - function isVanillaObject(object) { - return object && object.constructor === Object; - } - - /** - * Creates a {@link Sequence} consisting of the keys from this sequence whose - * values are functions. - * - * @public - * @aka methods - * @returns {Sequence} The new sequence. - * - * @examples - * var dog = { - * name: "Fido", - * breed: "Golden Retriever", - * bark: function() { console.log("Woof!"); }, - * wagTail: function() { console.log("TODO: implement robotic dog interface"); } - * }; - * - * Lazy(dog).functions() // sequence: ["bark", "wagTail"] - */ - ObjectLikeSequence.prototype.functions = function functions() { - return this - .filter(function(v, k) { return typeof(v) === "function"; }) - .map(function(v, k) { return k; }); - }; - - ObjectLikeSequence.prototype.methods = function methods() { - return this.functions(); - }; - - /** - * Creates an {@link ObjectLikeSequence} consisting of the key/value pairs from - * this sequence whose keys are included in the given array of property names. - * - * @public - * @param {Array} properties An array of the properties to "pick" from this - * sequence. - * @returns {ObjectLikeSequence} The new sequence. - * - * @examples - * var players = { - * "who": "first", - * "what": "second", - * "i don't know": "third" - * }; - * - * Lazy(players).pick(["who", "what"]) // sequence: { who: "first", what: "second" } - */ - ObjectLikeSequence.prototype.pick = function pick(properties) { - return new PickSequence(this, properties); - }; - - /** - * @constructor - */ - function PickSequence(parent, properties) { - this.parent = parent; - this.properties = properties; - } - - PickSequence.prototype = new ObjectLikeSequence(); - - PickSequence.prototype.get = function get(key) { - return arrayContains(this.properties, key) ? this.parent.get(key) : undefined; - }; - - PickSequence.prototype.each = function each(fn) { - var inArray = arrayContains, - properties = this.properties; - - return this.parent.each(function(value, key) { - if (inArray(properties, key)) { - return fn(value, key); - } - }); - }; - - /** - * Creates an {@link ObjectLikeSequence} consisting of the key/value pairs from - * this sequence excluding those with the specified keys. - * - * @public - * @param {Array} properties An array of the properties to *omit* from this - * sequence. - * @returns {ObjectLikeSequence} The new sequence. - * - * @examples - * var players = { - * "who": "first", - * "what": "second", - * "i don't know": "third" - * }; - * - * Lazy(players).omit(["who", "what"]) // sequence: { "i don't know": "third" } - */ - ObjectLikeSequence.prototype.omit = function omit(properties) { - return new OmitSequence(this, properties); - }; - - /** - * @constructor - */ - function OmitSequence(parent, properties) { - this.parent = parent; - this.properties = properties; - } - - OmitSequence.prototype = new ObjectLikeSequence(); - - OmitSequence.prototype.get = function get(key) { - return arrayContains(this.properties, key) ? undefined : this.parent.get(key); - }; - - OmitSequence.prototype.each = function each(fn) { - var inArray = arrayContains, - properties = this.properties; - - return this.parent.each(function(value, key) { - if (!inArray(properties, key)) { - return fn(value, key); - } - }); - }; - - /** - * Maps the key/value pairs in this sequence to arrays. - * - * @public - * @aka toArray - * @returns {Sequence} An sequence of `[key, value]` pairs. - * - * @examples - * var colorCodes = { - * red: "#f00", - * green: "#0f0", - * blue: "#00f" - * }; - * - * Lazy(colorCodes).pairs() // sequence: [["red", "#f00"], ["green", "#0f0"], ["blue", "#00f"]] - */ - ObjectLikeSequence.prototype.pairs = function pairs() { - return this.map(function(v, k) { return [k, v]; }); - }; - - /** - * Creates an array from the key/value pairs in this sequence. - * - * @public - * @returns {Array} An array of `[key, value]` elements. - * - * @examples - * var colorCodes = { - * red: "#f00", - * green: "#0f0", - * blue: "#00f" - * }; - * - * Lazy(colorCodes).toArray() // => [["red", "#f00"], ["green", "#0f0"], ["blue", "#00f"]] - */ - ObjectLikeSequence.prototype.toArray = function toArray() { - return this.pairs().toArray(); - }; - - /** - * Creates an object with the key/value pairs from this sequence. - * - * @public - * @returns {Object} An object with the same key/value pairs as this sequence. - * - * @examples - * var colorCodes = { - * red: "#f00", - * green: "#0f0", - * blue: "#00f" - * }; - * - * Lazy(colorCodes).toObject() // => { red: "#f00", green: "#0f0", blue: "#00f" } - */ - ObjectLikeSequence.prototype.toObject = function toObject() { - return this.reduce(function(object, value, key) { - object[key] = value; - return object; - }, {}); - }; - - // Now that we've fully initialized the ObjectLikeSequence prototype, we can - // actually set the prototypes for GroupedSequence, IndexedSequence, and - // CountedSequence. - - GroupedSequence.prototype = new ObjectLikeSequence(); - - GroupedSequence.prototype.each = function each(fn) { - var keyFn = createCallback(this.keyFn), - valFn = createCallback(this.valFn), - result; - - result = this.parent.reduce(function(grouped,e) { - var key = keyFn(e), - val = valFn(e); - if (!(grouped[key] instanceof Array)) { - grouped[key] = [val]; - } else { - grouped[key].push(val); - } - return grouped; - },{}); - - return transform(function(grouped) { - for (var key in grouped) { - if (fn(grouped[key], key) === false) { - return false; - } - } - }, result); - }; - - IndexedSequence.prototype = new ObjectLikeSequence(); - - IndexedSequence.prototype.each = function each(fn) { - var keyFn = createCallback(this.keyFn), - valFn = createCallback(this.valFn), - indexed = {}; - - return this.parent.each(function(e) { - var key = keyFn(e), - val = valFn(e); - - if (!indexed[key]) { - indexed[key] = val; - return fn(val, key); - } - }); - }; - - CountedSequence.prototype = new ObjectLikeSequence(); - - CountedSequence.prototype.each = function each(fn) { - var keyFn = createCallback(this.keyFn), - counted = {}; - - this.parent.each(function(e) { - var key = keyFn(e); - if (!counted[key]) { - counted[key] = 1; - } else { - counted[key] += 1; - } - }); - - for (var key in counted) { - if (fn(counted[key], key) === false) { - return false; - } - } - - return true; - }; - - /** - * Watches for all changes to a specified property (or properties) of an - * object and produces a sequence whose elements have the properties - * `{ property, value }` indicating which property changed and what it was - * changed to. - * - * Note that this method **only works on directly wrapped objects**; it will - * *not* work on any arbitrary {@link ObjectLikeSequence}. - * - * @public - * @param {(string|Array)=} propertyNames A property name or array of property - * names to watch. If this parameter is `undefined`, all of the object's - * current (enumerable) properties will be watched. - * @returns {Sequence} A sequence comprising `{ property, value }` objects - * describing each change to the specified property/properties. - * - * @examples - * var obj = {}, - * changes = []; - * - * Lazy(obj).watch('foo').each(function(change) { - * changes.push(change); - * }); - * - * obj.foo = 1; - * obj.bar = 2; - * obj.foo = 3; - * - * obj.foo; // => 3 - * changes; // => [{ property: 'foo', value: 1 }, { property: 'foo', value: 3 }] - */ - ObjectLikeSequence.prototype.watch = function watch(propertyNames) { - throw new Error('You can only call #watch on a directly wrapped object.'); - }; - - /** - * @constructor - */ - function ObjectWrapper(source) { - this.source = source; - } - - ObjectWrapper.prototype = new ObjectLikeSequence(); - - ObjectWrapper.prototype.root = function root() { - return this; - }; - - ObjectWrapper.prototype.isAsync = function isAsync() { - return false; - }; - - ObjectWrapper.prototype.get = function get(key) { - return this.source[key]; - }; - - ObjectWrapper.prototype.each = function each(fn) { - var source = this.source, - key; - - for (key in source) { - if (fn(source[key], key) === false) { - return false; - } - } - - return true; - }; - - /** - * A `StringLikeSequence` represents a sequence of characters. - * - * The initial sequence you get by wrapping a string with `Lazy(string)` is a - * `StringLikeSequence`. - * - * All methods of `StringLikeSequence` that conceptually should return - * something like a string return another `StringLikeSequence`. - * - * @public - * @constructor - * - * @examples - * function upcase(str) { return str.toUpperCase(); } - * - * Lazy('foo') // instanceof Lazy.StringLikeSequence - * Lazy('foo').toUpperCase() // instanceof Lazy.StringLikeSequence - * Lazy('foo').reverse() // instanceof Lazy.StringLikeSequence - * Lazy('foo').take(2) // instanceof Lazy.StringLikeSequence - * Lazy('foo').drop(1) // instanceof Lazy.StringLikeSequence - * Lazy('foo').substring(1) // instanceof Lazy.StringLikeSequence - * - * // Note that `map` does not create a `StringLikeSequence` because there's - * // no guarantee the mapping function will return characters. In the event - * // you do want to map a string onto a string-like sequence, use - * // `mapString`: - * Lazy('foo').map(Lazy.identity) // instanceof Lazy.ArrayLikeSequence - * Lazy('foo').mapString(Lazy.identity) // instanceof Lazy.StringLikeSequence - */ - function StringLikeSequence() {} - - StringLikeSequence.prototype = new ArrayLikeSequence(); - - /** - * Create a new constructor function for a type inheriting from - * `StringLikeSequence`. - * - * @public - * @param {string|Array.} methodName The name(s) of the method(s) to be - * used for constructing the new sequence. The method will be attached to - * the `StringLikeSequence` prototype so that it can be chained with any other - * methods that return string-like sequences. - * @param {Object} overrides An object containing function overrides for this - * new sequence type. Has the same requirements as - * {@link ArrayLikeSequence.define}. - * @returns {Function} A constructor for a new type inheriting from - * `StringLikeSequence`. - * - * @examples - * Lazy.StringLikeSequence.define("zomg", { - * length: function() { - * return this.parent.length() + "!!ZOMG!!!1".length; - * }, - * - * get: function(i) { - * if (i < this.parent.length()) { - * return this.parent.get(i); - * } - * return "!!ZOMG!!!1".charAt(i - this.parent.length()); - * } - * }); - * - * Lazy('foo').zomg() // sequence: "foo!!ZOMG!!!1" - */ - StringLikeSequence.define = function define(methodName, overrides) { - if (!overrides || typeof overrides.get !== 'function') { - throw new Error("A custom string-like sequence must implement *at least* get!"); - } - - return defineSequenceType(StringLikeSequence, methodName, overrides); - }; - - StringLikeSequence.prototype.value = function value() { - return this.toString(); - }; - - /** - * Returns an {@link IndexedIterator} that will step over each character in this - * sequence one by one. - * - * @returns {IndexedIterator} The iterator. - */ - StringLikeSequence.prototype.getIterator = function getIterator() { - return new CharIterator(this); - }; - - /** - * @constructor - */ - function CharIterator(source) { - this.source = Lazy(source); - this.index = -1; - } - - CharIterator.prototype.current = function current() { - return this.source.charAt(this.index); - }; - - CharIterator.prototype.moveNext = function moveNext() { - return (++this.index < this.source.length()); - }; - - /** - * Returns the character at the given index of this sequence, or the empty - * string if the specified index lies outside the bounds of the sequence. - * - * @public - * @param {number} i The index of this sequence. - * @returns {string} The character at the specified index. - * - * @examples - * Lazy("foo").charAt(0) // => "f" - * Lazy("foo").charAt(-1) // => "" - * Lazy("foo").charAt(10) // => "" - */ - StringLikeSequence.prototype.charAt = function charAt(i) { - return this.get(i); - }; - - /** - * Returns the character code at the given index of this sequence, or `NaN` if - * the index lies outside the bounds of the sequence. - * - * @public - * @param {number} i The index of the character whose character code you want. - * @returns {number} The character code. - * - * @examples - * Lazy("abc").charCodeAt(0) // => 97 - * Lazy("abc").charCodeAt(-1) // => NaN - * Lazy("abc").charCodeAt(10) // => NaN - */ - StringLikeSequence.prototype.charCodeAt = function charCodeAt(i) { - var char = this.charAt(i); - if (!char) { return NaN; } - - return char.charCodeAt(0); - }; - - /** - * Returns a {@link StringLikeSequence} comprising the characters from *this* - * sequence starting at `start` and ending at `stop` (exclusive), or---if - * `stop` is `undefined`, including the rest of the sequence. - * - * @public - * @param {number} start The index where this sequence should begin. - * @param {number=} stop The index (exclusive) where this sequence should end. - * @returns {StringLikeSequence} The new sequence. - * - * @examples - * Lazy("foo").substring(1) // sequence: "oo" - * Lazy("foo").substring(-1) // sequence: "foo" - * Lazy("hello").substring(1, 3) // sequence: "el" - * Lazy("hello").substring(1, 9) // sequence: "ello" - */ - StringLikeSequence.prototype.substring = function substring(start, stop) { - return new StringSegment(this, start, stop); - }; - - /** - * @constructor - */ - function StringSegment(parent, start, stop) { - this.parent = parent; - this.start = Math.max(0, start); - this.stop = stop; - } - - StringSegment.prototype = new StringLikeSequence(); - - StringSegment.prototype.get = function get(i) { - return this.parent.get(i + this.start); - }; - - StringSegment.prototype.length = function length() { - return (typeof this.stop === "number" ? this.stop : this.parent.length()) - this.start; - }; - - /** - * An optimized version of {@link Sequence#first} that returns another - * {@link StringLikeSequence} (or just the first character, if `count` is - * undefined). - * - * @public - * @examples - * Lazy('foo').first() // => 'f' - * Lazy('fo').first(2) // sequence: 'fo' - * Lazy('foo').first(10) // sequence: 'foo' - * Lazy('foo').toUpperCase().first() // => 'F' - * Lazy('foo').toUpperCase().first(2) // sequence: 'FO' - */ - StringLikeSequence.prototype.first = function first(count) { - if (typeof count === "undefined") { - return this.charAt(0); - } - - return this.substring(0, count); - }; - - /** - * An optimized version of {@link Sequence#last} that returns another - * {@link StringLikeSequence} (or just the last character, if `count` is - * undefined). - * - * @public - * @examples - * Lazy('foo').last() // => 'o' - * Lazy('foo').last(2) // sequence: 'oo' - * Lazy('foo').last(10) // sequence: 'foo' - * Lazy('foo').toUpperCase().last() // => 'O' - * Lazy('foo').toUpperCase().last(2) // sequence: 'OO' - */ - StringLikeSequence.prototype.last = function last(count) { - if (typeof count === "undefined") { - return this.charAt(this.length() - 1); - } - - return this.substring(this.length() - count); - }; - - StringLikeSequence.prototype.drop = function drop(count) { - return this.substring(count); - }; - - /** - * Finds the index of the first occurrence of the given substring within this - * sequence, starting from the specified index (or the beginning of the - * sequence). - * - * @public - * @param {string} substring The substring to search for. - * @param {number=} startIndex The index from which to start the search. - * @returns {number} The first index where the given substring is found, or - * -1 if it isn't in the sequence. - * - * @examples - * Lazy('canal').indexOf('a') // => 1 - * Lazy('canal').indexOf('a', 2) // => 3 - * Lazy('canal').indexOf('ana') // => 1 - * Lazy('canal').indexOf('andy') // => -1 - * Lazy('canal').indexOf('x') // => -1 - */ - StringLikeSequence.prototype.indexOf = function indexOf(substring, startIndex) { - return this.toString().indexOf(substring, startIndex); - }; - - /** - * Finds the index of the last occurrence of the given substring within this - * sequence, starting from the specified index (or the end of the sequence) - * and working backwards. - * - * @public - * @param {string} substring The substring to search for. - * @param {number=} startIndex The index from which to start the search. - * @returns {number} The last index where the given substring is found, or - * -1 if it isn't in the sequence. - * - * @examples - * Lazy('canal').lastIndexOf('a') // => 3 - * Lazy('canal').lastIndexOf('a', 2) // => 1 - * Lazy('canal').lastIndexOf('ana') // => 1 - * Lazy('canal').lastIndexOf('andy') // => -1 - * Lazy('canal').lastIndexOf('x') // => -1 - */ - StringLikeSequence.prototype.lastIndexOf = function lastIndexOf(substring, startIndex) { - return this.toString().lastIndexOf(substring, startIndex); - }; - - /** - * Checks if this sequence contains a given substring. - * - * @public - * @param {string} substring The substring to check for. - * @returns {boolean} Whether or not this sequence contains `substring`. - * - * @examples - * Lazy('hello').contains('ell') // => true - * Lazy('hello').contains('') // => true - * Lazy('hello').contains('abc') // => false - */ - StringLikeSequence.prototype.contains = function contains(substring) { - return this.indexOf(substring) !== -1; - }; - - /** - * Checks if this sequence ends with a given suffix. - * - * @public - * @param {string} suffix The suffix to check for. - * @returns {boolean} Whether or not this sequence ends with `suffix`. - * - * @examples - * Lazy('foo').endsWith('oo') // => true - * Lazy('foo').endsWith('') // => true - * Lazy('foo').endsWith('abc') // => false - */ - StringLikeSequence.prototype.endsWith = function endsWith(suffix) { - return this.substring(this.length() - suffix.length).toString() === suffix; - }; - - /** - * Checks if this sequence starts with a given prefix. - * - * @public - * @param {string} prefix The prefix to check for. - * @returns {boolean} Whether or not this sequence starts with `prefix`. - * - * @examples - * Lazy('foo').startsWith('fo') // => true - * Lazy('foo').startsWith('') // => true - * Lazy('foo').startsWith('abc') // => false - */ - StringLikeSequence.prototype.startsWith = function startsWith(prefix) { - return this.substring(0, prefix.length).toString() === prefix; - }; - - /** - * Converts all of the characters in this string to uppercase. - * - * @public - * @returns {StringLikeSequence} A new sequence with the same characters as - * this sequence, all uppercase. - * - * @examples - * function nextLetter(a) { - * return String.fromCharCode(a.charCodeAt(0) + 1); - * } - * - * Lazy('foo').toUpperCase() // sequence: 'FOO' - * Lazy('foo').substring(1).toUpperCase() // sequence: 'OO' - * Lazy('abc').mapString(nextLetter).toUpperCase() // sequence: 'BCD' - */ - StringLikeSequence.prototype.toUpperCase = function toUpperCase() { - return this.mapString(function(char) { return char.toUpperCase(); }); - }; - - /** - * Converts all of the characters in this string to lowercase. - * - * @public - * @returns {StringLikeSequence} A new sequence with the same characters as - * this sequence, all lowercase. - * - * @examples - * function nextLetter(a) { - * return String.fromCharCode(a.charCodeAt(0) + 1); - * } - * - * Lazy('FOO').toLowerCase() // sequence: 'foo' - * Lazy('FOO').substring(1).toLowerCase() // sequence: 'oo' - * Lazy('ABC').mapString(nextLetter).toLowerCase() // sequence: 'bcd' - */ - StringLikeSequence.prototype.toLowerCase = function toLowerCase() { - return this.mapString(function(char) { return char.toLowerCase(); }); - }; - - /** - * Maps the characters of this sequence onto a new {@link StringLikeSequence}. - * - * @public - * @param {Function} mapFn The function used to map characters from this - * sequence onto the new sequence. - * @returns {StringLikeSequence} The new sequence. - * - * @examples - * function upcase(char) { return char.toUpperCase(); } - * - * Lazy("foo").mapString(upcase) // sequence: "FOO" - * Lazy("foo").mapString(upcase).charAt(0) // => "F" - * Lazy("foo").mapString(upcase).charCodeAt(0) // => 70 - * Lazy("foo").mapString(upcase).substring(1) // sequence: "OO" - */ - StringLikeSequence.prototype.mapString = function mapString(mapFn) { - return new MappedStringLikeSequence(this, mapFn); - }; - - /** - * @constructor - */ - function MappedStringLikeSequence(parent, mapFn) { - this.parent = parent; - this.mapFn = mapFn; - } - - MappedStringLikeSequence.prototype = new StringLikeSequence(); - MappedStringLikeSequence.prototype.get = IndexedMappedSequence.prototype.get; - MappedStringLikeSequence.prototype.length = IndexedMappedSequence.prototype.length; - - /** - * Returns a copy of this sequence that reads back to front. - * - * @public - * - * @examples - * Lazy("abcdefg").reverse() // sequence: "gfedcba" - */ - StringLikeSequence.prototype.reverse = function reverse() { - return new ReversedStringLikeSequence(this); - }; - - /** - * @constructor - */ - function ReversedStringLikeSequence(parent) { - this.parent = parent; - } - - ReversedStringLikeSequence.prototype = new StringLikeSequence(); - ReversedStringLikeSequence.prototype.get = IndexedReversedSequence.prototype.get; - ReversedStringLikeSequence.prototype.length = IndexedReversedSequence.prototype.length; - - StringLikeSequence.prototype.toString = function toString() { - return this.join(""); - }; - - /** - * Creates a {@link Sequence} comprising all of the matches for the specified - * pattern in the underlying string. - * - * @public - * @param {RegExp} pattern The pattern to match. - * @returns {Sequence} A sequence of all the matches. - * - * @examples - * Lazy("abracadabra").match(/a[bcd]/) // sequence: ["ab", "ac", "ad", "ab"] - * Lazy("fee fi fo fum").match(/\w+/) // sequence: ["fee", "fi", "fo", "fum"] - * Lazy("hello").match(/xyz/) // sequence: [] - */ - StringLikeSequence.prototype.match = function match(pattern) { - return new StringMatchSequence(this, pattern); - }; - - /** - * @constructor - */ - function StringMatchSequence(parent, pattern) { - this.parent = parent; - this.pattern = pattern; - } - - StringMatchSequence.prototype = new Sequence(); - - StringMatchSequence.prototype.getIterator = function getIterator() { - return new StringMatchIterator(this.parent.toString(), this.pattern); - }; - - /** - * @constructor - */ - function StringMatchIterator(source, pattern) { - this.source = source; - this.pattern = cloneRegex(pattern); - } - - StringMatchIterator.prototype.current = function current() { - return this.match[0]; - }; - - StringMatchIterator.prototype.moveNext = function moveNext() { - return !!(this.match = this.pattern.exec(this.source)); - }; - - /** - * Creates a {@link Sequence} comprising all of the substrings of this string - * separated by the given delimiter, which can be either a string or a regular - * expression. - * - * @public - * @param {string|RegExp} delimiter The delimiter to use for recognizing - * substrings. - * @returns {Sequence} A sequence of all the substrings separated by the given - * delimiter. - * - * @examples - * Lazy("foo").split("") // sequence: ["f", "o", "o"] - * Lazy("yo dawg").split(" ") // sequence: ["yo", "dawg"] - * Lazy("bah bah\tblack sheep").split(/\s+/) // sequence: ["bah", "bah", "black", "sheep"] - */ - StringLikeSequence.prototype.split = function split(delimiter) { - return new SplitStringSequence(this, delimiter); - }; - - /** - * @constructor - */ - function SplitStringSequence(parent, pattern) { - this.parent = parent; - this.pattern = pattern; - } - - SplitStringSequence.prototype = new Sequence(); - - SplitStringSequence.prototype.getIterator = function getIterator() { - var source = this.parent.toString(); - - if (this.pattern instanceof RegExp) { - if (this.pattern.source === "" || this.pattern.source === "(?:)") { - return new CharIterator(source); - } else { - return new SplitWithRegExpIterator(source, this.pattern); - } - } else if (this.pattern === "") { - return new CharIterator(source); - } else { - return new SplitWithStringIterator(source, this.pattern); - } - }; - - /** - * @constructor - */ - function SplitWithRegExpIterator(source, pattern) { - this.source = source; - this.pattern = cloneRegex(pattern); - } - - SplitWithRegExpIterator.prototype.current = function current() { - return this.source.substring(this.start, this.end); - }; - - SplitWithRegExpIterator.prototype.moveNext = function moveNext() { - if (!this.pattern) { - return false; - } - - var match = this.pattern.exec(this.source); - - if (match) { - this.start = this.nextStart ? this.nextStart : 0; - this.end = match.index; - this.nextStart = match.index + match[0].length; - return true; - - } else if (this.pattern) { - this.start = this.nextStart; - this.end = undefined; - this.nextStart = undefined; - this.pattern = undefined; - return true; - } - - return false; - }; - - /** - * @constructor - */ - function SplitWithStringIterator(source, delimiter) { - this.source = source; - this.delimiter = delimiter; - } - - SplitWithStringIterator.prototype.current = function current() { - return this.source.substring(this.leftIndex, this.rightIndex); - }; - - SplitWithStringIterator.prototype.moveNext = function moveNext() { - if (!this.finished) { - this.leftIndex = typeof this.leftIndex !== "undefined" ? - this.rightIndex + this.delimiter.length : - 0; - this.rightIndex = this.source.indexOf(this.delimiter, this.leftIndex); - } - - if (this.rightIndex === -1) { - this.finished = true; - this.rightIndex = undefined; - return true; - } - - return !this.finished; - }; - - /** - * Wraps a string exposing {@link #match} and {@link #split} methods that return - * {@link Sequence} objects instead of arrays, improving on the efficiency of - * JavaScript's built-in `String#split` and `String.match` methods and - * supporting asynchronous iteration. - * - * @param {string} source The string to wrap. - * @constructor - */ - function StringWrapper(source) { - this.source = source; - } - - StringWrapper.prototype = new StringLikeSequence(); - - StringWrapper.prototype.root = function root() { - return this; - }; - - StringWrapper.prototype.isAsync = function isAsync() { - return false; - }; - - StringWrapper.prototype.get = function get(i) { - return this.source.charAt(i); - }; - - StringWrapper.prototype.length = function length() { - return this.source.length; - }; - - StringWrapper.prototype.toString = function toString() { - return this.source; - }; - - /** - * A `GeneratedSequence` does not wrap an in-memory colllection but rather - * determines its elements on-the-fly during iteration according to a generator - * function. - * - * You create a `GeneratedSequence` by calling {@link Lazy.generate}. - * - * @public - * @constructor - * @param {function(number):*} generatorFn A function which accepts an index - * and returns a value for the element at that position in the sequence. - * @param {number=} length The length of the sequence. If this argument is - * omitted, the sequence will go on forever. - */ - function GeneratedSequence(generatorFn, length) { - this.get = generatorFn; - this.fixedLength = length; - } - - GeneratedSequence.prototype = new Sequence(); - - GeneratedSequence.prototype.isAsync = function isAsync() { - return false; - }; - - /** - * Returns the length of this sequence. - * - * @public - * @returns {number} The length, or `undefined` if this is an indefinite - * sequence. - */ - GeneratedSequence.prototype.length = function length() { - return this.fixedLength; - }; - - /** - * Iterates over the sequence produced by invoking this sequence's generator - * function up to its specified length, or, if length is `undefined`, - * indefinitely (in which case the sequence will go on forever--you would need - * to call, e.g., {@link Sequence#take} to limit iteration). - * - * @public - * @param {Function} fn The function to call on each output from the generator - * function. - */ - GeneratedSequence.prototype.each = function each(fn) { - var generatorFn = this.get, - length = this.fixedLength, - i = 0; - - while (typeof length === "undefined" || i < length) { - if (fn(generatorFn(i), i++) === false) { - return false; - } - } - - return true; - }; - - GeneratedSequence.prototype.getIterator = function getIterator() { - return new GeneratedIterator(this); - }; - - /** - * Iterates over a generated sequence. (This allows generated sequences to be - * iterated asynchronously.) - * - * @param {GeneratedSequence} sequence The generated sequence to iterate over. - * @constructor - */ - function GeneratedIterator(sequence) { - this.sequence = sequence; - this.index = 0; - this.currentValue = null; - } - - GeneratedIterator.prototype.current = function current() { - return this.currentValue; - }; - - GeneratedIterator.prototype.moveNext = function moveNext() { - var sequence = this.sequence; - - if (typeof sequence.fixedLength === "number" && this.index >= sequence.fixedLength) { - return false; - } - - this.currentValue = sequence.get(this.index++); - return true; - }; - - /** - * An `AsyncSequence` iterates over its elements asynchronously when - * {@link #each} is called. - * - * You get an `AsyncSequence` by calling {@link Sequence#async} on any - * sequence. Note that some sequence types may not support asynchronous - * iteration. - * - * Returning values - * ---------------- - * - * Because of its asynchronous nature, an `AsyncSequence` cannot be used in the - * same way as other sequences for functions that return values directly (e.g., - * `reduce`, `max`, `any`, even `toArray`). - * - * Instead, these methods return an `AsyncHandle` whose `onComplete` method - * accepts a callback that will be called with the final result once iteration - * has finished. - * - * Defining custom asynchronous sequences - * -------------------------------------- - * - * There are plenty of ways to define an asynchronous sequence. Here's one. - * - * 1. First, implement an {@link Iterator}. This is an object whose prototype - * has the methods {@link Iterator#moveNext} (which returns a `boolean`) and - * {@link current} (which returns the current value). - * 2. Next, create a simple wrapper that inherits from `AsyncSequence`, whose - * `getIterator` function returns an instance of the iterator type you just - * defined. - * - * The default implementation for {@link #each} on an `AsyncSequence` is to - * create an iterator and then asynchronously call {@link Iterator#moveNext} - * (using `setImmediate`, if available, otherwise `setTimeout`) until the iterator - * can't move ahead any more. - * - * @public - * @constructor - * @param {Sequence} parent A {@link Sequence} to wrap, to expose asynchronous - * iteration. - * @param {number=} interval How many milliseconds should elapse between each - * element when iterating over this sequence. If this argument is omitted, - * asynchronous iteration will be executed as fast as possible. - */ - function AsyncSequence(parent, interval) { - if (parent instanceof AsyncSequence) { - throw new Error("Sequence is already asynchronous!"); - } - - this.parent = parent; - this.interval = interval; - this.onNextCallback = getOnNextCallback(interval); - this.cancelCallback = getCancelCallback(interval); - } - - AsyncSequence.prototype = new Sequence(); - - AsyncSequence.prototype.isAsync = function isAsync() { - return true; - }; - - /** - * Throws an exception. You cannot manually iterate over an asynchronous - * sequence. - * - * @public - * @example - * Lazy([1, 2, 3]).async().getIterator() // throws - */ - AsyncSequence.prototype.getIterator = function getIterator() { - throw new Error('An AsyncSequence does not support synchronous iteration.'); - }; - - /** - * An asynchronous version of {@link Sequence#each}. - * - * @public - * @param {Function} fn The function to invoke asynchronously on each element in - * the sequence one by one. - * @returns {AsyncHandle} An {@link AsyncHandle} providing the ability to - * cancel the asynchronous iteration (by calling `cancel()`) as well as - * supply callback(s) for when an error is encountered (`onError`) or when - * iteration is complete (`onComplete`). - */ - AsyncSequence.prototype.each = function each(fn) { - var iterator = this.parent.getIterator(), - onNextCallback = this.onNextCallback, - cancelCallback = this.cancelCallback, - i = 0; - - var handle = new AsyncHandle(function cancel() { - if (cancellationId) { - cancelCallback(cancellationId); - } - }); - - var cancellationId = onNextCallback(function iterate() { - cancellationId = null; - - try { - if (iterator.moveNext() && fn(iterator.current(), i++) !== false) { - cancellationId = onNextCallback(iterate); - - } else { - handle._resolve(); - } - - } catch (e) { - handle._reject(e); - } - }); - - return handle; - }; - - /** - * An `AsyncHandle` provides a [Promises/A+](http://promises-aplus.github.io/promises-spec/) - * compliant interface for an {@link AsyncSequence} that is currently (or was) - * iterating over its elements. - * - * In addition to behaving as a promise, an `AsyncHandle` provides the ability - * to {@link AsyncHandle#cancel} iteration (if `cancelFn` is provided) - * and also offers convenient {@link AsyncHandle#onComplete} and - * {@link AsyncHandle#onError} methods to attach listeners for when iteration - * is complete or an error is thrown during iteration. - * - * @public - * @param {Function} cancelFn A function to cancel asynchronous iteration. - * This is passed in to support different cancellation mechanisms for - * different forms of asynchronous sequences (e.g., timeout-based - * sequences, sequences based on I/O, etc.). - * @constructor - * - * @example - * // Create a sequence of 100,000 random numbers, in chunks of 100. - * var sequence = Lazy.generate(Math.random) - * .chunk(100) - * .async() - * .take(1000); - * - * // Reduce-style operations -- i.e., operations that return a *value* (as - * // opposed to a *sequence*) -- return an AsyncHandle for async sequences. - * var handle = sequence.toArray(); - * - * handle.onComplete(function(array) { - * // Do something w/ 1,000-element array. - * }); - * - * // Since an AsyncHandle is a promise, you can also use it to create - * // subsequent promises using `then` (see the Promises/A+ spec for more - * // info). - * var flattened = handle.then(function(array) { - * return Lazy(array).flatten(); - * }); - */ - function AsyncHandle(cancelFn) { - this.resolveListeners = []; - this.rejectListeners = []; - this.state = PENDING; - this.cancelFn = cancelFn; - } - - // Async handle states - var PENDING = 1, - RESOLVED = 2, - REJECTED = 3; - - AsyncHandle.prototype.then = function then(onFulfilled, onRejected) { - var promise = new AsyncHandle(this.cancelFn); - - this.resolveListeners.push(function(value) { - try { - if (typeof onFulfilled !== 'function') { - resolve(promise, value); - return; - } - - resolve(promise, onFulfilled(value)); - - } catch (e) { - promise._reject(e); - } - }); - - this.rejectListeners.push(function(reason) { - try { - if (typeof onRejected !== 'function') { - promise._reject(reason); - return; - } - - resolve(promise, onRejected(reason)); - - } catch (e) { - promise._reject(e); - } - }); - - if (this.state === RESOLVED) { - this._resolve(this.value); - } - - if (this.state === REJECTED) { - this._reject(this.reason); - } - - return promise; - }; - - AsyncHandle.prototype._resolve = function _resolve(value) { - if (this.state === REJECTED) { - return; - } - - if (this.state === PENDING) { - this.state = RESOLVED; - this.value = value; - } - - consumeListeners(this.resolveListeners, this.value); - }; - - AsyncHandle.prototype._reject = function _reject(reason) { - if (this.state === RESOLVED) { - return; - } - - if (this.state === PENDING) { - this.state = REJECTED; - this.reason = reason; - } - - consumeListeners(this.rejectListeners, this.reason); - }; - - /** - * Cancels asynchronous iteration. - * - * @public - */ - AsyncHandle.prototype.cancel = function cancel() { - if (this.cancelFn) { - this.cancelFn(); - this.cancelFn = null; - this._resolve(false); - } - }; - - /** - * Updates the handle with a callback to execute when iteration is completed. - * - * @public - * @param {Function} callback The function to call when the asynchronous - * iteration is completed. - * @return {AsyncHandle} A reference to the handle (for chaining). - */ - AsyncHandle.prototype.onComplete = function onComplete(callback) { - this.resolveListeners.push(callback); - return this; - }; - - /** - * Updates the handle with a callback to execute if/when any error is - * encountered during asynchronous iteration. - * - * @public - * @param {Function} callback The function to call, with any associated error - * object, when an error occurs. - * @return {AsyncHandle} A reference to the handle (for chaining). - */ - AsyncHandle.prototype.onError = function onError(callback) { - this.rejectListeners.push(callback); - return this; - }; - - /** - * Promise resolution procedure: - * http://promises-aplus.github.io/promises-spec/#the_promise_resolution_procedure - */ - function resolve(promise, x) { - if (promise === x) { - promise._reject(new TypeError('Cannot resolve a promise to itself')); - return; - } - - if (x instanceof AsyncHandle) { - x.then( - function(value) { resolve(promise, value); }, - function(reason) { promise._reject(reason); } - ); - return; - } - - var then; - try { - then = (/function|object/).test(typeof x) && x != null && x.then; - } catch (e) { - promise._reject(e); - return; - } - - var thenableState = PENDING; - if (typeof then === 'function') { - try { - then.call( - x, - function resolvePromise(value) { - if (thenableState !== PENDING) { - return; - } - thenableState = RESOLVED; - resolve(promise, value); - }, - function rejectPromise(reason) { - if (thenableState !== PENDING) { - return; - } - thenableState = REJECTED; - promise._reject(reason); - } - ); - } catch (e) { - if (thenableState !== PENDING) { - return; - } - - promise._reject(e); - } - - return; - } - - promise._resolve(x); - } - - function consumeListeners(listeners, value, callback) { - callback || (callback = getOnNextCallback()); - - callback(function() { - if (listeners.length > 0) { - listeners.shift()(value); - consumeListeners(listeners, value, callback); - } - }); - } - - function getOnNextCallback(interval) { - if (typeof interval === "undefined") { - if (typeof setImmediate === "function") { - return setImmediate; - } - } - - interval = interval || 0; - return function(fn) { - return setTimeout(fn, interval); - }; - } - - function getCancelCallback(interval) { - if (typeof interval === "undefined") { - if (typeof clearImmediate === "function") { - return clearImmediate; - } - } - - return clearTimeout; - } - - /** - * Transform a value, whether the value is retrieved asynchronously or directly. - * - * @private - * @param {Function} fn The function that transforms the value. - * @param {*} value The value to be transformed. This can be an {@link AsyncHandle} when the value - * is retrieved asynchronously, otherwise it can be anything. - * @returns {*} An {@link AsyncHandle} when `value` is also an {@link AsyncHandle}, otherwise - * whatever `fn` resulted in. - */ - function transform(fn, value) { - if (value instanceof AsyncHandle) { - return value.then(function() { fn(value); }); - } - return fn(value); - } - - /** - * An async version of {@link Sequence#reverse}. - */ - AsyncSequence.prototype.reverse = function reverse() { - return this.parent.reverse().async(); - }; - - /** - * A version of {@link Sequence#find} which returns an {@link AsyncHandle}. - * - * @public - * @param {Function} predicate A function to call on (potentially) every element - * in the sequence. - * @returns {AsyncHandle} An {@link AsyncHandle} (promise) which resolves to - * the found element, once it is detected, or else `undefined`. - */ - AsyncSequence.prototype.find = function find(predicate) { - var found; - - var handle = this.each(function(e, i) { - if (predicate(e, i)) { - found = e; - return false; - } - }); - - return handle.then(function() { return found; }); - }; - - /** - * A version of {@link Sequence#indexOf} which returns an {@link AsyncHandle}. - * - * @public - * @param {*} value The element to search for in the sequence. - * @returns {AsyncHandle} An {@link AsyncHandle} (promise) which resolves to - * the found index, once it is detected, or -1. - */ - AsyncSequence.prototype.indexOf = function indexOf(value) { - var foundIndex = -1; - - var handle = this.each(function(e, i) { - if (e === value) { - foundIndex = i; - return false; - } - }); - - return handle.then(function() { - return foundIndex; - }); - }; - - /** - * A version of {@link Sequence#contains} which returns an {@link AsyncHandle}. - * - * @public - * @param {*} value The element to search for in the sequence. - * @returns {AsyncHandle} An {@link AsyncHandle} (promise) which resolves to - * either `true` or `false` to indicate whether the element was found. - */ - AsyncSequence.prototype.contains = function contains(value) { - var found = false; - - var handle = this.each(function(e) { - if (e === value) { - found = true; - return false; - } - }); - - return handle.then(function() { - return found; - }); - }; - - /** - * Just return the same sequence for `AsyncSequence#async` (I see no harm in this). - */ - AsyncSequence.prototype.async = function async() { - return this; - }; - - /** - * See {@link ObjectLikeSequence#watch} for docs. - */ - ObjectWrapper.prototype.watch = function watch(propertyNames) { - return new WatchedPropertySequence(this.source, propertyNames); - }; - - function WatchedPropertySequence(object, propertyNames) { - this.listeners = []; - - if (!propertyNames) { - propertyNames = Lazy(object).keys().toArray(); - } else if (!(propertyNames instanceof Array)) { - propertyNames = [propertyNames]; - } - - var listeners = this.listeners, - index = 0; - - Lazy(propertyNames).each(function(propertyName) { - var propertyValue = object[propertyName]; - - Object.defineProperty(object, propertyName, { - get: function() { - return propertyValue; - }, - - set: function(value) { - for (var i = listeners.length - 1; i >= 0; --i) { - if (listeners[i]({ property: propertyName, value: value }, index) === false) { - listeners.splice(i, 1); - } - } - propertyValue = value; - ++index; - } - }); - }); - } - - WatchedPropertySequence.prototype = new AsyncSequence(); - - WatchedPropertySequence.prototype.each = function each(fn) { - this.listeners.push(fn); - }; - - /** - * A StreamLikeSequence comprises a sequence of 'chunks' of data, which are - * typically multiline strings. - * - * @constructor - */ - function StreamLikeSequence() {} - - StreamLikeSequence.prototype = new AsyncSequence(); - - StreamLikeSequence.prototype.isAsync = function isAsync() { - return true; - }; - - StreamLikeSequence.prototype.split = function split(delimiter) { - return new SplitStreamSequence(this, delimiter); - }; - - /** - * @constructor - */ - function SplitStreamSequence(parent, delimiter) { - this.parent = parent; - this.delimiter = delimiter; - this.each = this.getEachForDelimiter(delimiter); - } - - SplitStreamSequence.prototype = new Sequence(); - - SplitStreamSequence.prototype.getEachForDelimiter = function getEachForDelimiter(delimiter) { - if (delimiter instanceof RegExp) { - return this.regexEach; - } - - return this.stringEach; - }; - - SplitStreamSequence.prototype.regexEach = function each(fn) { - var delimiter = cloneRegex(this.delimiter), - buffer = '', - start = 0, end, - index = 0; - - var handle = this.parent.each(function(chunk) { - buffer += chunk; - - var match; - while (match = delimiter.exec(buffer)) { - end = match.index; - if (fn(buffer.substring(start, end), index++) === false) { - return false; - } - start = end + match[0].length; - } - - buffer = buffer.substring(start); - start = 0; - }); - - handle.onComplete(function() { - if (buffer.length > 0) { - fn(buffer, index++); - } - }); - - return handle; - }; - - SplitStreamSequence.prototype.stringEach = function each(fn) { - var delimiter = this.delimiter, - pieceIndex = 0, - buffer = '', - bufferIndex = 0; - - var handle = this.parent.each(function(chunk) { - buffer += chunk; - var delimiterIndex; - while ((delimiterIndex = buffer.indexOf(delimiter)) >= 0) { - var piece = buffer.substr(0,delimiterIndex); - buffer = buffer.substr(delimiterIndex+delimiter.length); - if (fn(piece,pieceIndex++) === false) { - return false; - } - } - return true; - }); - - handle.onComplete(function() { - fn(buffer, pieceIndex++); - }); - - return handle; - }; - - StreamLikeSequence.prototype.lines = function lines() { - return this.split("\n"); - }; - - StreamLikeSequence.prototype.match = function match(pattern) { - return new MatchedStreamSequence(this, pattern); - }; - - /** - * @constructor - */ - function MatchedStreamSequence(parent, pattern) { - this.parent = parent; - this.pattern = cloneRegex(pattern); - } - - MatchedStreamSequence.prototype = new AsyncSequence(); - - MatchedStreamSequence.prototype.each = function each(fn) { - var pattern = this.pattern, - done = false, - i = 0; - - return this.parent.each(function(chunk) { - Lazy(chunk).match(pattern).each(function(match) { - if (fn(match, i++) === false) { - done = true; - return false; - } - }); - - return !done; - }); - }; - - /** - * Defines a wrapper for custom {@link StreamLikeSequence}s. This is useful - * if you want a way to handle a stream of events as a sequence, but you can't - * use Lazy's existing interface (i.e., you're wrapping an object from a - * library with its own custom events). - * - * This method defines a *factory*: that is, it produces a function that can - * be used to wrap objects and return a {@link Sequence}. Hopefully the - * example will make this clear. - * - * @public - * @param {Function} initializer An initialization function called on objects - * created by this factory. `this` will be bound to the created object, - * which is an instance of {@link StreamLikeSequence}. Use `emit` to - * generate data for the sequence. - * @returns {Function} A function that creates a new {@link StreamLikeSequence}, - * initializes it using the specified function, and returns it. - * - * @example - * var factory = Lazy.createWrapper(function(eventSource) { - * var sequence = this; - * - * eventSource.handleEvent(function(data) { - * sequence.emit(data); - * }); - * }); - * - * var eventEmitter = { - * triggerEvent: function(data) { - * eventEmitter.eventHandler(data); - * }, - * handleEvent: function(handler) { - * eventEmitter.eventHandler = handler; - * }, - * eventHandler: function() {} - * }; - * - * var events = []; - * - * factory(eventEmitter).each(function(e) { - * events.push(e); - * }); - * - * eventEmitter.triggerEvent('foo'); - * eventEmitter.triggerEvent('bar'); - * - * events // => ['foo', 'bar'] - */ - Lazy.createWrapper = function createWrapper(initializer) { - var ctor = function() { - this.listeners = []; - }; - - ctor.prototype = new StreamLikeSequence(); - - ctor.prototype.each = function(listener) { - this.listeners.push(listener); - }; - - ctor.prototype.emit = function(data) { - var listeners = this.listeners; - - for (var len = listeners.length, i = len - 1; i >= 0; --i) { - if (listeners[i](data) === false) { - listeners.splice(i, 1); - } - } - }; - - return function() { - var sequence = new ctor(); - initializer.apply(sequence, arguments); - return sequence; - }; - }; - - /** - * Creates a {@link GeneratedSequence} using the specified generator function - * and (optionally) length. - * - * @public - * @param {function(number):*} generatorFn The function used to generate the - * sequence. This function accepts an index as a parameter and should return - * a value for that index in the resulting sequence. - * @param {number=} length The length of the sequence, for sequences with a - * definite length. - * @returns {GeneratedSequence} The generated sequence. - * - * @examples - * var randomNumbers = Lazy.generate(Math.random); - * var countingNumbers = Lazy.generate(function(i) { return i + 1; }, 5); - * - * randomNumbers // instanceof Lazy.GeneratedSequence - * randomNumbers.length() // => undefined - * countingNumbers // sequence: [1, 2, 3, 4, 5] - * countingNumbers.length() // => 5 - */ - Lazy.generate = function generate(generatorFn, length) { - return new GeneratedSequence(generatorFn, length); - }; - - /** - * Creates a sequence from a given starting value, up to a specified stopping - * value, incrementing by a given step. Invalid values for any of these - * arguments (e.g., a step of 0) result in an empty sequence. - * - * @public - * @returns {GeneratedSequence} The sequence defined by the given ranges. - * - * @examples - * Lazy.range(3) // sequence: [0, 1, 2] - * Lazy.range(1, 4) // sequence: [1, 2, 3] - * Lazy.range(2, 10, 2) // sequence: [2, 4, 6, 8] - * Lazy.range(5, 1, 2) // sequence: [] - * Lazy.range(5, 15, -2) // sequence: [] - * Lazy.range(3, 10, 3) // sequence: [3, 6, 9] - * Lazy.range(5, 2) // sequence: [5, 4, 3] - * Lazy.range(7, 2, -2) // sequence: [7, 5, 3] - * Lazy.range(3, 5, 0) // sequence: [] - */ - Lazy.range = function range() { - var start = arguments.length > 1 ? arguments[0] : 0, - stop = arguments.length > 1 ? arguments[1] : arguments[0], - step = arguments.length > 2 && arguments[2]; - - if (step === false) { - step = stop > start ? 1 : -1; - } - - if (step === 0) { - return Lazy([]); - } - - return Lazy.generate(function(i) { return start + (step * i); }) - .take(Math.ceil((stop - start) / step)); - }; - - /** - * Creates a sequence consisting of the given value repeated a specified number - * of times. - * - * @public - * @param {*} value The value to repeat. - * @param {number=} count The number of times the value should be repeated in - * the sequence. If this argument is omitted, the value will repeat forever. - * @returns {GeneratedSequence} The sequence containing the repeated value. - * - * @examples - * Lazy.repeat("hi", 3) // sequence: ["hi", "hi", "hi"] - * Lazy.repeat("young") // instanceof Lazy.GeneratedSequence - * Lazy.repeat("young").length() // => undefined - * Lazy.repeat("young").take(3) // sequence: ["young", "young", "young"] - */ - Lazy.repeat = function repeat(value, count) { - return Lazy.generate(function() { return value; }, count); - }; - - Lazy.Sequence = Sequence; - Lazy.ArrayLikeSequence = ArrayLikeSequence; - Lazy.ObjectLikeSequence = ObjectLikeSequence; - Lazy.StringLikeSequence = StringLikeSequence; - Lazy.StreamLikeSequence = StreamLikeSequence; - Lazy.GeneratedSequence = GeneratedSequence; - Lazy.AsyncSequence = AsyncSequence; - Lazy.AsyncHandle = AsyncHandle; - - /*** Useful utility methods ***/ - - /** - * Creates a shallow copy of an array or object. - * - * @examples - * var array = [1, 2, 3], clonedArray, - * object = { foo: 1, bar: 2 }, clonedObject; - * - * clonedArray = Lazy.clone(array); // => [1, 2, 3] - * clonedArray.push(4); // clonedArray == [1, 2, 3, 4] - * array; // => [1, 2, 3] - * - * clonedObject = Lazy.clone(object); // => { foo: 1, bar: 2 } - * clonedObject.baz = 3; // clonedObject == { foo: 1, bar: 2, baz: 3 } - * object; // => { foo: 1, bar: 2 } - */ - Lazy.clone = function clone(target) { - return Lazy(target).value(); - }; - - /** - * Marks a method as deprecated, so calling it will issue a console warning. - */ - Lazy.deprecate = function deprecate(message, fn) { - return function() { - console.warn(message); - return fn.apply(this, arguments); - }; - }; - - var arrayPop = Array.prototype.pop, - arraySlice = Array.prototype.slice; - - /** - * Creates a callback... you know, Lo-Dash style. - * - * - for functions, just returns the function - * - for strings, returns a pluck-style callback - * - for objects, returns a where-style callback - * - * @private - * @param {Function|string|Object} callback A function, string, or object to - * convert to a callback. - * @param {*} defaultReturn If the callback is undefined, a default return - * value to use for the function. - * @returns {Function} The callback function. - * - * @examples - * createCallback(function() {}) // instanceof Function - * createCallback('foo') // instanceof Function - * createCallback('foo')({ foo: 'bar'}) // => 'bar' - * createCallback({ foo: 'bar' })({ foo: 'bar' }) // => true - * createCallback({ foo: 'bar' })({ foo: 'baz' }) // => false - */ - function createCallback(callback, defaultValue) { - switch (typeof callback) { - case "function": - return callback; - - case "string": - return function(e) { - return e[callback]; - }; - - case "object": - return function(e) { - return Lazy(callback).all(function(value, key) { - return e[key] === value; - }); - }; - - case "undefined": - return defaultValue ? - function() { return defaultValue; } : - Lazy.identity; - - default: - throw new Error("Don't know how to make a callback from a " + typeof callback + "!"); - } - } - - /** - * Takes a function that returns a value for one argument and produces a - * function that compares two arguments. - * - * @private - * @param {Function|string|Object} callback A function, string, or object to - * convert to a callback using `createCallback`. - * @returns {Function} A function that accepts two values and returns 1 if - * the first is greater, -1 if the second is greater, or 0 if they are - * equivalent. - * - * @examples - * createComparator('a')({ a: 1 }, { a: 2 }); // => -1 - * createComparator('a')({ a: 6 }, { a: 2 }); // => 1 - * createComparator('a')({ a: 1 }, { a: 1 }); // => 0 - * createComparator()(3, 5); // => -1 - * createComparator()(7, 5); // => 1 - * createComparator()(3, 3); // => 0 - */ - function createComparator(callback, descending) { - if (!callback) { return compare; } - - callback = createCallback(callback); - - return function(x, y) { - return compare(callback(x), callback(y)); - }; - } - - /** - * Takes a function and returns a function with the same logic but the - * arguments reversed. Only applies to functions w/ arity=2 as this is private - * and I can do what I want. - * - * @private - * @param {Function} fn The function to "reverse" - * @returns {Function} The "reversed" function - * - * @examples - * reverseArguments(function(x, y) { return x + y; })('a', 'b'); // => 'ba' - */ - function reverseArguments(fn) { - return function(x, y) { return fn(y, x); }; - } - - /** - * Creates a Set containing the specified values. - * - * @param {...Array} values One or more array(s) of values used to populate the - * set. - * @returns {Set} A new set containing the values passed in. - */ - function createSet(values) { - var set = new Set(); - Lazy(values || []).flatten().each(function(e) { - set.add(e); - }); - return set; - } - - /** - * Compares two elements for sorting purposes. - * - * @private - * @param {*} x The left element to compare. - * @param {*} y The right element to compare. - * @returns {number} 1 if x > y, -1 if x < y, or 0 if x and y are equal. - * - * @examples - * compare(1, 2) // => -1 - * compare(1, 1) // => 0 - * compare(2, 1) // => 1 - * compare('a', 'b') // => -1 - */ - function compare(x, y) { - if (x === y) { - return 0; - } - - return x > y ? 1 : -1; - } - - /** - * Iterates over every element in an array. - * - * @param {Array} array The array. - * @param {Function} fn The function to call on every element, which can return - * false to stop the iteration early. - * @returns {boolean} True if every element in the entire sequence was iterated, - * otherwise false. - */ - function forEach(array, fn) { - var i = -1, - len = array.length; - - while (++i < len) { - if (fn(array[i], i) === false) { - return false; - } - } - - return true; - } - - function getFirst(sequence) { - var result; - sequence.each(function(e) { - result = e; - return false; - }); - return result; - } - - /** - * Checks if an element exists in an array. - * - * @private - * @param {Array} array - * @param {*} element - * @returns {boolean} Whether or not the element exists in the array. - * - * @examples - * arrayContains([1, 2], 2) // => true - * arrayContains([1, 2], 3) // => false - * arrayContains([undefined], undefined) // => true - * arrayContains([NaN], NaN) // => true - */ - function arrayContains(array, element) { - var i = -1, - length = array.length; - - // Special handling for NaN - if (element !== element) { - while (++i < length) { - if (array[i] !== array[i]) { - return true; - } - } - return false; - } - - while (++i < length) { - if (array[i] === element) { - return true; - } - } - return false; - } - - /** - * Checks if an element exists in an array before a given index. - * - * @private - * @param {Array} array - * @param {*} element - * @param {number} index - * @param {Function} keyFn - * @returns {boolean} - * - * @examples - * arrayContainsBefore([1, 2, 3], 3, 2) // => false - * arrayContainsBefore([1, 2, 3], 3, 3) // => true - */ - function arrayContainsBefore(array, element, index, keyFn) { - var i = -1; - - if (keyFn) { - keyFn = createCallback(keyFn); - while (++i < index) { - if (keyFn(array[i]) === keyFn(element)) { - return true; - } - } - - } else { - while (++i < index) { - if (array[i] === element) { - return true; - } - } - } - - return false; - } - - /** - * Swaps the elements at two specified positions of an array. - * - * @private - * @param {Array} array - * @param {number} i - * @param {number} j - * - * @examples - * var array = [1, 2, 3, 4, 5]; - * - * swap(array, 2, 3) // array == [1, 2, 4, 3, 5] - */ - function swap(array, i, j) { - var temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - /** - * "Clones" a regular expression (but makes it always global). - * - * @private - * @param {RegExp|string} pattern - * @returns {RegExp} - */ - function cloneRegex(pattern) { - return eval("" + pattern + (!pattern.global ? "g" : "")); - }; - - /** - * A collection of unique elements. - * - * @private - * @constructor - * - * @examples - * var set = new Set(), - * obj1 = {}, - * obj2 = {}, - * fn1 = function fn1() {}, - * fn2 = function fn2() {}; - * - * set.add('foo') // => true - * set.add('foo') // => false - * set.add(1) // => true - * set.add(1) // => false - * set.add('1') // => true - * set.add('1') // => false - * set.add(obj1) // => true - * set.add(obj1) // => false - * set.add(obj2) // => true - * set.add(fn1) // => true - * set.add(fn2) // => true - * set.add(fn2) // => false - * set.contains('__proto__') // => false - * set.add('__proto__') // => true - * set.add('__proto__') // => false - * set.contains('add') // => false - * set.add('add') // => true - * set.add('add') // => false - * set.contains(undefined) // => false - * set.add(undefined) // => true - * set.contains(undefined) // => true - * set.contains('undefined') // => false - * set.add('undefined') // => true - * set.contains('undefined') // => true - * set.contains(NaN) // => false - * set.add(NaN) // => true - * set.contains(NaN) // => true - * set.contains('NaN') // => false - * set.add('NaN') // => true - * set.contains('NaN') // => true - * set.contains('@foo') // => false - * set.add('@foo') // => true - * set.contains('@foo') // => true - */ - function Set() { - this.table = {}; - this.objects = []; - } - - /** - * Attempts to add a unique value to the set. - * - * @param {*} value The value to add. - * @returns {boolean} True if the value was added to the set (meaning an equal - * value was not already present), or else false. - */ - Set.prototype.add = function add(value) { - var table = this.table, - type = typeof value, - - // only applies for strings - firstChar, - - // only applies for objects - objects; - - switch (type) { - case "number": - case "boolean": - case "undefined": - if (!table[value]) { - table[value] = true; - return true; - } - return false; - - case "string": - // Essentially, escape the first character if it could possibly collide - // with a number, boolean, or undefined (or a string that happens to start - // with the escape character!), OR if it could override a special property - // such as '__proto__' or 'constructor'. - switch (value.charAt(0)) { - case "_": // e.g., __proto__ - case "f": // for 'false' - case "t": // for 'true' - case "c": // for 'constructor' - case "u": // for 'undefined' - case "@": // escaped - case "0": - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - case "N": // for NaN - value = "@" + value; - } - if (!table[value]) { - table[value] = true; - return true; - } - return false; - - default: - // For objects and functions, we can't really do anything other than store - // them in an array and do a linear search for reference equality. - objects = this.objects; - if (!arrayContains(objects, value)) { - objects.push(value); - return true; - } - return false; - } - }; - - /** - * Checks whether the set contains a value. - * - * @param {*} value The value to check for. - * @returns {boolean} True if the set contains the value, or else false. - */ - Set.prototype.contains = function contains(value) { - var type = typeof value, - - // only applies for strings - firstChar; - - switch (type) { - case "number": - case "boolean": - case "undefined": - return !!this.table[value]; - - case "string": - // Essentially, escape the first character if it could possibly collide - // with a number, boolean, or undefined (or a string that happens to start - // with the escape character!), OR if it could override a special property - // such as '__proto__' or 'constructor'. - switch (value.charAt(0)) { - case "_": // e.g., __proto__ - case "f": // for 'false' - case "t": // for 'true' - case "c": // for 'constructor' - case "u": // for 'undefined' - case "@": // escaped - case "0": - case "1": - case "2": - case "3": - case "4": - case "5": - case "6": - case "7": - case "8": - case "9": - case "N": // for NaN - value = "@" + value; - } - return !!this.table[value]; - - default: - // For objects and functions, we can't really do anything other than store - // them in an array and do a linear search for reference equality. - return arrayContains(this.objects, value); - } - }; - - /** - * A "rolling" queue, with a fixed capacity. As items are added to the head, - * excess items are dropped from the tail. - * - * @private - * @constructor - * - * @examples - * var queue = new Queue(3); - * - * queue.add(1).toArray() // => [1] - * queue.add(2).toArray() // => [1, 2] - * queue.add(3).toArray() // => [1, 2, 3] - * queue.add(4).toArray() // => [2, 3, 4] - * queue.add(5).add(6).toArray() // => [4, 5, 6] - * queue.add(7).add(8).toArray() // => [6, 7, 8] - * - * // also want to check corner cases - * new Queue(1).add('foo').add('bar').toArray() // => ['bar'] - * new Queue(0).add('foo').toArray() // => [] - * new Queue(-1) // throws - * - * @benchmarks - * function populateQueue(count, capacity) { - * var q = new Queue(capacity); - * for (var i = 0; i < count; ++i) { - * q.add(i); - * } - * } - * - * function populateArray(count, capacity) { - * var arr = []; - * for (var i = 0; i < count; ++i) { - * if (arr.length === capacity) { arr.shift(); } - * arr.push(i); - * } - * } - * - * populateQueue(100, 10); // populating a Queue - * populateArray(100, 10); // populating an Array - */ - function Queue(capacity) { - this.contents = new Array(capacity); - this.start = 0; - this.count = 0; - } - - /** - * Adds an item to the queue, and returns the queue. - */ - Queue.prototype.add = function add(element) { - var contents = this.contents, - capacity = contents.length, - start = this.start; - - if (this.count === capacity) { - contents[start] = element; - this.start = (start + 1) % capacity; - - } else { - contents[this.count++] = element; - } - - return this; - }; - - /** - * Returns an array containing snapshot of the queue's contents. - */ - Queue.prototype.toArray = function toArray() { - var contents = this.contents, - start = this.start, - count = this.count; - - var snapshot = contents.slice(start, start + count); - if (snapshot.length < count) { - snapshot = snapshot.concat(contents.slice(0, count - snapshot.length)); - } - - return snapshot; - }; - - /** - * Shared base method for defining new sequence types. - */ - function defineSequenceType(base, name, overrides) { - /** @constructor */ - var ctor = function ctor() {}; - - // Make this type inherit from the specified base. - ctor.prototype = new base(); - - // Attach overrides to the new sequence type's prototype. - for (var override in overrides) { - ctor.prototype[override] = overrides[override]; - } - - // Define a factory method that sets the new sequence's parent to the caller - // and (optionally) applies any additional initialization logic. - // Expose this as a chainable method so that we can do: - // Lazy(...).map(...).filter(...).blah(...); - var factory = function factory() { - var sequence = new ctor(); - - // Every sequence needs a reference to its parent in order to work. - sequence.parent = this; - - // If a custom init function was supplied, call it now. - if (sequence.init) { - sequence.init.apply(sequence, arguments); - } - - return sequence; - }; - - var methodNames = typeof name === 'string' ? [name] : name; - for (var i = 0; i < methodNames.length; ++i) { - base.prototype[methodNames[i]] = factory; - } - - return ctor; - } - - return Lazy; - }); - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7).setImmediate, __webpack_require__(7).clearImmediate)) - -/***/ }, -/* 73 */ -/***/ function(module, exports) { - - "use strict"; - 'use strict'; - - module.exports = { - createWriteStream: function(filename, options) { - return; - }, - writeFileSync: function() { - return; - }, - openSync: function() { - return; - }, - writeSync: function() { - return; - } - } - - -/***/ }, -/* 74 */ -/***/ function(module, exports) { - - "use strict"; - 'use strict'; - - class EventIndex { - constructor() { - this._index = {}; - } - - get() { - return Object.keys(this._index).map((f) => this._index[f]); - } - - updateIndex(oplog, added) { - added.reduce((handled, item) => { - if(handled.indexOf(item.hash) === -1) { - handled.push(item.hash); - if(item.payload.op === 'ADD') - this._index[item.hash] = item - } - return handled; - }, []); - } - } - - module.exports = EventIndex; - - -/***/ }, -/* 75 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - 'use strict'; - - const Lazy = __webpack_require__(72); - const Store = __webpack_require__(38); - const EventIndex = __webpack_require__(74); - - class EventStore extends Store { - constructor(ipfs, id, dbname, options) { - if(!options) options = {}; - if(!options.Index) Object.assign(options, { Index: EventIndex }); - super(ipfs, id, dbname, options) - } - - add(data) { - return this._addOperation({ - op: 'ADD', - key: null, - value: data, - meta: { - ts: new Date().getTime() - } - }); - } - - iterator(options) { - const messages = this._query(this.dbname, options); - let currentIndex = 0; - let iterator = { - [Symbol.iterator]() { - return this; - }, - next() { - let item = { value: null, done: true }; - if(currentIndex < messages.length) { - item = { value: messages[currentIndex], done: false }; - currentIndex ++; - } - return item; - }, - collect: () => messages - } - - return iterator; - } - - _query(dbname, opts) { - if(!opts) opts = {}; - - const amount = opts.limit ? (opts.limit > -1 ? opts.limit : this._index.get().length) : 1; // Return 1 if no limit is provided - const events = this._index.get(); - let result = []; - - if(opts.gt || opts.gte) { - // Greater than case - result = this._read(events, opts.gt ? opts.gt : opts.gte, amount, opts.gte ? true : false) - } else { - // Lower than and lastN case, search latest first by reversing the sequence - result = this._read(events.reverse(), opts.lt ? opts.lt : opts.lte, amount, opts.lte || !opts.lt).reverse() - } - - if(opts.reverse) result.reverse(); - - return result.toArray(); - } - - _read(ops, hash, amount, inclusive) { - return Lazy(ops) - .skipWhile((f) => hash && f.hash !== hash) - .drop(inclusive ? 0 : 1) - .take(amount); - } - } - - module.exports = EventStore; - - -/***/ }, -/* 76 */ -/***/ function(module, exports) { - - /** - * Parses an URI - * - * @author Steven Levithan (MIT license) - * @api private - */ - - var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; - - var parts = [ - 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' - ]; - - module.exports = function parseuri(str) { - var src = str, - b = str.indexOf('['), - e = str.indexOf(']'); - - if (b != -1 && e != -1) { - str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); - } - - var m = re.exec(str || ''), - uri = {}, - i = 14; - - while (i--) { - uri[parts[i]] = m[i] || ''; - } - - if (b != -1 && e != -1) { - uri.source = src; - uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); - uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); - uri.ipv6uri = true; - } - - return uri; - }; - - -/***/ }, -/* 77 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. - // - // 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 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. - - // resolves . and .. elements in a path array with directory names there - // must be no slashes, empty elements, or device names (c:\) in the array - // (so also no leading and trailing slashes - it does not distinguish - // relative and absolute paths) - function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; - } - - // Split a filename into [root, dir, basename, ext], unix version - // 'root' is just a slash, or nothing. - var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; - var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); - }; - - // path.resolve([from ...], to) - // posix version - exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; - }; - - // path.normalize(path) - // posix version - exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; - }; - - // posix version - exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; - }; - - // posix version - exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); - }; - - - // path.relative(from, to) - // posix version - exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); - }; - - exports.sep = '/'; - exports.delimiter = ':'; - - exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; - }; - - - exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; - }; - - - exports.extname = function(path) { - return splitPath(path)[3]; - }; - - function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; - } - - // String.prototype.substr - negative index don't work in IE8 - var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } - ; - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(20))) - -/***/ }, -/* 78 */ -/***/ function(module, exports, __webpack_require__) { - - - /** - * Module dependencies. - */ - - var eio = __webpack_require__(170); - var Socket = __webpack_require__(80); - var Emitter = __webpack_require__(56); - var parser = __webpack_require__(40); - var on = __webpack_require__(79); - var bind = __webpack_require__(55); - var debug = __webpack_require__(3)('socket.io-client:manager'); - var indexOf = __webpack_require__(71); - var Backoff = __webpack_require__(126); - - /** - * IE6+ hasOwnProperty - */ - - var has = Object.prototype.hasOwnProperty; - - /** - * Module exports - */ - - module.exports = Manager; - - /** - * `Manager` constructor. - * - * @param {String} engine instance or engine uri/opts - * @param {Object} options - * @api public - */ - - function Manager(uri, opts){ - if (!(this instanceof Manager)) return new Manager(uri, opts); - if (uri && ('object' == typeof uri)) { - opts = uri; - uri = undefined; - } - opts = opts || {}; - - opts.path = opts.path || '/socket.io'; - this.nsps = {}; - this.subs = []; - this.opts = opts; - this.reconnection(opts.reconnection !== false); - this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); - this.reconnectionDelay(opts.reconnectionDelay || 1000); - this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); - this.randomizationFactor(opts.randomizationFactor || 0.5); - this.backoff = new Backoff({ - min: this.reconnectionDelay(), - max: this.reconnectionDelayMax(), - jitter: this.randomizationFactor() - }); - this.timeout(null == opts.timeout ? 20000 : opts.timeout); - this.readyState = 'closed'; - this.uri = uri; - this.connecting = []; - this.lastPing = null; - this.encoding = false; - this.packetBuffer = []; - this.encoder = new parser.Encoder(); - this.decoder = new parser.Decoder(); - this.autoConnect = opts.autoConnect !== false; - if (this.autoConnect) this.open(); - } - - /** - * Propagate given event to sockets and emit on `this` - * - * @api private - */ - - Manager.prototype.emitAll = function() { - this.emit.apply(this, arguments); - for (var nsp in this.nsps) { - if (has.call(this.nsps, nsp)) { - this.nsps[nsp].emit.apply(this.nsps[nsp], arguments); - } - } - }; - - /** - * Update `socket.id` of all sockets - * - * @api private - */ - - Manager.prototype.updateSocketIds = function(){ - for (var nsp in this.nsps) { - if (has.call(this.nsps, nsp)) { - this.nsps[nsp].id = this.engine.id; - } - } - }; - - /** - * Mix in `Emitter`. - */ - - Emitter(Manager.prototype); - - /** - * Sets the `reconnection` config. - * - * @param {Boolean} true/false if it should automatically reconnect - * @return {Manager} self or value - * @api public - */ - - Manager.prototype.reconnection = function(v){ - if (!arguments.length) return this._reconnection; - this._reconnection = !!v; - return this; - }; - - /** - * Sets the reconnection attempts config. - * - * @param {Number} max reconnection attempts before giving up - * @return {Manager} self or value - * @api public - */ - - Manager.prototype.reconnectionAttempts = function(v){ - if (!arguments.length) return this._reconnectionAttempts; - this._reconnectionAttempts = v; - return this; - }; - - /** - * Sets the delay between reconnections. - * - * @param {Number} delay - * @return {Manager} self or value - * @api public - */ - - Manager.prototype.reconnectionDelay = function(v){ - if (!arguments.length) return this._reconnectionDelay; - this._reconnectionDelay = v; - this.backoff && this.backoff.setMin(v); - return this; - }; - - Manager.prototype.randomizationFactor = function(v){ - if (!arguments.length) return this._randomizationFactor; - this._randomizationFactor = v; - this.backoff && this.backoff.setJitter(v); - return this; - }; - - /** - * Sets the maximum delay between reconnections. - * - * @param {Number} delay - * @return {Manager} self or value - * @api public - */ - - Manager.prototype.reconnectionDelayMax = function(v){ - if (!arguments.length) return this._reconnectionDelayMax; - this._reconnectionDelayMax = v; - this.backoff && this.backoff.setMax(v); - return this; - }; - - /** - * Sets the connection timeout. `false` to disable - * - * @return {Manager} self or value - * @api public - */ - - Manager.prototype.timeout = function(v){ - if (!arguments.length) return this._timeout; - this._timeout = v; - return this; - }; - - /** - * Starts trying to reconnect if reconnection is enabled and we have not - * started reconnecting yet - * - * @api private - */ - - Manager.prototype.maybeReconnectOnOpen = function() { - // Only try to reconnect if it's the first time we're connecting - if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) { - // keeps reconnection from firing twice for the same reconnection loop - this.reconnect(); - } - }; - - - /** - * Sets the current transport `socket`. - * - * @param {Function} optional, callback - * @return {Manager} self - * @api public - */ - - Manager.prototype.open = - Manager.prototype.connect = function(fn){ - debug('readyState %s', this.readyState); - if (~this.readyState.indexOf('open')) return this; - - debug('opening %s', this.uri); - this.engine = eio(this.uri, this.opts); - var socket = this.engine; - var self = this; - this.readyState = 'opening'; - this.skipReconnect = false; - - // emit `open` - var openSub = on(socket, 'open', function() { - self.onopen(); - fn && fn(); - }); - - // emit `connect_error` - var errorSub = on(socket, 'error', function(data){ - debug('connect_error'); - self.cleanup(); - self.readyState = 'closed'; - self.emitAll('connect_error', data); - if (fn) { - var err = new Error('Connection error'); - err.data = data; - fn(err); - } else { - // Only do this if there is no fn to handle the error - self.maybeReconnectOnOpen(); - } - }); - - // emit `connect_timeout` - if (false !== this._timeout) { - var timeout = this._timeout; - debug('connect attempt will timeout after %d', timeout); - - // set timer - var timer = setTimeout(function(){ - debug('connect attempt timed out after %d', timeout); - openSub.destroy(); - socket.close(); - socket.emit('error', 'timeout'); - self.emitAll('connect_timeout', timeout); - }, timeout); - - this.subs.push({ - destroy: function(){ - clearTimeout(timer); - } - }); - } - - this.subs.push(openSub); - this.subs.push(errorSub); - - return this; - }; - - /** - * Called upon transport open. - * - * @api private - */ - - Manager.prototype.onopen = function(){ - debug('open'); - - // clear old subs - this.cleanup(); - - // mark as open - this.readyState = 'open'; - this.emit('open'); - - // add new subs - var socket = this.engine; - this.subs.push(on(socket, 'data', bind(this, 'ondata'))); - this.subs.push(on(socket, 'ping', bind(this, 'onping'))); - this.subs.push(on(socket, 'pong', bind(this, 'onpong'))); - this.subs.push(on(socket, 'error', bind(this, 'onerror'))); - this.subs.push(on(socket, 'close', bind(this, 'onclose'))); - this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded'))); - }; - - /** - * Called upon a ping. - * - * @api private - */ - - Manager.prototype.onping = function(){ - this.lastPing = new Date; - this.emitAll('ping'); - }; - - /** - * Called upon a packet. - * - * @api private - */ - - Manager.prototype.onpong = function(){ - this.emitAll('pong', new Date - this.lastPing); - }; - - /** - * Called with data. - * - * @api private - */ - - Manager.prototype.ondata = function(data){ - this.decoder.add(data); - }; - - /** - * Called when parser fully decodes a packet. - * - * @api private - */ - - Manager.prototype.ondecoded = function(packet) { - this.emit('packet', packet); - }; - - /** - * Called upon socket error. - * - * @api private - */ - - Manager.prototype.onerror = function(err){ - debug('error', err); - this.emitAll('error', err); - }; - - /** - * Creates a new socket for the given `nsp`. - * - * @return {Socket} - * @api public - */ - - Manager.prototype.socket = function(nsp){ - var socket = this.nsps[nsp]; - if (!socket) { - socket = new Socket(this, nsp); - this.nsps[nsp] = socket; - var self = this; - socket.on('connecting', onConnecting); - socket.on('connect', function(){ - socket.id = self.engine.id; - }); - - if (this.autoConnect) { - // manually call here since connecting evnet is fired before listening - onConnecting(); - } - } - - function onConnecting() { - if (!~indexOf(self.connecting, socket)) { - self.connecting.push(socket); - } - } - - return socket; - }; - - /** - * Called upon a socket close. - * - * @param {Socket} socket - */ - - Manager.prototype.destroy = function(socket){ - var index = indexOf(this.connecting, socket); - if (~index) this.connecting.splice(index, 1); - if (this.connecting.length) return; - - this.close(); - }; - - /** - * Writes a packet. - * - * @param {Object} packet - * @api private - */ - - Manager.prototype.packet = function(packet){ - debug('writing packet %j', packet); - var self = this; - - if (!self.encoding) { - // encode, then write to engine with result - self.encoding = true; - this.encoder.encode(packet, function(encodedPackets) { - for (var i = 0; i < encodedPackets.length; i++) { - self.engine.write(encodedPackets[i], packet.options); - } - self.encoding = false; - self.processPacketQueue(); - }); - } else { // add packet to the queue - self.packetBuffer.push(packet); - } - }; - - /** - * If packet buffer is non-empty, begins encoding the - * next packet in line. - * - * @api private - */ - - Manager.prototype.processPacketQueue = function() { - if (this.packetBuffer.length > 0 && !this.encoding) { - var pack = this.packetBuffer.shift(); - this.packet(pack); - } - }; - - /** - * Clean up transport subscriptions and packet buffer. - * - * @api private - */ - - Manager.prototype.cleanup = function(){ - debug('cleanup'); - - var sub; - while (sub = this.subs.shift()) sub.destroy(); - - this.packetBuffer = []; - this.encoding = false; - this.lastPing = null; - - this.decoder.destroy(); - }; - - /** - * Close the current socket. - * - * @api private - */ - - Manager.prototype.close = - Manager.prototype.disconnect = function(){ - debug('disconnect'); - this.skipReconnect = true; - this.reconnecting = false; - if ('opening' == this.readyState) { - // `onclose` will not fire because - // an open event never happened - this.cleanup(); - } - this.backoff.reset(); - this.readyState = 'closed'; - if (this.engine) this.engine.close(); - }; - - /** - * Called upon engine close. - * - * @api private - */ - - Manager.prototype.onclose = function(reason){ - debug('onclose'); - - this.cleanup(); - this.backoff.reset(); - this.readyState = 'closed'; - this.emit('close', reason); - - if (this._reconnection && !this.skipReconnect) { - this.reconnect(); - } - }; - - /** - * Attempt a reconnection. - * - * @api private - */ - - Manager.prototype.reconnect = function(){ - if (this.reconnecting || this.skipReconnect) return this; - - var self = this; - - if (this.backoff.attempts >= this._reconnectionAttempts) { - debug('reconnect failed'); - this.backoff.reset(); - this.emitAll('reconnect_failed'); - this.reconnecting = false; - } else { - var delay = this.backoff.duration(); - debug('will wait %dms before reconnect attempt', delay); - - this.reconnecting = true; - var timer = setTimeout(function(){ - if (self.skipReconnect) return; - - debug('attempting reconnect'); - self.emitAll('reconnect_attempt', self.backoff.attempts); - self.emitAll('reconnecting', self.backoff.attempts); - - // check again for the case socket closed in above events - if (self.skipReconnect) return; - - self.open(function(err){ - if (err) { - debug('reconnect attempt error'); - self.reconnecting = false; - self.reconnect(); - self.emitAll('reconnect_error', err.data); - } else { - debug('reconnect success'); - self.onreconnect(); - } - }); - }, delay); - - this.subs.push({ - destroy: function(){ - clearTimeout(timer); - } - }); - } - }; - - /** - * Called upon successful reconnect. - * - * @api private - */ - - Manager.prototype.onreconnect = function(){ - var attempt = this.backoff.attempts; - this.reconnecting = false; - this.backoff.reset(); - this.updateSocketIds(); - this.emitAll('reconnect', attempt); - }; - - -/***/ }, -/* 79 */ -/***/ function(module, exports) { - - - /** - * Module exports. - */ - - module.exports = on; - - /** - * Helper for subscriptions. - * - * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` - * @param {String} event name - * @param {Function} callback - * @api public - */ - - function on(obj, ev, fn) { - obj.on(ev, fn); - return { - destroy: function(){ - obj.removeListener(ev, fn); - } - }; - } - - -/***/ }, -/* 80 */ -/***/ function(module, exports, __webpack_require__) { - - - /** - * Module dependencies. - */ - - var parser = __webpack_require__(40); - var Emitter = __webpack_require__(56); - var toArray = __webpack_require__(201); - var on = __webpack_require__(79); - var bind = __webpack_require__(55); - var debug = __webpack_require__(3)('socket.io-client:socket'); - var hasBin = __webpack_require__(179); - - /** - * Module exports. - */ - - module.exports = exports = Socket; - - /** - * Internal events (blacklisted). - * These events can't be emitted by the user. - * - * @api private - */ - - var events = { - connect: 1, - connect_error: 1, - connect_timeout: 1, - connecting: 1, - disconnect: 1, - error: 1, - reconnect: 1, - reconnect_attempt: 1, - reconnect_failed: 1, - reconnect_error: 1, - reconnecting: 1, - ping: 1, - pong: 1 - }; - - /** - * Shortcut to `Emitter#emit`. - */ - - var emit = Emitter.prototype.emit; - - /** - * `Socket` constructor. - * - * @api public - */ - - function Socket(io, nsp){ - this.io = io; - this.nsp = nsp; - this.json = this; // compat - this.ids = 0; - this.acks = {}; - this.receiveBuffer = []; - this.sendBuffer = []; - this.connected = false; - this.disconnected = true; - if (this.io.autoConnect) this.open(); - } - - /** - * Mix in `Emitter`. - */ - - Emitter(Socket.prototype); - - /** - * Subscribe to open, close and packet events - * - * @api private - */ - - Socket.prototype.subEvents = function() { - if (this.subs) return; - - var io = this.io; - this.subs = [ - on(io, 'open', bind(this, 'onopen')), - on(io, 'packet', bind(this, 'onpacket')), - on(io, 'close', bind(this, 'onclose')) - ]; - }; - - /** - * "Opens" the socket. - * - * @api public - */ - - Socket.prototype.open = - Socket.prototype.connect = function(){ - if (this.connected) return this; - - this.subEvents(); - this.io.open(); // ensure open - if ('open' == this.io.readyState) this.onopen(); - this.emit('connecting'); - return this; - }; - - /** - * Sends a `message` event. - * - * @return {Socket} self - * @api public - */ - - Socket.prototype.send = function(){ - var args = toArray(arguments); - args.unshift('message'); - this.emit.apply(this, args); - return this; - }; - - /** - * Override `emit`. - * If the event is in `events`, it's emitted normally. - * - * @param {String} event name - * @return {Socket} self - * @api public - */ - - Socket.prototype.emit = function(ev){ - if (events.hasOwnProperty(ev)) { - emit.apply(this, arguments); - return this; - } - - var args = toArray(arguments); - var parserType = parser.EVENT; // default - if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary - var packet = { type: parserType, data: args }; - - packet.options = {}; - packet.options.compress = !this.flags || false !== this.flags.compress; - - // event ack callback - if ('function' == typeof args[args.length - 1]) { - debug('emitting packet with ack id %d', this.ids); - this.acks[this.ids] = args.pop(); - packet.id = this.ids++; - } - - if (this.connected) { - this.packet(packet); - } else { - this.sendBuffer.push(packet); - } - - delete this.flags; - - return this; - }; - - /** - * Sends a packet. - * - * @param {Object} packet - * @api private - */ - - Socket.prototype.packet = function(packet){ - packet.nsp = this.nsp; - this.io.packet(packet); - }; - - /** - * Called upon engine `open`. - * - * @api private - */ - - Socket.prototype.onopen = function(){ - debug('transport is open - connecting'); - - // write connect packet if necessary - if ('/' != this.nsp) { - this.packet({ type: parser.CONNECT }); - } - }; - - /** - * Called upon engine `close`. - * - * @param {String} reason - * @api private - */ - - Socket.prototype.onclose = function(reason){ - debug('close (%s)', reason); - this.connected = false; - this.disconnected = true; - delete this.id; - this.emit('disconnect', reason); - }; - - /** - * Called with socket packet. - * - * @param {Object} packet - * @api private - */ - - Socket.prototype.onpacket = function(packet){ - if (packet.nsp != this.nsp) return; - - switch (packet.type) { - case parser.CONNECT: - this.onconnect(); - break; - - case parser.EVENT: - this.onevent(packet); - break; - - case parser.BINARY_EVENT: - this.onevent(packet); - break; - - case parser.ACK: - this.onack(packet); - break; - - case parser.BINARY_ACK: - this.onack(packet); - break; - - case parser.DISCONNECT: - this.ondisconnect(); - break; - - case parser.ERROR: - this.emit('error', packet.data); - break; - } - }; - - /** - * Called upon a server event. - * - * @param {Object} packet - * @api private - */ - - Socket.prototype.onevent = function(packet){ - var args = packet.data || []; - debug('emitting event %j', args); - - if (null != packet.id) { - debug('attaching ack callback to event'); - args.push(this.ack(packet.id)); - } - - if (this.connected) { - emit.apply(this, args); - } else { - this.receiveBuffer.push(args); - } - }; - - /** - * Produces an ack callback to emit with an event. - * - * @api private - */ - - Socket.prototype.ack = function(id){ - var self = this; - var sent = false; - return function(){ - // prevent double callbacks - if (sent) return; - sent = true; - var args = toArray(arguments); - debug('sending ack %j', args); - - var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK; - self.packet({ - type: type, - id: id, - data: args - }); - }; - }; - - /** - * Called upon a server acknowlegement. - * - * @param {Object} packet - * @api private - */ - - Socket.prototype.onack = function(packet){ - var ack = this.acks[packet.id]; - if ('function' == typeof ack) { - debug('calling ack %s with %j', packet.id, packet.data); - ack.apply(this, packet.data); - delete this.acks[packet.id]; - } else { - debug('bad ack %s', packet.id); - } - }; - - /** - * Called upon server connect. - * - * @api private - */ - - Socket.prototype.onconnect = function(){ - this.connected = true; - this.disconnected = false; - this.emit('connect'); - this.emitBuffered(); - }; - - /** - * Emit buffered events (received and emitted). - * - * @api private - */ - - Socket.prototype.emitBuffered = function(){ - var i; - for (i = 0; i < this.receiveBuffer.length; i++) { - emit.apply(this, this.receiveBuffer[i]); - } - this.receiveBuffer = []; - - for (i = 0; i < this.sendBuffer.length; i++) { - this.packet(this.sendBuffer[i]); - } - this.sendBuffer = []; - }; - - /** - * Called upon server disconnect. - * - * @api private - */ - - Socket.prototype.ondisconnect = function(){ - debug('server disconnect (%s)', this.nsp); - this.destroy(); - this.onclose('io server disconnect'); - }; - - /** - * Called upon forced client/server side disconnections, - * this method ensures the manager stops tracking us and - * that reconnections don't get triggered for this. - * - * @api private. - */ - - Socket.prototype.destroy = function(){ - if (this.subs) { - // clean subscriptions to avoid reconnections - for (var i = 0; i < this.subs.length; i++) { - this.subs[i].destroy(); - } - this.subs = null; - } - - this.io.destroy(this); - }; - - /** - * Disconnects the socket manually. - * - * @return {Socket} self - * @api public - */ - - Socket.prototype.close = - Socket.prototype.disconnect = function(){ - if (this.connected) { - debug('performing disconnect (%s)', this.nsp); - this.packet({ type: parser.DISCONNECT }); - } - - // remove socket from pool - this.destroy(); - - if (this.connected) { - // fire events - this.onclose('io client disconnect'); - } - return this; - }; - - /** - * Sets the compress flag. - * - * @param {Boolean} if `true`, compresses the sending data - * @return {Socket} self - * @api public - */ - - Socket.prototype.compress = function(compress){ - this.flags = this.flags || {}; - this.flags.compress = compress; - return this; - }; - - -/***/ }, -/* 81 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) { - module.exports = isBuf; - - /** - * Returns true if obj is a buffer or an arraybuffer. - * - * @api private - */ - - function isBuf(obj) { - return (global.Buffer && global.Buffer.isBuffer(obj)) || - (global.ArrayBuffer && obj instanceof ArrayBuffer); - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0))) - -/***/ }, -/* 82 */ -/***/ function(module, exports) { - - module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; - }; - - -/***/ }, -/* 83 */ -/***/ function(module, exports) { - - "use strict"; - 'use strict'; - - var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') - , length = 64 - , map = {} - , seed = 0 - , i = 0 - , prev; - - /** - * Return a string representing the specified number. - * - * @param {Number} num The number to convert. - * @returns {String} The string representation of the number. - * @api public - */ - function encode(num) { - var encoded = ''; - - do { - encoded = alphabet[num % length] + encoded; - num = Math.floor(num / length); - } while (num > 0); - - return encoded; - } - - /** - * Return the integer value specified by the given string. - * - * @param {String} str The string to convert. - * @returns {Number} The integer value represented by the string. - * @api public - */ - function decode(str) { - var decoded = 0; - - for (i = 0; i < str.length; i++) { - decoded = decoded * length + map[str.charAt(i)]; - } - - return decoded; - } - - /** - * Yeast: A tiny growing id generator. - * - * @returns {String} A unique id. - * @api public - */ - function yeast() { - var now = encode(+new Date()); - - if (now !== prev) return seed = 0, prev = now; - return now +'.'+ encode(seed++); - } - - // - // Map each character to its index. - // - for (; i < length; i++) map[alphabet[i]] = i; - - // - // Expose the `yeast`, `encode` and `decode` functions. - // - yeast.encode = encode; - yeast.decode = decode; - module.exports = yeast; - - -/***/ }, -/* 84 */ -/***/ function(module, exports, __webpack_require__) { - - "use strict"; - 'use strict'; - - var _stringify = __webpack_require__(51); - - var _stringify2 = _interopRequireDefault(_stringify); - - var _promise = __webpack_require__(52); - - var _promise2 = _interopRequireDefault(_promise); - - var _classCallCheck2 = __webpack_require__(53); - - var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); - - var _createClass2 = __webpack_require__(54); - - var _createClass3 = _interopRequireDefault(_createClass2); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - var EventEmitter = __webpack_require__(37).EventEmitter; - var Logger = __webpack_require__(21); - var logger = Logger.create("orbit-db", { color: Logger.Colors.Magenta }); - var EventStore = __webpack_require__(75); - var FeedStore = __webpack_require__(190); - var KeyValueStore = __webpack_require__(192); - var CounterStore = __webpack_require__(188); - var PubSub = __webpack_require__(124); - - var OrbitDB = function () { - function OrbitDB(ipfs) { - (0, _classCallCheck3.default)(this, OrbitDB); - - this._ipfs = ipfs; - this._pubsub = null; - this.user = null; - this.network = null; - this.events = new EventEmitter(); - this.stores = {}; - } - - /* Databases */ - - - (0, _createClass3.default)(OrbitDB, [{ - key: 'feed', - value: function feed(dbname, options) { - return this._createStore(FeedStore, dbname, options); - } - }, { - key: 'eventlog', - value: function eventlog(dbname, options) { - return this._createStore(EventStore, dbname, options); - } - }, { - key: 'kvstore', - value: function kvstore(dbname, options) { - return this._createStore(KeyValueStore, dbname, options); - } - }, { - key: 'counter', - value: function counter(dbname, options) { - return this._createStore(CounterStore, dbname, options); - } - }, { - key: 'disconnect', - value: function disconnect() { - this._pubsub.disconnect(); - this.stores = {}; - this.user = null; - this.network = null; - } - }, { - key: '_createStore', - value: function _createStore(Store, dbname, options) { - if (!options) options = {}; - var replicate = options.subscribe ? options.subscribe : true; - var store = new Store(this._ipfs, this.user.username, dbname, options); - this.stores[dbname] = store; - return this._subscribe(store, dbname, replicate); - } - }, { - key: '_subscribe', - value: function _subscribe(store, dbname, subscribe, callback) { - if (subscribe === undefined) subscribe = true; - - store.events.on('load', this._onLoad.bind(this)); - store.events.on('ready', this._onReady.bind(this)); - store.events.on('sync', this._onSync.bind(this)); - store.events.on('updated', this._onSynced.bind(this)); - store.events.on('data', this._onWrite.bind(this)); - store.events.on('close', this._onClose.bind(this)); - - if (subscribe) this._pubsub.subscribe(dbname, '', this._onMessage.bind(this)); - - return store.use(this.user.username); - } - }, { - key: '_onMessage', - value: function _onMessage(dbname, message) { - // console.log(".MESSAGE", dbname, message); - var store = this.stores[dbname]; - store.sync(message).catch(function (e) { - return logger.error(e.stack); - }); - } - }, { - key: '_onWrite', - value: function _onWrite(dbname, hash) { - // console.log(".WRITE", dbname); - if (!hash) throw new Error("Hash can't be null!"); - this._pubsub.publish(dbname, hash); - this.events.emit('data', dbname, hash); - } - }, { - key: '_onSync', - value: function _onSync(dbname) { - // console.log(".SYNC", dbname); - this.events.emit('sync', dbname); - } - }, { - key: '_onSynced', - value: function _onSynced(dbname, items) { - // console.log(".SYNCED", dbname); - this.events.emit('synced', dbname, items); - } - }, { - key: '_onLoad', - value: function _onLoad(dbname) { - // console.log(".LOAD", dbname); - this.events.emit('load', dbname); - } - }, { - key: '_onReady', - value: function _onReady(dbname) { - // console.log(".READY", dbname); - this.events.emit('ready', this.stores[dbname]); - } - }, { - key: '_onClose', - value: function _onClose(dbname) { - this._pubsub.unsubscribe(dbname); - delete this.stores[dbname]; - this.events.emit('closed', dbname); - } - }, { - key: '_connect', - value: function _connect(hash, username, password, allowOffline) { - var _this = this; - - if (allowOffline === undefined) allowOffline = false; - - var readNetworkInfo = function readNetworkInfo(hash) { - return new _promise2.default(function (resolve, reject) { - // this._ipfs.cat(hash).then((res) => { - // let buf = ''; - // res - // .on('error', (err) => reject(err)) - // .on('data', (data) => buf += data) - // .on('end', () => resolve(buf)) - // }).catch((e) => reject(e)); - resolve((0, _stringify2.default)({ - name: 'localhost dev network', - publishers: ['localhost:3333'] - })); - }); - }; - - var host = void 0, - port = void 0, - name = void 0; - return readNetworkInfo(hash).then(function (object) { - _this.network = JSON.parse(object); - name = _this.network.name; - host = _this.network.publishers[0].split(":")[0]; - port = _this.network.publishers[0].split(":")[1]; - }).then(function () { - _this._pubsub = new PubSub(); - logger.warn('Connecting to Pubsub at \'' + host + ':' + port + '\''); - return _this._pubsub.connect(host, port, username, password); - }).then(function () { - logger.debug('Connected to Pubsub at \'' + host + ':' + port + '\''); - _this.user = { username: username, id: username }; // TODO: user id from ipfs hash - return; - }).catch(function (e) { - logger.warn("Couldn't connect to Pubsub: " + e.message); - if (!allowOffline) { - logger.debug("'allowOffline' set to false, terminating"); - if (_this._pubsub) _this._pubsub.disconnect(); - throw e; - } - _this.user = { username: username, id: username }; // TODO: user id from ipfs hash - return; - }); - } - }]); - return OrbitDB; - }(); - - var OrbitClientFactory = function () { - function OrbitClientFactory() { - (0, _classCallCheck3.default)(this, OrbitClientFactory); - } - - (0, _createClass3.default)(OrbitClientFactory, null, [{ - key: 'connect', - value: function connect(network, username, password, ipfs, options) { - if (!options) options = { allowOffline: false }; - - if (!ipfs) { - logger.error("IPFS instance not provided"); - throw new Error("IPFS instance not provided"); - } - - var client = new OrbitDB(ipfs); - return client._connect(network, username, password, options.allowOffline).then(function () { - return client; - }); - } - }]); - return OrbitClientFactory; - }(); - - module.exports = OrbitClientFactory; - -/***/ }, -/* 85 */ -/***/ function(module, exports, __webpack_require__) { - - var require;var Ipfs = - /******/ (function(modules) { // webpackBootstrap - /******/ // The module cache - /******/ var installedModules = {}; - - /******/ // The require function - /******/ function __webpack_require__(moduleId) { - - /******/ // Check if module is in cache - /******/ if(installedModules[moduleId]) - /******/ return installedModules[moduleId].exports; - - /******/ // Create a new module (and put it into the cache) - /******/ var module = installedModules[moduleId] = { - /******/ i: moduleId, - /******/ l: false, - /******/ exports: {} - /******/ }; - - /******/ // Execute the module function - /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - - /******/ // Flag the module as loaded - /******/ module.l = true; - - /******/ // Return the exports of the module - /******/ return module.exports; - /******/ } - - - /******/ // expose the modules object (__webpack_modules__) - /******/ __webpack_require__.m = modules; - - /******/ // expose the module cache - /******/ __webpack_require__.c = installedModules; - - /******/ // __webpack_public_path__ - /******/ __webpack_require__.p = "/_karma_webpack_//"; - - /******/ // Load entry module and return exports - /******/ return __webpack_require__(__webpack_require__.s = 797); - /******/ }) - /************************************************************************/ - /******/ ([ - /* 0 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - /* WEBPACK VAR INJECTION */(function(Buffer, global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - 'use strict' - - var base64 = __webpack_require__(359) - var ieee754 = __webpack_require__(644) - var isArray = __webpack_require__(43) - - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - - /* - * Export kMaxLength after typed array support is determined. - */ - exports.kMaxLength = kMaxLength() - - function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.foo = function () { return 42 } - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } - } - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer.poolSize = 8192 // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr - } - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - } - - function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; i++) { - that[i] = 0 - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - } - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - } - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - that.write(string, encoding) - return that - } - - function fromArrayLike (that, array) { - var length = checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that - } - - function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) - } - - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'binary': - case 'base64': - case 'raw': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - } - - Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; i++) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; i++) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer - } - - function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'binary': - // Deprecated - case 'raw': - case 'raws': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - Buffer.byteLength = byteLength - - function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'binary': - return binarySlice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true - - function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i - } - - Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this - } - - Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this - } - - Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - } - - Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - } - - Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' - } - - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - function arrayIndexOf (arr, val, byteOffset, encoding) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var foundIndex = -1 - for (var i = 0; byteOffset + i < arrLength; i++) { - if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - return -1 - } - - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset >>= 0 - - if (this.length === 0) return -1 - if (byteOffset >= this.length) return -1 - - // Negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) - - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - if (Buffer.isBuffer(val)) { - // special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(this, val, byteOffset, encoding) - } - if (typeof val === 'number') { - if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { - return Uint8Array.prototype.indexOf.call(this, val, byteOffset) - } - return arrayIndexOf(this, [ val ], byteOffset, encoding) - } - - throw new TypeError('val must be string, number or Buffer') - } - - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - } - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new Error('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; i++) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function binaryWrite (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'binary': - return binaryWrite(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - } - - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000 - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret - } - - function binarySlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; i++) { - ret += String.fromCharCode(buf[i]) - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; i++) { - out += toHex(buf[i]) - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res - } - - Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; i++) { - newBuf[i] = this[i + start] - } - } - - return newBuf - } - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val - } - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val - } - - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] - } - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) - } - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] - } - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - } - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - } - - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - } - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - } - - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - } - - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) - } - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) - } - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) - } - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) - } - - function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 - } - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 - } - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 - } - - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - } - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - } - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; i--) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; i++) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len - } - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; i++) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; i++) { - this[i + start] = bytes[i % len] - } - } - - return this - } - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str - } - - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; i++) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; i++) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; i++) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray - } - - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; i++) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer, __webpack_require__(18))) - - /***/ }, - /* 1 */ - /***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(8) - , core = __webpack_require__(40) - , hide = __webpack_require__(25) - , redefine = __webpack_require__(28) - , ctx = __webpack_require__(44) - , PROTOTYPE = 'prototype'; - - var $export = function(type, name, source){ - var IS_FORCED = type & $export.F - , IS_GLOBAL = type & $export.G - , IS_STATIC = type & $export.S - , IS_PROTO = type & $export.P - , IS_BIND = type & $export.B - , target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE] - , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) - , expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}) - , key, own, out, exp; - if(IS_GLOBAL)source = name; - for(key in source){ - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - // export native or passed - out = (own ? target : source)[key]; - // bind timers to global for call from export context - exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // extend global - if(target)redefine(target, key, out, type & $export.U); - // export - if(exports[key] != out)hide(exports, key, exp); - if(IS_PROTO && expProto[key] != out)expProto[key] = out; - } - }; - global.core = core; - // type bitmap - $export.F = 1; // forced - $export.G = 2; // global - $export.S = 4; // static - $export.P = 8; // proto - $export.B = 16; // bind - $export.W = 32; // wrap - $export.U = 64; // safe - $export.R = 128; // real proto method for `library` - module.exports = $export; - - /***/ }, - /* 2 */ - /***/ function(module, exports) { - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } - - - /***/ }, - /* 3 */ - /***/ function(module, exports) { - - // shim for using process in browser - - var process = module.exports = {}; - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = setTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - clearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - setTimeout(drainQueue, 0); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - - /***/ }, - /* 4 */ - /***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors. - // - // 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 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. - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - - function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; - } - exports.isArray = isArray; - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; - - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; - - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; - - function isNumber(arg) { - return typeof arg === 'number'; - } - exports.isNumber = isNumber; - - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - exports.isSymbol = isSymbol; - - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; - - function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; - } - exports.isRegExp = isRegExp; - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; - - function isDate(d) { - return objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; - - function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; - - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; - - exports.isBuffer = Buffer.isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0).Buffer)) - - /***/ }, - /* 5 */ - /***/ function(module, exports, __webpack_require__) { - - // Copyright Joyent, Inc. and other Node contributors. - // - // 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 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. - - module.exports = Stream; - - var EE = __webpack_require__(7).EventEmitter; - var inherits = __webpack_require__(2); - - inherits(Stream, EE); - Stream.Readable = __webpack_require__(770); - Stream.Writable = __webpack_require__(772); - Stream.Duplex = __webpack_require__(768); - Stream.Transform = __webpack_require__(771); - Stream.PassThrough = __webpack_require__(769); - - // Backwards-compat with node 0.4.x - Stream.Stream = Stream; - - - - // old-style streams. Note that the pipe method (the only relevant - // part of this class) is overridden in the Readable class. - - function Stream() { - EE.call(this); - } - - Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; - }; - - - /***/ }, - /* 6 */ - /***/ function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(12); - module.exports = function(it){ - if(!isObject(it))throw TypeError(it + ' is not an object!'); - return it; - }; - - /***/ }, - /* 7 */ - /***/ function(module, exports) { - - // Copyright Joyent, Inc. and other Node contributors. - // - // 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 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 EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; - } - module.exports = EventEmitter; - - // Backwards-compat with node 0.10.x - EventEmitter.EventEmitter = EventEmitter; - - EventEmitter.prototype._events = undefined; - EventEmitter.prototype._maxListeners = undefined; - - // By default EventEmitters will print a warning if more than 10 listeners are - // added to it. This is a useful default which helps finding memory leaks. - EventEmitter.defaultMaxListeners = 10; - - // Obviously not all Emitters should be limited to 10. This function allows - // that to be increased. Set to zero for unlimited. - EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; - }; - - EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } - throw TypeError('Uncaught, unspecified "error" event.'); - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; - }; - - EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; - }; - - EventEmitter.prototype.on = EventEmitter.prototype.addListener; - - EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; - }; - - // emits a 'removeListener' event iff the listener was removed - EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; - }; - - EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; - }; - - EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; - }; - - EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; - }; - - EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); - }; - - function isFunction(arg) { - return typeof arg === 'function'; - } - - function isNumber(arg) { - return typeof arg === 'number'; - } - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - - function isUndefined(arg) { - return arg === void 0; - } - - - /***/ }, - /* 8 */ - /***/ function(module, exports) { - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); - if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef - - /***/ }, - /* 9 */ - /***/ function(module, exports) { - - module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; - } - }; - - /***/ }, - /* 10 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - /* WEBPACK VAR INJECTION */(function(process) {'use strict'; - - if (!process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = nextTick; - } else { - module.exports = process.nextTick; - } - - function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - - /***/ }, - /* 11 */ - /***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. - // - // 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 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. - - var formatRegExp = /%[sdj%]/g; - exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; - - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - }; - - - var debugs = {}; - var debugEnviron; - exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; - }; - - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - exports.inspect = inspect; - - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } - - - function stylizeNoColor(str, styleType) { - return str; - } - - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; - } - - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } - - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } - - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - exports.isArray = isArray; - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; - - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; - - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; - - function isNumber(arg) { - return typeof arg === 'number'; - } - exports.isNumber = isNumber; - - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - exports.isSymbol = isSymbol; - - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - exports.isRegExp = isRegExp; - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; - - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; - - exports.isBuffer = __webpack_require__(779); - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } - - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } - - - // log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); - }; - - - /** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ - exports.inherits = __webpack_require__(2); - - exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - }; - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18), __webpack_require__(3))) - - /***/ }, - /* 12 */ - /***/ function(module, exports) { - - module.exports = function(it){ - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - - /***/ }, - /* 13 */ - /***/ function(module, exports, __webpack_require__) { - - var store = __webpack_require__(113)('wks') - , uid = __webpack_require__(61) - , Symbol = __webpack_require__(8).Symbol - , USE_SYMBOL = typeof Symbol == 'function'; - - var $exports = module.exports = function(name){ - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); - }; - - $exports.store = store; - - /***/ }, - /* 14 */ - /***/ function(module, exports, __webpack_require__) { - - // Copyright Joyent, Inc. and other Node contributors. - // - // 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 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. - - var Buffer = __webpack_require__(0).Buffer; - - var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } - - - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } - } - - // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; - }; - - - // write decodes the given buffer and returns it as JS string that is - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; - }; - - // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; - }; - - StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; - }; - - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } - - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } - - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; - } - - - /***/ }, - /* 15 */ - /***/ function(module, exports, __webpack_require__) { - - // Thank's IE8 for his funny defineProperty - module.exports = !__webpack_require__(9)(function(){ - return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; - }); - - /***/ }, - /* 16 */ - /***/ function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(6) - , IE8_DOM_DEFINE = __webpack_require__(218) - , toPrimitive = __webpack_require__(42) - , dP = Object.defineProperty; - - exports.f = __webpack_require__(15) ? Object.defineProperty : function defineProperty(O, P, Attributes){ - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if(IE8_DOM_DEFINE)try { - return dP(O, P, Attributes); - } catch(e){ /* empty */ } - if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); - if('value' in Attributes)O[P] = Attributes.value; - return O; - }; - - /***/ }, - /* 17 */ - /***/ function(module, exports, __webpack_require__) { - - - /** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - - exports = module.exports = __webpack_require__(591); - exports.log = log; - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; - exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - - /** - * Colors. - */ - - exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' - ]; - - /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - - function useColors() { - // is webkit? http://stackoverflow.com/a/16459606/376773 - return ('WebkitAppearance' in document.documentElement.style) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (window.console && (console.firebug || (console.exception && console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); - } - - /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - - exports.formatters.j = function(v) { - return JSON.stringify(v); - }; - - - /** - * Colorize log arguments if enabled. - * - * @api public - */ - - function formatArgs() { - var args = arguments; - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return args; - - var c = 'color: ' + this.color; - args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); - return args; - } - - /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - - function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } - - /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - - function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} - } - - /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - - function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - return r; - } - - /** - * Enable namespaces listed in `localStorage.debug` initially. - */ - - exports.enable(load()); - - /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - - function localstorage(){ - try { - return window.localStorage; - } catch (e) {} - } - - - /***/ }, - /* 18 */ - /***/ function(module, exports) { - - var g; - - // This works in non-strict mode - g = (function() { return this; })(); - - try { - // This works if eval is allowed (see CSP) - g = g || Function("return this")() || (1,eval)("this"); - } catch(e) { - // This works if the window reference is available - if(typeof window === "object") - g = window; - } - - // g can still be undefined, but nothing to do about it... - // We return undefined, instead of nothing here, so it's - // easier to handle this case. if(!global) { ...} - - module.exports = g; - - - /***/ }, - /* 19 */ - /***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) { - 'use strict'; - - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); - } - - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - - // BN - - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } - - this.negative = 0; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - this._init(number || 0, base || 10, endian || 'be'); - } - } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; - try { - Buffer = __webpack_require__(0).Buffer; - } catch (e) { - } - - BN.isBN = function isBN (num) { - return num !== null && typeof num === 'object' && - num.constructor.name === 'BN' && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } - - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } - - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } - - if (number[0] === '-') { - this.negative = 1; - } - - this.strip(); - - if (endian !== 'le') return; - - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - - if (endian !== 'le') return; - - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; - - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } - - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; - - function parseHex (str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r <<= 4; - - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; - - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; - - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; - } - - BN.prototype._parseHex = function _parseHex (number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } - - var j, w; - // Scan 24-bit chunks and add them to the number - var off = 0; - for (i = number.length - 6, j = 0; i >= start; i -= 6) { - w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - if (i + 6 !== start) { - w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - } - this.strip(); - }; - - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; - - r *= mul; - - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; - - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; - - // '0' - '9' - } else { - r += c; - } - } - return r; - } - - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; - - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); - - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - - for (i = 0; i < mod; i++) { - pow *= base; - } - - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - }; - - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; - - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; - - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; - - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; - - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; - - /* - - var zeros = []; - var groupSizes = []; - var groupBases = []; - - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; - } - - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; - - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; - - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - - assert(false, 'Base should be between 2 and 36'); - }; - - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; - - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; - - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; - - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); - - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); - - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } - - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); - - res[i] = b; - } - - for (; i < reqLength; i++) { - res[i] = 0; - } - } - - return res; - }; - - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } - - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; - - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; - - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - - function toBitArray (num) { - var w = new Array(num.bitLength()); - - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; - - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } - - return w; - } - - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; - - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; - - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; - - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; - - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; - - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; - - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; - - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } - - return this; - }; - - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } - - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } - - return this.strip(); - }; - - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; - - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } - - this.length = b.length; - - return this.strip(); - }; - - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; - } - - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); - - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); - - if (bitsLeft > 0) { - bytesNeeded--; - } - - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } - - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } - - // And remove leading zeroes - return this.strip(); - }; - - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; - - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); - - var off = (bit / 26) | 0; - var wbit = bit % 26; - - this._expand(off + 1); - - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - - return this.strip(); - }; - - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; - - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - return this; - }; - - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - - if (this.length > num.length) return this.clone().iadd(num); - - return num.clone().iadd(this); - }; - - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } - - this.length = Math.max(this.length, i); - - if (a !== this) { - this.negative = 1; - } - - return this.strip(); - }; - - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; - - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; - - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; - - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - - return out.strip(); - } - - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; - - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid += Math.imul(ah0, bl0); - hi = Math.imul(ah0, bh0); - var w0 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w0 >>> 26); - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid += Math.imul(ah1, bl0); - hi = Math.imul(ah1, bh0); - lo += Math.imul(al0, bl1); - mid += Math.imul(al0, bh1); - mid += Math.imul(ah0, bl1); - hi += Math.imul(ah0, bh1); - var w1 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w1 >>> 26); - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid += Math.imul(ah2, bl0); - hi = Math.imul(ah2, bh0); - lo += Math.imul(al1, bl1); - mid += Math.imul(al1, bh1); - mid += Math.imul(ah1, bl1); - hi += Math.imul(ah1, bh1); - lo += Math.imul(al0, bl2); - mid += Math.imul(al0, bh2); - mid += Math.imul(ah0, bl2); - hi += Math.imul(ah0, bh2); - var w2 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w2 >>> 26); - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid += Math.imul(ah3, bl0); - hi = Math.imul(ah3, bh0); - lo += Math.imul(al2, bl1); - mid += Math.imul(al2, bh1); - mid += Math.imul(ah2, bl1); - hi += Math.imul(ah2, bh1); - lo += Math.imul(al1, bl2); - mid += Math.imul(al1, bh2); - mid += Math.imul(ah1, bl2); - hi += Math.imul(ah1, bh2); - lo += Math.imul(al0, bl3); - mid += Math.imul(al0, bh3); - mid += Math.imul(ah0, bl3); - hi += Math.imul(ah0, bh3); - var w3 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w3 >>> 26); - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid += Math.imul(ah4, bl0); - hi = Math.imul(ah4, bh0); - lo += Math.imul(al3, bl1); - mid += Math.imul(al3, bh1); - mid += Math.imul(ah3, bl1); - hi += Math.imul(ah3, bh1); - lo += Math.imul(al2, bl2); - mid += Math.imul(al2, bh2); - mid += Math.imul(ah2, bl2); - hi += Math.imul(ah2, bh2); - lo += Math.imul(al1, bl3); - mid += Math.imul(al1, bh3); - mid += Math.imul(ah1, bl3); - hi += Math.imul(ah1, bh3); - lo += Math.imul(al0, bl4); - mid += Math.imul(al0, bh4); - mid += Math.imul(ah0, bl4); - hi += Math.imul(ah0, bh4); - var w4 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w4 >>> 26); - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid += Math.imul(ah5, bl0); - hi = Math.imul(ah5, bh0); - lo += Math.imul(al4, bl1); - mid += Math.imul(al4, bh1); - mid += Math.imul(ah4, bl1); - hi += Math.imul(ah4, bh1); - lo += Math.imul(al3, bl2); - mid += Math.imul(al3, bh2); - mid += Math.imul(ah3, bl2); - hi += Math.imul(ah3, bh2); - lo += Math.imul(al2, bl3); - mid += Math.imul(al2, bh3); - mid += Math.imul(ah2, bl3); - hi += Math.imul(ah2, bh3); - lo += Math.imul(al1, bl4); - mid += Math.imul(al1, bh4); - mid += Math.imul(ah1, bl4); - hi += Math.imul(ah1, bh4); - lo += Math.imul(al0, bl5); - mid += Math.imul(al0, bh5); - mid += Math.imul(ah0, bl5); - hi += Math.imul(ah0, bh5); - var w5 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w5 >>> 26); - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid += Math.imul(ah6, bl0); - hi = Math.imul(ah6, bh0); - lo += Math.imul(al5, bl1); - mid += Math.imul(al5, bh1); - mid += Math.imul(ah5, bl1); - hi += Math.imul(ah5, bh1); - lo += Math.imul(al4, bl2); - mid += Math.imul(al4, bh2); - mid += Math.imul(ah4, bl2); - hi += Math.imul(ah4, bh2); - lo += Math.imul(al3, bl3); - mid += Math.imul(al3, bh3); - mid += Math.imul(ah3, bl3); - hi += Math.imul(ah3, bh3); - lo += Math.imul(al2, bl4); - mid += Math.imul(al2, bh4); - mid += Math.imul(ah2, bl4); - hi += Math.imul(ah2, bh4); - lo += Math.imul(al1, bl5); - mid += Math.imul(al1, bh5); - mid += Math.imul(ah1, bl5); - hi += Math.imul(ah1, bh5); - lo += Math.imul(al0, bl6); - mid += Math.imul(al0, bh6); - mid += Math.imul(ah0, bl6); - hi += Math.imul(ah0, bh6); - var w6 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w6 >>> 26); - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid += Math.imul(ah7, bl0); - hi = Math.imul(ah7, bh0); - lo += Math.imul(al6, bl1); - mid += Math.imul(al6, bh1); - mid += Math.imul(ah6, bl1); - hi += Math.imul(ah6, bh1); - lo += Math.imul(al5, bl2); - mid += Math.imul(al5, bh2); - mid += Math.imul(ah5, bl2); - hi += Math.imul(ah5, bh2); - lo += Math.imul(al4, bl3); - mid += Math.imul(al4, bh3); - mid += Math.imul(ah4, bl3); - hi += Math.imul(ah4, bh3); - lo += Math.imul(al3, bl4); - mid += Math.imul(al3, bh4); - mid += Math.imul(ah3, bl4); - hi += Math.imul(ah3, bh4); - lo += Math.imul(al2, bl5); - mid += Math.imul(al2, bh5); - mid += Math.imul(ah2, bl5); - hi += Math.imul(ah2, bh5); - lo += Math.imul(al1, bl6); - mid += Math.imul(al1, bh6); - mid += Math.imul(ah1, bl6); - hi += Math.imul(ah1, bh6); - lo += Math.imul(al0, bl7); - mid += Math.imul(al0, bh7); - mid += Math.imul(ah0, bl7); - hi += Math.imul(ah0, bh7); - var w7 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w7 >>> 26); - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid += Math.imul(ah8, bl0); - hi = Math.imul(ah8, bh0); - lo += Math.imul(al7, bl1); - mid += Math.imul(al7, bh1); - mid += Math.imul(ah7, bl1); - hi += Math.imul(ah7, bh1); - lo += Math.imul(al6, bl2); - mid += Math.imul(al6, bh2); - mid += Math.imul(ah6, bl2); - hi += Math.imul(ah6, bh2); - lo += Math.imul(al5, bl3); - mid += Math.imul(al5, bh3); - mid += Math.imul(ah5, bl3); - hi += Math.imul(ah5, bh3); - lo += Math.imul(al4, bl4); - mid += Math.imul(al4, bh4); - mid += Math.imul(ah4, bl4); - hi += Math.imul(ah4, bh4); - lo += Math.imul(al3, bl5); - mid += Math.imul(al3, bh5); - mid += Math.imul(ah3, bl5); - hi += Math.imul(ah3, bh5); - lo += Math.imul(al2, bl6); - mid += Math.imul(al2, bh6); - mid += Math.imul(ah2, bl6); - hi += Math.imul(ah2, bh6); - lo += Math.imul(al1, bl7); - mid += Math.imul(al1, bh7); - mid += Math.imul(ah1, bl7); - hi += Math.imul(ah1, bh7); - lo += Math.imul(al0, bl8); - mid += Math.imul(al0, bh8); - mid += Math.imul(ah0, bl8); - hi += Math.imul(ah0, bh8); - var w8 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w8 >>> 26); - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid += Math.imul(ah9, bl0); - hi = Math.imul(ah9, bh0); - lo += Math.imul(al8, bl1); - mid += Math.imul(al8, bh1); - mid += Math.imul(ah8, bl1); - hi += Math.imul(ah8, bh1); - lo += Math.imul(al7, bl2); - mid += Math.imul(al7, bh2); - mid += Math.imul(ah7, bl2); - hi += Math.imul(ah7, bh2); - lo += Math.imul(al6, bl3); - mid += Math.imul(al6, bh3); - mid += Math.imul(ah6, bl3); - hi += Math.imul(ah6, bh3); - lo += Math.imul(al5, bl4); - mid += Math.imul(al5, bh4); - mid += Math.imul(ah5, bl4); - hi += Math.imul(ah5, bh4); - lo += Math.imul(al4, bl5); - mid += Math.imul(al4, bh5); - mid += Math.imul(ah4, bl5); - hi += Math.imul(ah4, bh5); - lo += Math.imul(al3, bl6); - mid += Math.imul(al3, bh6); - mid += Math.imul(ah3, bl6); - hi += Math.imul(ah3, bh6); - lo += Math.imul(al2, bl7); - mid += Math.imul(al2, bh7); - mid += Math.imul(ah2, bl7); - hi += Math.imul(ah2, bh7); - lo += Math.imul(al1, bl8); - mid += Math.imul(al1, bh8); - mid += Math.imul(ah1, bl8); - hi += Math.imul(ah1, bh8); - lo += Math.imul(al0, bl9); - mid += Math.imul(al0, bh9); - mid += Math.imul(ah0, bl9); - hi += Math.imul(ah0, bh9); - var w9 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w9 >>> 26); - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid += Math.imul(ah9, bl1); - hi = Math.imul(ah9, bh1); - lo += Math.imul(al8, bl2); - mid += Math.imul(al8, bh2); - mid += Math.imul(ah8, bl2); - hi += Math.imul(ah8, bh2); - lo += Math.imul(al7, bl3); - mid += Math.imul(al7, bh3); - mid += Math.imul(ah7, bl3); - hi += Math.imul(ah7, bh3); - lo += Math.imul(al6, bl4); - mid += Math.imul(al6, bh4); - mid += Math.imul(ah6, bl4); - hi += Math.imul(ah6, bh4); - lo += Math.imul(al5, bl5); - mid += Math.imul(al5, bh5); - mid += Math.imul(ah5, bl5); - hi += Math.imul(ah5, bh5); - lo += Math.imul(al4, bl6); - mid += Math.imul(al4, bh6); - mid += Math.imul(ah4, bl6); - hi += Math.imul(ah4, bh6); - lo += Math.imul(al3, bl7); - mid += Math.imul(al3, bh7); - mid += Math.imul(ah3, bl7); - hi += Math.imul(ah3, bh7); - lo += Math.imul(al2, bl8); - mid += Math.imul(al2, bh8); - mid += Math.imul(ah2, bl8); - hi += Math.imul(ah2, bh8); - lo += Math.imul(al1, bl9); - mid += Math.imul(al1, bh9); - mid += Math.imul(ah1, bl9); - hi += Math.imul(ah1, bh9); - var w10 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w10 >>> 26); - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid += Math.imul(ah9, bl2); - hi = Math.imul(ah9, bh2); - lo += Math.imul(al8, bl3); - mid += Math.imul(al8, bh3); - mid += Math.imul(ah8, bl3); - hi += Math.imul(ah8, bh3); - lo += Math.imul(al7, bl4); - mid += Math.imul(al7, bh4); - mid += Math.imul(ah7, bl4); - hi += Math.imul(ah7, bh4); - lo += Math.imul(al6, bl5); - mid += Math.imul(al6, bh5); - mid += Math.imul(ah6, bl5); - hi += Math.imul(ah6, bh5); - lo += Math.imul(al5, bl6); - mid += Math.imul(al5, bh6); - mid += Math.imul(ah5, bl6); - hi += Math.imul(ah5, bh6); - lo += Math.imul(al4, bl7); - mid += Math.imul(al4, bh7); - mid += Math.imul(ah4, bl7); - hi += Math.imul(ah4, bh7); - lo += Math.imul(al3, bl8); - mid += Math.imul(al3, bh8); - mid += Math.imul(ah3, bl8); - hi += Math.imul(ah3, bh8); - lo += Math.imul(al2, bl9); - mid += Math.imul(al2, bh9); - mid += Math.imul(ah2, bl9); - hi += Math.imul(ah2, bh9); - var w11 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w11 >>> 26); - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid += Math.imul(ah9, bl3); - hi = Math.imul(ah9, bh3); - lo += Math.imul(al8, bl4); - mid += Math.imul(al8, bh4); - mid += Math.imul(ah8, bl4); - hi += Math.imul(ah8, bh4); - lo += Math.imul(al7, bl5); - mid += Math.imul(al7, bh5); - mid += Math.imul(ah7, bl5); - hi += Math.imul(ah7, bh5); - lo += Math.imul(al6, bl6); - mid += Math.imul(al6, bh6); - mid += Math.imul(ah6, bl6); - hi += Math.imul(ah6, bh6); - lo += Math.imul(al5, bl7); - mid += Math.imul(al5, bh7); - mid += Math.imul(ah5, bl7); - hi += Math.imul(ah5, bh7); - lo += Math.imul(al4, bl8); - mid += Math.imul(al4, bh8); - mid += Math.imul(ah4, bl8); - hi += Math.imul(ah4, bh8); - lo += Math.imul(al3, bl9); - mid += Math.imul(al3, bh9); - mid += Math.imul(ah3, bl9); - hi += Math.imul(ah3, bh9); - var w12 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w12 >>> 26); - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid += Math.imul(ah9, bl4); - hi = Math.imul(ah9, bh4); - lo += Math.imul(al8, bl5); - mid += Math.imul(al8, bh5); - mid += Math.imul(ah8, bl5); - hi += Math.imul(ah8, bh5); - lo += Math.imul(al7, bl6); - mid += Math.imul(al7, bh6); - mid += Math.imul(ah7, bl6); - hi += Math.imul(ah7, bh6); - lo += Math.imul(al6, bl7); - mid += Math.imul(al6, bh7); - mid += Math.imul(ah6, bl7); - hi += Math.imul(ah6, bh7); - lo += Math.imul(al5, bl8); - mid += Math.imul(al5, bh8); - mid += Math.imul(ah5, bl8); - hi += Math.imul(ah5, bh8); - lo += Math.imul(al4, bl9); - mid += Math.imul(al4, bh9); - mid += Math.imul(ah4, bl9); - hi += Math.imul(ah4, bh9); - var w13 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w13 >>> 26); - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid += Math.imul(ah9, bl5); - hi = Math.imul(ah9, bh5); - lo += Math.imul(al8, bl6); - mid += Math.imul(al8, bh6); - mid += Math.imul(ah8, bl6); - hi += Math.imul(ah8, bh6); - lo += Math.imul(al7, bl7); - mid += Math.imul(al7, bh7); - mid += Math.imul(ah7, bl7); - hi += Math.imul(ah7, bh7); - lo += Math.imul(al6, bl8); - mid += Math.imul(al6, bh8); - mid += Math.imul(ah6, bl8); - hi += Math.imul(ah6, bh8); - lo += Math.imul(al5, bl9); - mid += Math.imul(al5, bh9); - mid += Math.imul(ah5, bl9); - hi += Math.imul(ah5, bh9); - var w14 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w14 >>> 26); - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid += Math.imul(ah9, bl6); - hi = Math.imul(ah9, bh6); - lo += Math.imul(al8, bl7); - mid += Math.imul(al8, bh7); - mid += Math.imul(ah8, bl7); - hi += Math.imul(ah8, bh7); - lo += Math.imul(al7, bl8); - mid += Math.imul(al7, bh8); - mid += Math.imul(ah7, bl8); - hi += Math.imul(ah7, bh8); - lo += Math.imul(al6, bl9); - mid += Math.imul(al6, bh9); - mid += Math.imul(ah6, bl9); - hi += Math.imul(ah6, bh9); - var w15 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w15 >>> 26); - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid += Math.imul(ah9, bl7); - hi = Math.imul(ah9, bh7); - lo += Math.imul(al8, bl8); - mid += Math.imul(al8, bh8); - mid += Math.imul(ah8, bl8); - hi += Math.imul(ah8, bh8); - lo += Math.imul(al7, bl9); - mid += Math.imul(al7, bh9); - mid += Math.imul(ah7, bl9); - hi += Math.imul(ah7, bh9); - var w16 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w16 >>> 26); - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid += Math.imul(ah9, bl8); - hi = Math.imul(ah9, bh8); - lo += Math.imul(al8, bl9); - mid += Math.imul(al8, bh9); - mid += Math.imul(ah8, bl9); - hi += Math.imul(ah8, bh9); - var w17 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w17 >>> 26); - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid += Math.imul(ah9, bl9); - hi = Math.imul(ah9, bh9); - var w18 = c + lo + ((mid & 0x1fff) << 13); - c = hi + (mid >>> 13) + (w18 >>> 26); - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } - - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; - } - - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } - - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this.strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); - }; - - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(this.negative === 0, 'imaskn works only with positive numbers'); - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this.strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); - } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - return this.strip(); - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, 'Number is too big'); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; - - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); - - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - - return prime; - }; - - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; - } - } - - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; - - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; - - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; - - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; - - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; - - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; - }; - - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; - }; - - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - - // - // Montgomery method engine - // - - BN.mont = function mont (num) { - return new Mont(num); - }; - - function Mont (m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); - - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; - - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; - })(typeof module === 'undefined' || module, this); - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(48)(module))) - - /***/ }, - /* 20 */ - /***/ function(module, exports, __webpack_require__) { - - // 7.1.15 ToLength - var toInteger = __webpack_require__(52) - , min = Math.min; - module.exports = function(it){ - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 - }; - - /***/ }, - /* 21 */ - /***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(setImmediate, clearImmediate) {var nextTick = __webpack_require__(3).nextTick; - var apply = Function.prototype.apply; - var slice = Array.prototype.slice; - var immediateIds = {}; - var nextImmediateId = 0; - - // DOM APIs, for completeness - - exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); - }; - exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); - }; - exports.clearTimeout = - exports.clearInterval = function(timeout) { timeout.close(); }; - - function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; - } - Timeout.prototype.unref = Timeout.prototype.ref = function() {}; - Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); - }; - - // Does not start the time, just sets up the members needed. - exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; - }; - - exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; - }; - - exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } - }; - - // That's not how node.js implements it but the exposed api is the same. - exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; - }; - - exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; - }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(21).setImmediate, __webpack_require__(21).clearImmediate)) - - /***/ }, - /* 22 */ - /***/ function(module, exports, __webpack_require__) { - - // 7.1.13 ToObject(argument) - var defined = __webpack_require__(37); - module.exports = function(it){ - return Object(defined(it)); - }; - - /***/ }, - /* 23 */ - /***/ function(module, exports) { - - var hasOwnProperty = {}.hasOwnProperty; - module.exports = function(it, key){ - return hasOwnProperty.call(it, key); - }; - - /***/ }, - /* 24 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - 'use strict'; - - var transport = exports; - - // Exports utils - transport.utils = __webpack_require__(765); - - // Export parser&framer - transport.protocol = {}; - transport.protocol.base = __webpack_require__(177); - transport.protocol.spdy = __webpack_require__(283); - transport.protocol.http2 = __webpack_require__(129); - - // Window - transport.Window = __webpack_require__(766); - - // Priority Tree - transport.Priority = __webpack_require__(750); - - // Export Connection and Stream - transport.Stream = __webpack_require__(764).Stream; - transport.Connection = __webpack_require__(749).Connection; - - // Just for `transport.connection.create()` - transport.connection = transport.Connection; - - - /***/ }, - /* 25 */ - /***/ function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(16) - , createDesc = __webpack_require__(51); - module.exports = __webpack_require__(15) ? function(object, key, value){ - return dP.f(object, key, createDesc(1, value)); - } : function(object, key, value){ - object[key] = value; - return object; - }; - - /***/ }, - /* 26 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - 'use strict'; - - var elliptic = exports; - - elliptic.version = __webpack_require__(296).version; - elliptic.utils = __webpack_require__(618); - elliptic.rand = __webpack_require__(196); - elliptic.hmacDRBG = __webpack_require__(616); - elliptic.curve = __webpack_require__(115); - elliptic.curves = __webpack_require__(609); - - // Protocols - elliptic.ec = __webpack_require__(610); - elliptic.eddsa = __webpack_require__(613); - - - /***/ }, - /* 27 */ - /***/ function(module, exports) { - - module.exports = function(it){ - if(typeof it != 'function')throw TypeError(it + ' is not a function!'); - return it; - }; - - /***/ }, - /* 28 */ - /***/ function(module, exports, __webpack_require__) { - - var global = __webpack_require__(8) - , hide = __webpack_require__(25) - , has = __webpack_require__(23) - , SRC = __webpack_require__(61)('src') - , TO_STRING = 'toString' - , $toString = Function[TO_STRING] - , TPL = ('' + $toString).split(TO_STRING); - - __webpack_require__(40).inspectSource = function(it){ - return $toString.call(it); - }; - - (module.exports = function(O, key, val, safe){ - var isFunction = typeof val == 'function'; - if(isFunction)has(val, 'name') || hide(val, 'name', key); - if(O[key] === val)return; - if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); - if(O === global){ - O[key] = val; - } else { - if(!safe){ - delete O[key]; - hide(O, key, val); - } else { - if(O[key])O[key] = val; - else hide(O, key, val); - } - } - // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative - })(Function.prototype, TO_STRING, function toString(){ - return typeof this == 'function' && this[SRC] || $toString.call(this); - }); - - /***/ }, - /* 29 */ - /***/ function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(1) - , fails = __webpack_require__(9) - , defined = __webpack_require__(37) - , quot = /"/g; - // B.2.3.2.1 CreateHTML(string, tag, attribute, value) - var createHTML = function(string, tag, attribute, value) { - var S = String(defined(string)) - , p1 = '<' + tag; - if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; - return p1 + '>' + S + ''; - }; - module.exports = function(NAME, exec){ - var O = {}; - O[NAME] = exec(createHTML); - $export($export.P + $export.F * fails(function(){ - var test = ''[NAME]('"'); - return test !== test.toLowerCase() || test.split('"').length > 3; - }), 'String', O); - }; - - /***/ }, - /* 30 */ - /***/ function(module, exports, __webpack_require__) { - - // to indexed object, toObject with fallback for non-array-like ES3 strings - var IObject = __webpack_require__(86) - , defined = __webpack_require__(37); - module.exports = function(it){ - return IObject(defined(it)); - }; - - /***/ }, - /* 31 */ - /***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(process) {// Copyright Joyent, Inc. and other Node contributors. - // - // 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 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. - - // resolves . and .. elements in a path array with directory names there - // must be no slashes, empty elements, or device names (c:\) in the array - // (so also no leading and trailing slashes - it does not distinguish - // relative and absolute paths) - function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; - } - - // Split a filename into [root, dir, basename, ext], unix version - // 'root' is just a slash, or nothing. - var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; - var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); - }; - - // path.resolve([from ...], to) - // posix version - exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; - }; - - // path.normalize(path) - // posix version - exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; - }; - - // posix version - exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; - }; - - // posix version - exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); - }; - - - // path.relative(from, to) - // posix version - exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); - }; - - exports.sep = '/'; - exports.delimiter = ':'; - - exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; - }; - - - exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; - }; - - - exports.extname = function(path) { - return splitPath(path)[3]; - }; - - function filter (xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - return res; - } - - // String.prototype.substr - negative index don't work in IE8 - var substr = 'ab'.substr(-1) === 'b' - ? function (str, start, len) { return str.substr(start, len) } - : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - } - ; - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - - /***/ }, - /* 32 */ - /***/ function(module, exports, __webpack_require__) { - - var pIE = __webpack_require__(87) - , createDesc = __webpack_require__(51) - , toIObject = __webpack_require__(30) - , toPrimitive = __webpack_require__(42) - , has = __webpack_require__(23) - , IE8_DOM_DEFINE = __webpack_require__(218) - , gOPD = Object.getOwnPropertyDescriptor; - - exports.f = __webpack_require__(15) ? gOPD : function getOwnPropertyDescriptor(O, P){ - O = toIObject(O); - P = toPrimitive(P, true); - if(IE8_DOM_DEFINE)try { - return gOPD(O, P); - } catch(e){ /* empty */ } - if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); - }; - - /***/ }, - /* 33 */ - /***/ function(module, exports, __webpack_require__) { - - // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) - var has = __webpack_require__(23) - , toObject = __webpack_require__(22) - , IE_PROTO = __webpack_require__(155)('IE_PROTO') - , ObjectProto = Object.prototype; - - module.exports = Object.getPrototypeOf || function(O){ - O = toObject(O); - if(has(O, IE_PROTO))return O[IE_PROTO]; - if(typeof O.constructor == 'function' && O instanceof O.constructor){ - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; - }; - - /***/ }, - /* 34 */ - /***/ function(module, exports, __webpack_require__) { - - // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 - // - // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! - // - // Originally from narwhal.js (http://narwhaljs.org) - // Copyright (c) 2009 Thomas Robinson <280north.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 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 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. - - // when used in node, this will actually load the util module we depend on - // versus loading the builtin util module as happens otherwise - // this is a bug in node module loading as far as I am concerned - var util = __webpack_require__(11); - - var pSlice = Array.prototype.slice; - var hasOwn = Object.prototype.hasOwnProperty; - - // 1. The assert module provides functions that throw - // AssertionError's when particular conditions are not met. The - // assert module must conform to the following interface. - - var assert = module.exports = ok; - - // 2. The AssertionError is defined in assert. - // new assert.AssertionError({ message: message, - // actual: actual, - // expected: expected }) - - assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } - else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = stackStartFunction.name; - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } - }; - - // assert.AssertionError instanceof Error - util.inherits(assert.AssertionError, Error); - - function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && !isFinite(value)) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; - } - - function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } - } - - function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); - } - - // At present only the three keys mentioned above are used and - // understood by the spec. Implementations or sub modules can pass - // other keys to the AssertionError's constructor - they will be - // ignored. - - // 3. All of the following functions must throw an AssertionError - // when a corresponding condition is not met, with a message that - // may be undefined if not provided. All assertion methods provide - // both the actual and expected values to the assertion error for - // display purposes. - - function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); - } - - // EXTENSION! allows for well behaved errors defined elsewhere. - assert.fail = fail; - - // 4. Pure assertion tests whether a value is truthy, as determined - // by !!guard. - // assert.ok(guard, message_opt); - // This statement is equivalent to assert.equal(true, !!guard, - // message_opt);. To test strictly for the value true, use - // assert.strictEqual(true, guard, message_opt);. - - function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); - } - assert.ok = ok; - - // 5. The equality assertion tests shallow, coercive equality with - // ==. - // assert.equal(actual, expected, message_opt); - - assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); - }; - - // 6. The non-equality assertion tests for whether two objects are not equal - // with != assert.notEqual(actual, expected, message_opt); - - assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } - }; - - // 7. The equivalence assertion tests a deep equality relation. - // assert.deepEqual(actual, expected, message_opt); - - assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } - }; - - function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } - } - - function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; - } - - function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) { - return a === b; - } - var aIsArgs = isArguments(a), - bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - var ka = objectKeys(a), - kb = objectKeys(b), - key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; - } - - // 8. The non-equivalence assertion tests for any deep inequality. - // assert.notDeepEqual(actual, expected, message_opt); - - assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } - }; - - // 9. The strict equality assertion tests strict equality, as determined by ===. - // assert.strictEqual(actual, expected, message_opt); - - assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } - }; - - // 10. The strict non-equality assertion tests for strict inequality, as - // determined by !==. assert.notStrictEqual(actual, expected, message_opt); - - assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } - }; - - function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; - } - - function _throws(shouldThrow, block, expected, message) { - var actual; - - if (util.isString(expected)) { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } - } - - // 11. Expected to throw an error: - // assert.throws(block, Error_opt, message_opt); - - assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); - }; - - // EXTENSION! This is annoying to write outside this module. - assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); - }; - - assert.ifError = function(err) { if (err) {throw err;}}; - - var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; - }; - - - /***/ }, - /* 35 */ - /***/ function(module, exports, __webpack_require__) { - - var basex = __webpack_require__(358) - var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' - var base58 = basex(ALPHABET) - - module.exports = { - encode: base58.encode, - decode: base58.decode - } - - - /***/ }, - /* 36 */ - /***/ function(module, exports) { - - var toString = {}.toString; - - module.exports = function(it){ - return toString.call(it).slice(8, -1); - }; - - /***/ }, - /* 37 */ - /***/ function(module, exports) { - - // 7.2.1 RequireObjectCoercible(argument) - module.exports = function(it){ - if(it == undefined)throw TypeError("Can't call method on " + it); - return it; - }; - - /***/ }, - /* 38 */ - /***/ function(module, exports, __webpack_require__) { - - var fails = __webpack_require__(9); - - module.exports = function(method, arg){ - return !!method && fails(function(){ - arg ? method.call(null, function(){}, 1) : method.call(null); - }); - }; - - /***/ }, - /* 39 */ - /***/ function(module, exports, __webpack_require__) { - - // 0 -> Array#forEach - // 1 -> Array#map - // 2 -> Array#filter - // 3 -> Array#some - // 4 -> Array#every - // 5 -> Array#find - // 6 -> Array#findIndex - var ctx = __webpack_require__(44) - , IObject = __webpack_require__(86) - , toObject = __webpack_require__(22) - , toLength = __webpack_require__(20) - , asc = __webpack_require__(408); - module.exports = function(TYPE, $create){ - var IS_MAP = TYPE == 1 - , IS_FILTER = TYPE == 2 - , IS_SOME = TYPE == 3 - , IS_EVERY = TYPE == 4 - , IS_FIND_INDEX = TYPE == 6 - , NO_HOLES = TYPE == 5 || IS_FIND_INDEX - , create = $create || asc; - return function($this, callbackfn, that){ - var O = toObject($this) - , self = IObject(O) - , f = ctx(callbackfn, that, 3) - , length = toLength(self.length) - , index = 0 - , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined - , val, res; - for(;length > index; index++)if(NO_HOLES || index in self){ - val = self[index]; - res = f(val, index, O); - if(TYPE){ - if(IS_MAP)result[index] = res; // map - else if(res)switch(TYPE){ - case 3: return true; // some - case 5: return val; // find - case 6: return index; // findIndex - case 2: result.push(val); // filter - } else if(IS_EVERY)return false; // every - } - } - return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; - }; - }; - - /***/ }, - /* 40 */ - /***/ function(module, exports) { - - var core = module.exports = {version: '2.4.0'}; - if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef - - /***/ }, - /* 41 */ - /***/ function(module, exports, __webpack_require__) { - - // most Object methods by ES6 should accept primitives - var $export = __webpack_require__(1) - , core = __webpack_require__(40) - , fails = __webpack_require__(9); - module.exports = function(KEY, exec){ - var fn = (core.Object || {})[KEY] || Object[KEY] - , exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); - }; - - /***/ }, - /* 42 */ - /***/ function(module, exports, __webpack_require__) { - - // 7.1.1 ToPrimitive(input [, PreferredType]) - var isObject = __webpack_require__(12); - // instead of the ES6 spec version, we didn't implement @@toPrimitive case - // and the second argument - flag - preferred type is a string - module.exports = function(it, S){ - if(!isObject(it))return it; - var fn, val; - if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; - if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - throw TypeError("Can't convert object to primitive value"); - }; - - /***/ }, - /* 43 */ - /***/ function(module, exports) { - - var toString = {}.toString; - - module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - - /***/ }, - /* 44 */ - /***/ function(module, exports, __webpack_require__) { - - // optional / simple context binding - var aFunction = __webpack_require__(27); - module.exports = function(fn, that, length){ - aFunction(fn); - if(that === undefined)return fn; - switch(length){ - case 1: return function(a){ - return fn.call(that, a); - }; - case 2: return function(a, b){ - return fn.call(that, a, b); - }; - case 3: return function(a, b, c){ - return fn.call(that, a, b, c); - }; - } - return function(/* ...args */){ - return fn.apply(that, arguments); - }; - }; - - /***/ }, - /* 45 */ - /***/ function(module, exports, __webpack_require__) { - - var Map = __webpack_require__(233) - , $export = __webpack_require__(1) - , shared = __webpack_require__(113)('metadata') - , store = shared.store || (shared.store = new (__webpack_require__(236))); - - var getOrCreateMetadataMap = function(target, targetKey, create){ - var targetMetadata = store.get(target); - if(!targetMetadata){ - if(!create)return undefined; - store.set(target, targetMetadata = new Map); - } - var keyMetadata = targetMetadata.get(targetKey); - if(!keyMetadata){ - if(!create)return undefined; - targetMetadata.set(targetKey, keyMetadata = new Map); - } return keyMetadata; - }; - var ordinaryHasOwnMetadata = function(MetadataKey, O, P){ - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? false : metadataMap.has(MetadataKey); - }; - var ordinaryGetOwnMetadata = function(MetadataKey, O, P){ - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); - }; - var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){ - getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); - }; - var ordinaryOwnMetadataKeys = function(target, targetKey){ - var metadataMap = getOrCreateMetadataMap(target, targetKey, false) - , keys = []; - if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); }); - return keys; - }; - var toMetaKey = function(it){ - return it === undefined || typeof it == 'symbol' ? it : String(it); - }; - var exp = function(O){ - $export($export.S, 'Reflect', O); - }; - - module.exports = { - store: store, - map: getOrCreateMetadataMap, - has: ordinaryHasOwnMetadata, - get: ordinaryGetOwnMetadata, - set: ordinaryDefineOwnMetadata, - keys: ordinaryOwnMetadataKeys, - key: toMetaKey, - exp: exp - }; - - /***/ }, - /* 46 */ - /***/ function(module, exports, __webpack_require__) { - - "use strict"; - 'use strict'; - if(__webpack_require__(15)){ - var LIBRARY = __webpack_require__(54) - , global = __webpack_require__(8) - , fails = __webpack_require__(9) - , $export = __webpack_require__(1) - , $typed = __webpack_require__(114) - , $buffer = __webpack_require__(162) - , ctx = __webpack_require__(44) - , anInstance = __webpack_require__(49) - , propertyDesc = __webpack_require__(51) - , hide = __webpack_require__(25) - , redefineAll = __webpack_require__(58) - , isInteger = __webpack_require__(149) - , toInteger = __webpack_require__(52) - , toLength = __webpack_require__(20) - , toIndex = __webpack_require__(60) - , toPrimitive = __webpack_require__(42) - , has = __webpack_require__(23) - , same = __webpack_require__(230) - , classof = __webpack_require__(68) - , isObject = __webpack_require__(12) - , toObject = __webpack_require__(22) - , isArrayIter = __webpack_require__(147) - , create = __webpack_require__(55) - , getPrototypeOf = __webpack_require__(33) - , gOPN = __webpack_require__(56).f - , isIterable = __webpack_require__(415) - , getIterFn = __webpack_require__(164) - , uid = __webpack_require__(61) - , wks = __webpack_require__(13) - , createArrayMethod = __webpack_require__(39) - , createArrayIncludes = __webpack_require__(103) - , speciesConstructor = __webpack_require__(156) - , ArrayIterators = __webpack_require__(165) - , Iterators = __webpack_require__(53) - , $iterDetect = __webpack_require__(109) - , setSpecies = __webpack_require__(59) - , arrayFill = __webpack_require__(140) - , arrayCopyWithin = __webpack_require__(211) - , $DP = __webpack_require__(16) - , $GOPD = __webpack_require__(32) - , dP = $DP.f - , gOPD = $GOPD.f - , RangeError = global.RangeError - , TypeError = global.TypeError - , Uint8Array = global.Uint8Array - , ARRAY_BUFFER = 'ArrayBuffer' - , SHARED_BUFFER = 'Shared' + ARRAY_BUFFER - , BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT' - , PROTOTYPE = 'prototype' - , ArrayProto = Array[PROTOTYPE] - , $ArrayBuffer = $buffer.ArrayBuffer - , $DataView = $buffer.DataView - , arrayForEach = createArrayMethod(0) - , arrayFilter = createArrayMethod(2) - , arraySome = createArrayMethod(3) - , arrayEvery = createArrayMethod(4) - , arrayFind = createArrayMethod(5) - , arrayFindIndex = createArrayMethod(6) - , arrayIncludes = createArrayIncludes(true) - , arrayIndexOf = createArrayIncludes(false) - , arrayValues = ArrayIterators.values - , arrayKeys = ArrayIterators.keys - , arrayEntries = ArrayIterators.entries - , arrayLastIndexOf = ArrayProto.lastIndexOf - , arrayReduce = ArrayProto.reduce - , arrayReduceRight = ArrayProto.reduceRight - , arrayJoin = ArrayProto.join - , arraySort = ArrayProto.sort - , arraySlice = ArrayProto.slice - , arrayToString = ArrayProto.toString - , arrayToLocaleString = ArrayProto.toLocaleString - , ITERATOR = wks('iterator') - , TAG = wks('toStringTag') - , TYPED_CONSTRUCTOR = uid('typed_constructor') - , DEF_CONSTRUCTOR = uid('def_constructor') - , ALL_CONSTRUCTORS = $typed.CONSTR - , TYPED_ARRAY = $typed.TYPED - , VIEW = $typed.VIEW - , WRONG_LENGTH = 'Wrong length!'; - - var $map = createArrayMethod(1, function(O, length){ - return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); - }); - - var LITTLE_ENDIAN = fails(function(){ - return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; - }); - - var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){ - new Uint8Array(1).set({}); - }); - - var strictToLength = function(it, SAME){ - if(it === undefined)throw TypeError(WRONG_LENGTH); - var number = +it - , length = toLength(it); - if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH); - return length; - }; - - var toOffset = function(it, BYTES){ - var offset = toInteger(it); - if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!'); - return offset; - }; - - var validate = function(it){ - if(isObject(it) && TYPED_ARRAY in it)return it; - throw TypeError(it + ' is not a typed array!'); - }; - - var allocate = function(C, length){ - if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){ - throw TypeError('It is not a typed array constructor!'); - } return new C(length); - }; - - var speciesFromList = function(O, list){ - return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); - }; - - var fromList = function(C, list){ - var index = 0 - , length = list.length - , result = allocate(C, length); - while(length > index)result[index] = list[index++]; - return result; - }; - - var addGetter = function(it, key, internal){ - dP(it, key, {get: function(){ return this._d[internal]; }}); - }; - - var $from = function from(source /*, mapfn, thisArg */){ - var O = toObject(source) - , aLen = arguments.length - , mapfn = aLen > 1 ? arguments[1] : undefined - , mapping = mapfn !== undefined - , iterFn = getIterFn(O) - , i, length, values, result, step, iterator; - if(iterFn != undefined && !isArrayIter(iterFn)){ - for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){ - values.push(step.value); - } O = values; - } - if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2); - for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){ - result[i] = mapping ? mapfn(O[i], i) : O[i]; - } - return result; - }; - - var $of = function of(/*...items*/){ - var index = 0 - , length = arguments.length - , result = allocate(this, length); - while(length > index)result[index] = arguments[index++]; - return result; - }; - - // iOS Safari 6.x fails here - var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); }); - - var $toLocaleString = function toLocaleString(){ - return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); - }; - - var proto = { - copyWithin: function copyWithin(target, start /*, end */){ - return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); - }, - every: function every(callbackfn /*, thisArg */){ - return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars - return arrayFill.apply(validate(this), arguments); - }, - filter: function filter(callbackfn /*, thisArg */){ - return speciesFromList(this, arrayFilter(validate(this), callbackfn, - arguments.length > 1 ? arguments[1] : undefined)); - }, - find: function find(predicate /*, thisArg */){ - return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - findIndex: function findIndex(predicate /*, thisArg */){ - return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - forEach: function forEach(callbackfn /*, thisArg */){ - arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - indexOf: function indexOf(searchElement /*, fromIndex */){ - return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - includes: function includes(searchElement /*, fromIndex */){ - return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - join: function join(separator){ // eslint-disable-line no-unused-vars - return arrayJoin.apply(validate(this), arguments); - }, - lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars - return arrayLastIndexOf.apply(validate(this), arguments); - }, - map: function map(mapfn /*, thisArg */){ - return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); - }, - reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars - return arrayReduce.apply(validate(this), arguments); - }, - reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars - return arrayReduceRight.apply(validate(this), arguments); - }, - reverse: function reverse(){ - var that = this - , length = validate(that).length - , middle = Math.floor(length / 2) - , index = 0 - , value; - while(index < middle){ - value = that[index]; - that[index++] = that[--length]; - that[length] = value; - } return that; - }, - some: function some(callbackfn /*, thisArg */){ - return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - sort: function sort(comparefn){ - return arraySort.call(validate(this), comparefn); - }, - subarray: function subarray(begin, end){ - var O = validate(this) - , length = O.length - , $begin = toIndex(begin, length); - return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( - O.buffer, - O.byteOffset + $begin * O.BYTES_PER_ELEMENT, - toLength((end === undefined ? length : toIndex(end, length)) - $begin) - ); - } - }; - - var $slice = function slice(start, end){ - return speciesFromList(this, arraySlice.call(validate(this), start, end)); - }; - - var $set = function set(arrayLike /*, offset */){ - validate(this); - var offset = toOffset(arguments[1], 1) - , length = this.length - , src = toObject(arrayLike) - , len = toLength(src.length) - , index = 0; - if(len + offset > length)throw RangeError(WRONG_LENGTH); - while(index < len)this[offset + index] = src[index++]; - }; - - var $iterators = { - entries: function entries(){ - return arrayEntries.call(validate(this)); - }, - keys: function keys(){ - return arrayKeys.call(validate(this)); - }, - values: function values(){ - return arrayValues.call(validate(this)); - } - }; - - var isTAIndex = function(target, key){ - return isObject(target) - && target[TYPED_ARRAY] - && typeof key != 'symbol' - && key in target - && String(+key) == String(key); - }; - var $getDesc = function getOwnPropertyDescriptor(target, key){ - return isTAIndex(target, key = toPrimitive(key, true)) - ? propertyDesc(2, target[key]) - : gOPD(target, key); - }; - var $setDesc = function defineProperty(target, key, desc){ - if(isTAIndex(target, key = toPrimitive(key, true)) - && isObject(desc) - && has(desc, 'value') - && !has(desc, 'get') - && !has(desc, 'set') - // TODO: add validation descriptor w/o calling accessors - && !desc.configurable - && (!has(desc, 'writable') || desc.writable) - && (!has(desc, 'enumerable') || desc.enumerable) - ){ - target[key] = desc.value; - return target; - } else return dP(target, key, desc); - }; - - if(!ALL_CONSTRUCTORS){ - $GOPD.f = $getDesc; - $DP.f = $setDesc; - } - - $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { - getOwnPropertyDescriptor: $getDesc, - defineProperty: $setDesc - }); - - if(fails(function(){ arrayToString.call({}); })){ - arrayToString = arrayToLocaleString = function toString(){ - return arrayJoin.call(this); - } - } - - var $TypedArrayPrototype$ = redefineAll({}, proto); - redefineAll($TypedArrayPrototype$, $iterators); - hide($TypedArrayPrototype$, ITERATOR, $iterators.values); - redefineAll($TypedArrayPrototype$, { - slice: $slice, - set: $set, - constructor: function(){ /* noop */ }, - toString: arrayToString, - toLocaleString: $toLocaleString - }); - addGetter($TypedArrayPrototype$, 'buffer', 'b'); - addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); - addGetter($TypedArrayPrototype$, 'byteLength', 'l'); - addGetter($TypedArrayPrototype$, 'length', 'e'); - dP($TypedArrayPrototype$, TAG, { - get: function(){ return this[TYPED_ARRAY]; } - }); - - module.exports = function(KEY, BYTES, wrapper, CLAMPED){ - CLAMPED = !!CLAMPED; - var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array' - , ISNT_UINT8 = NAME != 'Uint8Array' - , GETTER = 'get' + KEY - , SETTER = 'set' + KEY - , TypedArray = global[NAME] - , Base = TypedArray || {} - , TAC = TypedArray && getPrototypeOf(TypedArray) - , FORCED = !TypedArray || !$typed.ABV - , O = {} - , TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; - var getter = function(that, index){ - var data = that._d; - return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); - }; - var setter = function(that, index, value){ - var data = that._d; - if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; - data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); - }; - var addElement = function(that, index){ - dP(that, index, { - get: function(){ - return getter(this, index); - }, - set: function(value){ - return setter(this, index, value); - }, - enumerable: true - }); - }; - if(FORCED){ - TypedArray = wrapper(function(that, data, $offset, $length){ - anInstance(that, TypedArray, NAME, '_d'); - var index = 0 - , offset = 0 - , buffer, byteLength, length, klass; - if(!isObject(data)){ - length = strictToLength(data, true) - byteLength = length * BYTES; - buffer = new $ArrayBuffer(byteLength); - } else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ - buffer = data; - offset = toOffset($offset, BYTES); - var $len = data.byteLength; - if($length === undefined){ - if($len % BYTES)throw RangeError(WRONG_LENGTH); - byteLength = $len - offset; - if(byteLength < 0)throw RangeError(WRONG_LENGTH); - } else { - byteLength = toLength($length) * BYTES; - if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH); - } - length = byteLength / BYTES; - } else if(TYPED_ARRAY in data){ - return fromList(TypedArray, data); - } else { - return $from.call(TypedArray, data); - } - hide(that, '_d', { - b: buffer, - o: offset, - l: byteLength, - e: length, - v: new $DataView(buffer) - }); - while(index < length)addElement(that, index++); - }); - TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); - hide(TypedArrayPrototype, 'constructor', TypedArray); - } else if(!$iterDetect(function(iter){ - // V8 works with iterators, but fails in many other cases - // https://code.google.com/p/v8/issues/detail?id=4552 - new TypedArray(null); // eslint-disable-line no-new - new TypedArray(iter); // eslint-disable-line no-new - }, true)){ - TypedArray = wrapper(function(that, data, $offset, $length){ - anInstance(that, TypedArray, NAME); - var klass; - // `ws` module bug, temporarily remove validation length for Uint8Array - // https://github.com/websockets/ws/pull/645 - if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8)); - if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ - return $length !== undefined - ? new Base(data, toOffset($offset, BYTES), $length) - : $offset !== undefined - ? new Base(data, toOffset($offset, BYTES)) - : new Base(data); - } - if(TYPED_ARRAY in data)return fromList(TypedArray, data); - return $from.call(TypedArray, data); - }); - arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){ - if(!(key in TypedArray))hide(TypedArray, key, Base[key]); - }); - TypedArray[PROTOTYPE] = TypedArrayPrototype; - if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray; - } - var $nativeIterator = TypedArrayPrototype[ITERATOR] - , CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined) - , $iterator = $iterators.values; - hide(TypedArray, TYPED_CONSTRUCTOR, true); - hide(TypedArrayPrototype, TYPED_ARRAY, NAME); - hide(TypedArrayPrototype, VIEW, true); - hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); - - if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){ - dP(TypedArrayPrototype, TAG, { - get: function(){ return NAME; } - }); - } - - O[NAME] = TypedArray; - - $export($export.G + $export.W + $export.F * (TypedArray != Base), O); - - $export($export.S, NAME, { - BYTES_PER_ELEMENT: BYTES, - from: $from, - of: $of - }); - - if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); - - $export($export.P, NAME, proto); - - setSpecies(NAME); - - $export($export.P + $export.F * FORCED_SET, NAME, {set: $set}); - - $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); - - $export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString}); - - $export($export.P + $export.F * fails(function(){ - new TypedArray(1).slice(); - }), NAME, {slice: $slice}); - - $export($export.P + $export.F * (fails(function(){ - return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString() - }) || !fails(function(){ - TypedArrayPrototype.toLocaleString.call([1, 2]); - })), NAME, {toLocaleString: $toLocaleString}); - - Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; - if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator); - }; - } else module.exports = function(){ /* empty */ }; - - /***/ }, - /* 47 */ - /***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) { - /** - * Module exports. - */ - - module.exports = deprecate; - - /** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - - function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - } - - /** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - - function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; - } - - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18))) - - /***/ }, - /* 48 */ - /***/ function(module, exports) { - - module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - configurable: false, - get: function() { return module.l; } - }); - Object.defineProperty(module, "id", { - enumerable: true, - configurable: false, - get: function() { return module.i; } - }); - module.webpackPolyfill = 1; - } - return module; - } - - - /***/ }, - /* 49 */ - /***/ function(module, exports) { - - module.exports = function(it, Constructor, name, forbiddenField){ - if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ - throw TypeError(name + ': incorrect invocation!'); - } return it; - }; - - /***/ }, - /* 50 */ - /***/ function(module, exports, __webpack_require__) { - - var META = __webpack_require__(61)('meta') - , isObject = __webpack_require__(12) - , has = __webpack_require__(23) - , setDesc = __webpack_require__(16).f - , id = 0; - var isExtensible = Object.isExtensible || function(){ - return true; - }; - var FREEZE = !__webpack_require__(9)(function(){ - return isExtensible(Object.preventExtensions({})); - }); - var setMeta = function(it){ - setDesc(it, META, {value: { - i: 'O' + ++id, // object ID - w: {} // weak collections IDs - }}); - }; - var fastKey = function(it, create){ - // return primitive with prefix - if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if(!has(it, META)){ - // can't set metadata to uncaught frozen object - if(!isExtensible(it))return 'F'; - // not necessary to add metadata - if(!create)return 'E'; - // add missing metadata - setMeta(it); - // return object ID - } return it[META].i; - }; - var getWeak = function(it, create){ - if(!has(it, META)){ - // can't set metadata to uncaught frozen object - if(!isExtensible(it))return true; - // not necessary to add metadata - if(!create)return false; - // add missing metadata - setMeta(it); - // return hash weak collections IDs - } return it[META].w; - }; - // add metadata on freeze-family methods calling - var onFreeze = function(it){ - if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); - return it; - }; - var meta = module.exports = { - KEY: META, - NEED: false, - fastKey: fastKey, - getWeak: getWeak, - onFreeze: onFreeze - }; - - /***/ }, - /* 51 */ - /***/ function(module, exports) { - - module.exports = function(bitmap, value){ - return { - enumerable : !(bitmap & 1), - configurable: !(bitmap & 2), - writable : !(bitmap & 4), - value : value - }; - }; - - /***/ }, - /* 52 */ - /***/ function(module, exports) { - - // 7.1.4 ToInteger - var ceil = Math.ceil - , floor = Math.floor; - module.exports = function(it){ - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); - }; - - /***/ }, - /* 53 */ - /***/ function(module, exports) { - - module.exports = {}; - - /***/ }, - /* 54 */ - /***/ function(module, exports) { - - module.exports = false; - - /***/ }, - /* 55 */ - /***/ function(module, exports, __webpack_require__) { - - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - var anObject = __webpack_require__(6) - , dPs = __webpack_require__(223) - , enumBugKeys = __webpack_require__(143) - , IE_PROTO = __webpack_require__(155)('IE_PROTO') - , Empty = function(){ /* empty */ } - , PROTOTYPE = 'prototype'; - - // Create object with fake `null` prototype: use iframe Object with cleared prototype - var createDict = function(){ - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(142)('iframe') - , i = enumBugKeys.length - , gt = '>' - , iframeDocument; - iframe.style.display = 'none'; - __webpack_require__(145).appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write('