From e2c7c7dc72e1bcc8e507f75d2ca03a68907f90cf Mon Sep 17 00:00:00 2001 From: Michael Jae-Yoon Chung Date: Wed, 1 May 2019 11:33:53 -0700 Subject: [PATCH] WIP: organize as pkg --- .gitignore | 1 + dist/index.js | 30731 +++++++++++++++++++++++++++++++++-------- examples/visual.html | 1 + index.html | 13 - package-lock.json | 2122 +-- package.json | 22 +- src/index.js | 29 +- 7 files changed, 26213 insertions(+), 6706 deletions(-) delete mode 100644 index.html diff --git a/.gitignore b/.gitignore index 3c3629e..491fc35 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ node_modules +lib diff --git a/dist/index.js b/dist/index.js index cfbfd19..ef76210 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,5948 +1,25129 @@ -(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i= 0 && n[max].type !== 'total'); - var destination = __assign({}, options, { scopeChecker: scopeChecker, - subject: subject, bubbles: !!options.bubbles, useCapture: !!options.useCapture, passive: !!options.passive }); - for (var i = 0; i < relevantSets.length; i++) { - relevantSets[i].add(destination, n.length); - } - return destination; - }; - /** - * Returns a set of all virtual listeners in the scope of the namespace - * Set `exact` to true to treat sibiling isolated scopes as total scopes - */ - EventDelegator.prototype.getVirtualListeners = function (eventType, namespace, exact, max) { - if (exact === void 0) { exact = false; } - var _max = max !== undefined ? max : namespace.length; - if (!exact) { - for (var i = _max - 1; i >= 0; i--) { - if (namespace[i].type === 'total') { - _max = i + 1; - break; - } - _max = i; - } - } - var map = this.virtualListeners.getDefault(namespace, function () { return new Map(); }, _max); - if (!map.has(eventType)) { - map.set(eventType, new PriorityQueue_1.default()); - } - return map.get(eventType); - }; - EventDelegator.prototype.setupDOMListener = function (eventType, passive) { - var _this = this; - if (this.origin) { - var sub = fromEvent_1.fromEvent(this.origin, eventType, false, false, passive).subscribe({ - next: function (event) { return _this.onEvent(eventType, event, passive); }, - error: function () { }, - complete: function () { }, - }); - this.domListeners.set(eventType, { sub: sub, passive: passive }); - } - else { - this.domListenersToAdd.set(eventType, passive); - } - }; - EventDelegator.prototype.setupNonBubblingListener = function (input) { - var _this = this; - var eventType = input[0], elementFinder = input[1], destination = input[2]; - if (!this.origin) { - this.nonBubblingListenersToAdd.add(input); - return; - } - var element = elementFinder.call()[0]; - if (element) { - this.nonBubblingListenersToAdd.delete(input); - var sub = fromEvent_1.fromEvent(element, eventType, false, false, destination.passive).subscribe({ - next: function (ev) { return _this.onEvent(eventType, ev, !!destination.passive, false); }, - error: function () { }, - complete: function () { }, - }); - if (!this.nonBubblingListeners.has(eventType)) { - this.nonBubblingListeners.set(eventType, new Map()); - } - var map = this.nonBubblingListeners.get(eventType); - if (!map) { - return; - } - map.set(element, { sub: sub, destination: destination }); - } - else { - this.nonBubblingListenersToAdd.add(input); - } - }; - EventDelegator.prototype.resetEventListeners = function () { - var iter = this.domListeners.entries(); - var curr = iter.next(); - while (!curr.done) { - var _a = curr.value, type = _a[0], _b = _a[1], sub = _b.sub, passive = _b.passive; - sub.unsubscribe(); - this.setupDOMListener(type, passive); - curr = iter.next(); - } - }; - EventDelegator.prototype.resetNonBubblingListeners = function () { - var _this = this; - var newMap = new Map(); - var insert = utils_1.makeInsert(newMap); - this.nonBubblingListeners.forEach(function (map, type) { - map.forEach(function (value, elm) { - if (!document.body.contains(elm)) { - var sub = value.sub, destination_1 = value.destination; - if (sub) { - sub.unsubscribe(); - } - var elementFinder = new ElementFinder_1.ElementFinder(destination_1.scopeChecker.namespace, _this.isolateModule); - var newElm = elementFinder.call()[0]; - var newSub = fromEvent_1.fromEvent(newElm, type, false, false, destination_1.passive).subscribe({ - next: function (event) { - return _this.onEvent(type, event, !!destination_1.passive, false); - }, - error: function () { }, - complete: function () { }, - }); - insert(type, newElm, { sub: newSub, destination: destination_1 }); - } - else { - insert(type, elm, value); - } - }); - _this.nonBubblingListeners = newMap; - }); - }; - EventDelegator.prototype.putNonBubblingListener = function (eventType, elm, useCapture, passive) { - var map = this.nonBubblingListeners.get(eventType); - if (!map) { - return; - } - var listener = map.get(elm); - if (listener && - listener.destination.passive === passive && - listener.destination.useCapture === useCapture) { - this.virtualNonBubblingListener[0] = listener.destination; - } - }; - EventDelegator.prototype.onEvent = function (eventType, event, passive, bubbles) { - if (bubbles === void 0) { bubbles = true; } - var cycleEvent = this.patchEvent(event); - var rootElement = this.isolateModule.getRootElement(event.target); - if (bubbles) { - var namespace = this.isolateModule.getNamespace(event.target); - if (!namespace) { - return; - } - var listeners = this.getVirtualListeners(eventType, namespace); - this.bubble(eventType, event.target, rootElement, cycleEvent, listeners, namespace, namespace.length - 1, true, passive); - this.bubble(eventType, event.target, rootElement, cycleEvent, listeners, namespace, namespace.length - 1, false, passive); - } - else { - this.putNonBubblingListener(eventType, event.target, true, passive); - this.doBubbleStep(eventType, event.target, rootElement, cycleEvent, this.virtualNonBubblingListener, true, passive); - this.putNonBubblingListener(eventType, event.target, false, passive); - this.doBubbleStep(eventType, event.target, rootElement, cycleEvent, this.virtualNonBubblingListener, false, passive); - event.stopPropagation(); //fix reset event (spec'ed as non-bubbling, but bubbles in reality - } - }; - EventDelegator.prototype.bubble = function (eventType, elm, rootElement, event, listeners, namespace, index, useCapture, passive) { - if (!useCapture && !event.propagationHasBeenStopped) { - this.doBubbleStep(eventType, elm, rootElement, event, listeners, useCapture, passive); - } - var newRoot = rootElement; - var newIndex = index; - if (elm === rootElement) { - if (index >= 0 && namespace[index].type === 'sibling') { - newRoot = this.isolateModule.getElement(namespace, index); - newIndex--; - } - else { - return; - } - } - if (elm.parentNode && newRoot) { - this.bubble(eventType, elm.parentNode, newRoot, event, listeners, namespace, newIndex, useCapture, passive); - } - if (useCapture && !event.propagationHasBeenStopped) { - this.doBubbleStep(eventType, elm, rootElement, event, listeners, useCapture, passive); - } - }; - EventDelegator.prototype.doBubbleStep = function (eventType, elm, rootElement, event, listeners, useCapture, passive) { - if (!rootElement) { - return; - } - this.mutateEventCurrentTarget(event, elm); - listeners.forEach(function (dest) { - if (dest.passive === passive && dest.useCapture === useCapture) { - var sel = utils_1.getSelectors(dest.scopeChecker.namespace); - if (!event.propagationHasBeenStopped && - dest.scopeChecker.isDirectlyInScope(elm) && - ((sel !== '' && elm.matches(sel)) || - (sel === '' && elm === rootElement))) { - fromEvent_1.preventDefaultConditional(event, dest.preventDefault); - dest.subject.shamefullySendNext(event); - } - } - }); - }; - EventDelegator.prototype.patchEvent = function (event) { - var pEvent = event; - pEvent.propagationHasBeenStopped = false; - var oldStopPropagation = pEvent.stopPropagation; - pEvent.stopPropagation = function stopPropagation() { - oldStopPropagation.call(this); - this.propagationHasBeenStopped = true; - }; - return pEvent; - }; - EventDelegator.prototype.mutateEventCurrentTarget = function (event, currentTargetElement) { - try { - Object.defineProperty(event, "currentTarget", { - value: currentTargetElement, - configurable: true, - }); - } - catch (err) { - console.log("please use event.ownerTarget"); - } - event.ownerTarget = currentTargetElement; - }; - return EventDelegator; -}()); -exports.EventDelegator = EventDelegator; - -},{"./ElementFinder":3,"./PriorityQueue":7,"./RemovalSet":8,"./ScopeChecker":9,"./SymbolTree":10,"./fromEvent":12,"./utils":20,"xstream":55}],5:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var utils_1 = require("./utils"); -var SymbolTree_1 = require("./SymbolTree"); -var IsolateModule = /** @class */ (function () { - function IsolateModule() { - this.namespaceTree = new SymbolTree_1.default(function (x) { return x.scope; }); - this.namespaceByElement = new Map(); - this.vnodesBeingRemoved = []; - } - IsolateModule.prototype.setEventDelegator = function (del) { - this.eventDelegator = del; - }; - IsolateModule.prototype.insertElement = function (namespace, el) { - this.namespaceByElement.set(el, namespace); - this.namespaceTree.set(namespace, el); - }; - IsolateModule.prototype.removeElement = function (elm) { - this.namespaceByElement.delete(elm); - var namespace = this.getNamespace(elm); - if (namespace) { - this.namespaceTree.delete(namespace); - } - }; - IsolateModule.prototype.getElement = function (namespace, max) { - return this.namespaceTree.get(namespace, undefined, max); - }; - IsolateModule.prototype.getRootElement = function (elm) { - if (this.namespaceByElement.has(elm)) { - return elm; - } - //TODO: Add quick-lru or similar as additional O(1) cache - var curr = elm; - while (!this.namespaceByElement.has(curr)) { - curr = curr.parentNode; - if (!curr) { - return undefined; - } - else if (curr.tagName === 'HTML') { - throw new Error('No root element found, this should not happen at all'); - } - } - return curr; - }; - IsolateModule.prototype.getNamespace = function (elm) { - var rootElement = this.getRootElement(elm); - if (!rootElement) { - return undefined; - } - return this.namespaceByElement.get(rootElement); - }; - IsolateModule.prototype.createModule = function () { - var self = this; - return { - create: function (emptyVNode, vNode) { - var elm = vNode.elm, _a = vNode.data, data = _a === void 0 ? {} : _a; - var namespace = data.isolate; - if (Array.isArray(namespace)) { - self.insertElement(namespace, elm); - } - }, - update: function (oldVNode, vNode) { - var oldElm = oldVNode.elm, _a = oldVNode.data, oldData = _a === void 0 ? {} : _a; - var elm = vNode.elm, _b = vNode.data, data = _b === void 0 ? {} : _b; - var oldNamespace = oldData.isolate; - var namespace = data.isolate; - if (!utils_1.isEqualNamespace(oldNamespace, namespace)) { - if (Array.isArray(oldNamespace)) { - self.removeElement(oldElm); - } - } - if (Array.isArray(namespace)) { - self.insertElement(namespace, elm); - } - }, - destroy: function (vNode) { - self.vnodesBeingRemoved.push(vNode); - }, - remove: function (vNode, cb) { - self.vnodesBeingRemoved.push(vNode); - cb(); - }, - post: function () { - var vnodesBeingRemoved = self.vnodesBeingRemoved; - for (var i = vnodesBeingRemoved.length - 1; i >= 0; i--) { - var vnode = vnodesBeingRemoved[i]; - var namespace = vnode.data !== undefined - ? vnode.data.isolation - : undefined; - if (namespace !== undefined) { - self.removeElement(namespace); - } - self.eventDelegator.removeElement(vnode.elm, namespace); - } - self.vnodesBeingRemoved = []; - }, - }; - }; - return IsolateModule; -}()); -exports.IsolateModule = IsolateModule; - -},{"./SymbolTree":10,"./utils":20}],6:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var adapt_1 = require("@cycle/run/lib/adapt"); -var DocumentDOMSource_1 = require("./DocumentDOMSource"); -var BodyDOMSource_1 = require("./BodyDOMSource"); -var ElementFinder_1 = require("./ElementFinder"); -var isolate_1 = require("./isolate"); -var MainDOMSource = /** @class */ (function () { - function MainDOMSource(_rootElement$, _sanitation$, _namespace, _isolateModule, _eventDelegator, _name) { - if (_namespace === void 0) { _namespace = []; } - this._rootElement$ = _rootElement$; - this._sanitation$ = _sanitation$; - this._namespace = _namespace; - this._isolateModule = _isolateModule; - this._eventDelegator = _eventDelegator; - this._name = _name; - this.isolateSource = function (source, scope) { - return new MainDOMSource(source._rootElement$, source._sanitation$, source._namespace.concat(isolate_1.getScopeObj(scope)), source._isolateModule, source._eventDelegator, source._name); - }; - this.isolateSink = isolate_1.makeIsolateSink(this._namespace); - } - MainDOMSource.prototype._elements = function () { - if (this._namespace.length === 0) { - return this._rootElement$.map(function (x) { return [x]; }); - } - else { - var elementFinder_1 = new ElementFinder_1.ElementFinder(this._namespace, this._isolateModule); - return this._rootElement$.map(function () { return elementFinder_1.call(); }); - } - }; - MainDOMSource.prototype.elements = function () { - var out = adapt_1.adapt(this._elements().remember()); - out._isCycleSource = this._name; - return out; - }; - MainDOMSource.prototype.element = function () { - var out = adapt_1.adapt(this._elements() - .filter(function (arr) { return arr.length > 0; }) - .map(function (arr) { return arr[0]; }) - .remember()); - out._isCycleSource = this._name; - return out; + +// Public methods list +var methods = [ + 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', + 'any', 'contains' +].concat(tags); + +// Overrided methods list +var overrided = [ + '_peekTag', '_decodeTag', '_use', + '_decodeStr', '_decodeObjid', '_decodeTime', + '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', + + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', + '_encodeNull', '_encodeInt', '_encodeBool' +]; + +function Node(enc, parent) { + var state = {}; + this._baseState = state; + + state.enc = enc; + + state.parent = parent || null; + state.children = null; + + // State + state.tag = null; + state.args = null; + state.reverseArgs = null; + state.choice = null; + state.optional = false; + state.any = false; + state.obj = false; + state.use = null; + state.useDecoder = null; + state.key = null; + state['default'] = null; + state.explicit = null; + state.implicit = null; + state.contains = null; + + // Should create new instance on each method + if (!state.parent) { + state.children = []; + this._wrap(); + } +} +module.exports = Node; + +var stateProps = [ + 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', + 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', + 'implicit', 'contains' +]; + +Node.prototype.clone = function clone() { + var state = this._baseState; + var cstate = {}; + stateProps.forEach(function(prop) { + cstate[prop] = state[prop]; + }); + var res = new this.constructor(cstate.parent); + res._baseState = cstate; + return res; +}; + +Node.prototype._wrap = function wrap() { + var state = this._baseState; + methods.forEach(function(method) { + this[method] = function _wrappedMethod() { + var clone = new this.constructor(this); + state.children.push(clone); + return clone[method].apply(clone, arguments); }; - Object.defineProperty(MainDOMSource.prototype, "namespace", { - get: function () { - return this._namespace; - }, - enumerable: true, - configurable: true + }, this); +}; + +Node.prototype._init = function init(body) { + var state = this._baseState; + + assert(state.parent === null); + body.call(this); + + // Filter children + state.children = state.children.filter(function(child) { + return child._baseState.parent === this; + }, this); + assert.equal(state.children.length, 1, 'Root node can have only one child'); +}; + +Node.prototype._useArgs = function useArgs(args) { + var state = this._baseState; + + // Filter children and args + var children = args.filter(function(arg) { + return arg instanceof this.constructor; + }, this); + args = args.filter(function(arg) { + return !(arg instanceof this.constructor); + }, this); + + if (children.length !== 0) { + assert(state.children === null); + state.children = children; + + // Replace parent to maintain backward link + children.forEach(function(child) { + child._baseState.parent = this; + }, this); + } + if (args.length !== 0) { + assert(state.args === null); + state.args = args; + state.reverseArgs = args.map(function(arg) { + if (typeof arg !== 'object' || arg.constructor !== Object) + return arg; + + var res = {}; + Object.keys(arg).forEach(function(key) { + if (key == (key | 0)) + key |= 0; + var value = arg[key]; + res[value] = key; + }); + return res; }); - MainDOMSource.prototype.select = function (selector) { - if (typeof selector !== 'string') { - throw new Error("DOM driver's select() expects the argument to be a " + - "string as a CSS selector"); - } - if (selector === 'document') { - return new DocumentDOMSource_1.DocumentDOMSource(this._name); - } - if (selector === 'body') { - return new BodyDOMSource_1.BodyDOMSource(this._name); - } - var namespace = selector === ':root' - ? [] - : this._namespace.concat({ type: 'selector', scope: selector.trim() }); - return new MainDOMSource(this._rootElement$, this._sanitation$, namespace, this._isolateModule, this._eventDelegator, this._name); - }; - MainDOMSource.prototype.events = function (eventType, options, bubbles) { - if (options === void 0) { options = {}; } - if (typeof eventType !== "string") { - throw new Error("DOM driver's events() expects argument to be a " + - "string representing the event type to listen for."); - } - var event$ = this._eventDelegator.addEventListener(eventType, this._namespace, options, bubbles); - var out = adapt_1.adapt(event$); - out._isCycleSource = this._name; - return out; - }; - MainDOMSource.prototype.dispose = function () { - this._sanitation$.shamefullySendNext(null); - //this._isolateModule.reset(); - }; - return MainDOMSource; -}()); -exports.MainDOMSource = MainDOMSource; - -},{"./BodyDOMSource":1,"./DocumentDOMSource":2,"./ElementFinder":3,"./isolate":15,"@cycle/run/lib/adapt":21}],7:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var PriorityQueue = /** @class */ (function () { - function PriorityQueue() { - this.arr = []; - this.prios = []; - } - PriorityQueue.prototype.add = function (t, prio) { - for (var i = 0; i < this.arr.length; i++) { - if (this.prios[i] < prio) { - this.arr.splice(i, 0, t); - this.prios.splice(i, 0, prio); - return; - } - } - this.arr.push(t); - this.prios.push(prio); - }; - PriorityQueue.prototype.forEach = function (f) { - for (var i = 0; i < this.arr.length; i++) { - f(this.arr[i], i, this.arr); - } - }; - PriorityQueue.prototype.delete = function (t) { - for (var i = 0; i < this.arr.length; i++) { - if (this.arr[i] === t) { - this.arr.splice(i, 1); - this.prios.splice(i, 1); - return; - } - } - }; - return PriorityQueue; -}()); -exports.default = PriorityQueue; - -},{}],8:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var RemovalSet = /** @class */ (function () { - function RemovalSet() { - this.toDelete = []; - this.toDeleteSize = 0; - this._set = new Set(); - } - RemovalSet.prototype.add = function (t) { - this._set.add(t); - }; - RemovalSet.prototype.forEach = function (f) { - this._set.forEach(f); - this.flush(); - }; - RemovalSet.prototype.delete = function (t) { - if (this.toDelete.length === this.toDeleteSize) { - this.toDelete.push(t); - } - else { - this.toDelete[this.toDeleteSize] = t; - } - this.toDeleteSize++; - }; - RemovalSet.prototype.flush = function () { - for (var i = 0; i < this.toDelete.length; i++) { - if (i < this.toDeleteSize) { - this._set.delete(this.toDelete[i]); - } - this.toDelete[i] = undefined; - } - this.toDeleteSize = 0; - }; - return RemovalSet; -}()); -exports.default = RemovalSet; - -},{}],9:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var utils_1 = require("./utils"); -var ScopeChecker = /** @class */ (function () { - function ScopeChecker(namespace, isolateModule) { - this.namespace = namespace; - this.isolateModule = isolateModule; - this._namespace = namespace.filter(function (n) { return n.type !== 'selector'; }); - } - /** - * Checks whether the given element is *directly* in the scope of this - * scope checker. Being contained *indirectly* through other scopes - * is not valid. This is crucial for implementing parent-child isolation, - * so that the parent selectors don't search inside a child scope. - */ - ScopeChecker.prototype.isDirectlyInScope = function (leaf) { - var namespace = this.isolateModule.getNamespace(leaf); - if (!namespace) { - return false; - } - if (this._namespace.length > namespace.length || - !utils_1.isEqualNamespace(this._namespace, namespace.slice(0, this._namespace.length))) { - return false; - } - for (var i = this._namespace.length; i < namespace.length; i++) { - if (namespace[i].type === 'total') { - return false; - } - } + } +}; + +// +// Overrided methods +// + +overrided.forEach(function(method) { + Node.prototype[method] = function _overrided() { + var state = this._baseState; + throw new Error(method + ' not implemented for encoding: ' + state.enc); + }; +}); + +// +// Public methods +// + +tags.forEach(function(tag) { + Node.prototype[tag] = function _tagMethod() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + assert(state.tag === null); + state.tag = tag; + + this._useArgs(args); + + return this; + }; +}); + +Node.prototype.use = function use(item) { + assert(item); + var state = this._baseState; + + assert(state.use === null); + state.use = item; + + return this; +}; + +Node.prototype.optional = function optional() { + var state = this._baseState; + + state.optional = true; + + return this; +}; + +Node.prototype.def = function def(val) { + var state = this._baseState; + + assert(state['default'] === null); + state['default'] = val; + state.optional = true; + + return this; +}; + +Node.prototype.explicit = function explicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.explicit = num; + + return this; +}; + +Node.prototype.implicit = function implicit(num) { + var state = this._baseState; + + assert(state.explicit === null && state.implicit === null); + state.implicit = num; + + return this; +}; + +Node.prototype.obj = function obj() { + var state = this._baseState; + var args = Array.prototype.slice.call(arguments); + + state.obj = true; + + if (args.length !== 0) + this._useArgs(args); + + return this; +}; + +Node.prototype.key = function key(newKey) { + var state = this._baseState; + + assert(state.key === null); + state.key = newKey; + + return this; +}; + +Node.prototype.any = function any() { + var state = this._baseState; + + state.any = true; + + return this; +}; + +Node.prototype.choice = function choice(obj) { + var state = this._baseState; + + assert(state.choice === null); + state.choice = obj; + this._useArgs(Object.keys(obj).map(function(key) { + return obj[key]; + })); + + return this; +}; + +Node.prototype.contains = function contains(item) { + var state = this._baseState; + + assert(state.use === null); + state.contains = item; + + return this; +}; + +// +// Decoding +// + +Node.prototype._decode = function decode(input, options) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return input.wrapResult(state.children[0]._decode(input, options)); + + var result = state['default']; + var present = true; + + var prevKey = null; + if (state.key !== null) + prevKey = input.enterKey(state.key); + + // Check if tag is there + if (state.optional) { + var tag = null; + if (state.explicit !== null) + tag = state.explicit; + else if (state.implicit !== null) + tag = state.implicit; + else if (state.tag !== null) + tag = state.tag; + + if (tag === null && !state.any) { + // Trial and Error + var save = input.save(); + try { + if (state.choice === null) + this._decodeGeneric(state.tag, input, options); + else + this._decodeChoice(input, options); + present = true; + } catch (e) { + present = false; + } + input.restore(save); + } else { + present = this._peekTag(input, tag, state.any); + + if (input.isError(present)) + return present; + } + } + + // Push object on stack + var prevObj; + if (state.obj && present) + prevObj = input.enterObject(); + + if (present) { + // Unwrap explicit values + if (state.explicit !== null) { + var explicit = this._decodeTag(input, state.explicit); + if (input.isError(explicit)) + return explicit; + input = explicit; + } + + var start = input.offset; + + // Unwrap implicit and normal values + if (state.use === null && state.choice === null) { + if (state.any) + var save = input.save(); + var body = this._decodeTag( + input, + state.implicit !== null ? state.implicit : state.tag, + state.any + ); + if (input.isError(body)) + return body; + + if (state.any) + result = input.raw(save); + else + input = body; + } + + if (options && options.track && state.tag !== null) + options.track(input.path(), start, input.length, 'tagged'); + + if (options && options.track && state.tag !== null) + options.track(input.path(), input.offset, input.length, 'content'); + + // Select proper method for tag + if (state.any) + result = result; + else if (state.choice === null) + result = this._decodeGeneric(state.tag, input, options); + else + result = this._decodeChoice(input, options); + + if (input.isError(result)) + return result; + + // Decode children + if (!state.any && state.choice === null && state.children !== null) { + state.children.forEach(function decodeChildren(child) { + // NOTE: We are ignoring errors here, to let parser continue with other + // parts of encoded data + child._decode(input, options); + }); + } + + // Decode contained/encoded by schema, only in bit or octet strings + if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { + var data = new DecoderBuffer(result); + result = this._getUse(state.contains, input._reporterState.obj) + ._decode(data, options); + } + } + + // Pop object + if (state.obj && present) + result = input.leaveObject(prevObj); + + // Set key + if (state.key !== null && (result !== null || present === true)) + input.leaveKey(prevKey, state.key, result); + else if (prevKey !== null) + input.exitKey(prevKey); + + return result; +}; + +Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { + var state = this._baseState; + + if (tag === 'seq' || tag === 'set') + return null; + if (tag === 'seqof' || tag === 'setof') + return this._decodeList(input, tag, state.args[0], options); + else if (/str$/.test(tag)) + return this._decodeStr(input, tag, options); + else if (tag === 'objid' && state.args) + return this._decodeObjid(input, state.args[0], state.args[1], options); + else if (tag === 'objid') + return this._decodeObjid(input, null, null, options); + else if (tag === 'gentime' || tag === 'utctime') + return this._decodeTime(input, tag, options); + else if (tag === 'null_') + return this._decodeNull(input, options); + else if (tag === 'bool') + return this._decodeBool(input, options); + else if (tag === 'objDesc') + return this._decodeStr(input, tag, options); + else if (tag === 'int' || tag === 'enum') + return this._decodeInt(input, state.args && state.args[0], options); + + if (state.use !== null) { + return this._getUse(state.use, input._reporterState.obj) + ._decode(input, options); + } else { + return input.error('unknown tag: ' + tag); + } +}; + +Node.prototype._getUse = function _getUse(entity, obj) { + + var state = this._baseState; + // Create altered use decoder if implicit is set + state.useDecoder = this._use(entity, obj); + assert(state.useDecoder._baseState.parent === null); + state.useDecoder = state.useDecoder._baseState.children[0]; + if (state.implicit !== state.useDecoder._baseState.implicit) { + state.useDecoder = state.useDecoder.clone(); + state.useDecoder._baseState.implicit = state.implicit; + } + return state.useDecoder; +}; + +Node.prototype._decodeChoice = function decodeChoice(input, options) { + var state = this._baseState; + var result = null; + var match = false; + + Object.keys(state.choice).some(function(key) { + var save = input.save(); + var node = state.choice[key]; + try { + var value = node._decode(input, options); + if (input.isError(value)) + return false; + + result = { type: key, value: value }; + match = true; + } catch (e) { + input.restore(save); + return false; + } + return true; + }, this); + + if (!match) + return input.error('Choice not matched'); + + return result; +}; + +// +// Encoding +// + +Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { + return new EncoderBuffer(data, this.reporter); +}; + +Node.prototype._encode = function encode(data, reporter, parent) { + var state = this._baseState; + if (state['default'] !== null && state['default'] === data) + return; + + var result = this._encodeValue(data, reporter, parent); + if (result === undefined) + return; + + if (this._skipDefault(result, reporter, parent)) + return; + + return result; +}; + +Node.prototype._encodeValue = function encode(data, reporter, parent) { + var state = this._baseState; + + // Decode root node + if (state.parent === null) + return state.children[0]._encode(data, reporter || new Reporter()); + + var result = null; + + // Set reporter to share it with a child class + this.reporter = reporter; + + // Check if data is there + if (state.optional && data === undefined) { + if (state['default'] !== null) + data = state['default'] + else + return; + } + + // Encode children first + var content = null; + var primitive = false; + if (state.any) { + // Anything that was given is translated to buffer + result = this._createEncoderBuffer(data); + } else if (state.choice) { + result = this._encodeChoice(data, reporter); + } else if (state.contains) { + content = this._getUse(state.contains, parent)._encode(data, reporter); + primitive = true; + } else if (state.children) { + content = state.children.map(function(child) { + if (child._baseState.tag === 'null_') + return child._encode(null, reporter, data); + + if (child._baseState.key === null) + return reporter.error('Child should have a key'); + var prevKey = reporter.enterKey(child._baseState.key); + + if (typeof data !== 'object') + return reporter.error('Child expected, but input is not object'); + + var res = child._encode(data[child._baseState.key], reporter, data); + reporter.leaveKey(prevKey); + + return res; + }, this).filter(function(child) { + return child; + }); + content = this._createEncoderBuffer(content); + } else { + if (state.tag === 'seqof' || state.tag === 'setof') { + // TODO(indutny): this should be thrown on DSL level + if (!(state.args && state.args.length === 1)) + return reporter.error('Too many args for : ' + state.tag); + + if (!Array.isArray(data)) + return reporter.error('seqof/setof, but data is not Array'); + + var child = this.clone(); + child._baseState.implicit = null; + content = this._createEncoderBuffer(data.map(function(item) { + var state = this._baseState; + + return this._getUse(state.args[0], data)._encode(item, reporter); + }, child)); + } else if (state.use !== null) { + result = this._getUse(state.use, parent)._encode(data, reporter); + } else { + content = this._encodePrimitive(state.tag, data); + primitive = true; + } + } + + // Encode data itself + var result; + if (!state.any && state.choice === null) { + var tag = state.implicit !== null ? state.implicit : state.tag; + var cls = state.implicit === null ? 'universal' : 'context'; + + if (tag === null) { + if (state.use === null) + reporter.error('Tag could be omitted only for .use()'); + } else { + if (state.use === null) + result = this._encodeComposite(tag, primitive, cls, content); + } + } + + // Wrap in explicit + if (state.explicit !== null) + result = this._encodeComposite(state.explicit, false, 'context', result); + + return result; +}; + +Node.prototype._encodeChoice = function encodeChoice(data, reporter) { + var state = this._baseState; + + var node = state.choice[data.type]; + if (!node) { + assert( + false, + data.type + ' not found in ' + + JSON.stringify(Object.keys(state.choice))); + } + return node._encode(data.value, reporter); +}; + +Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { + var state = this._baseState; + + if (/str$/.test(tag)) + return this._encodeStr(data, tag); + else if (tag === 'objid' && state.args) + return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); + else if (tag === 'objid') + return this._encodeObjid(data, null, null); + else if (tag === 'gentime' || tag === 'utctime') + return this._encodeTime(data, tag); + else if (tag === 'null_') + return this._encodeNull(); + else if (tag === 'int' || tag === 'enum') + return this._encodeInt(data, state.args && state.reverseArgs[0]); + else if (tag === 'bool') + return this._encodeBool(data); + else if (tag === 'objDesc') + return this._encodeStr(data, tag); + else + throw new Error('Unsupported tag: ' + tag); +}; + +Node.prototype._isNumstr = function isNumstr(str) { + return /^[0-9 ]*$/.test(str); +}; + +Node.prototype._isPrintstr = function isPrintstr(str) { + return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); +}; + +},{"../base":4,"minimalistic-assert":106}],6:[function(require,module,exports){ +var inherits = require('inherits'); + +function Reporter(options) { + this._reporterState = { + obj: null, + path: [], + options: options || {}, + errors: [] + }; +} +exports.Reporter = Reporter; + +Reporter.prototype.isError = function isError(obj) { + return obj instanceof ReporterError; +}; + +Reporter.prototype.save = function save() { + var state = this._reporterState; + + return { obj: state.obj, pathLen: state.path.length }; +}; + +Reporter.prototype.restore = function restore(data) { + var state = this._reporterState; + + state.obj = data.obj; + state.path = state.path.slice(0, data.pathLen); +}; + +Reporter.prototype.enterKey = function enterKey(key) { + return this._reporterState.path.push(key); +}; + +Reporter.prototype.exitKey = function exitKey(index) { + var state = this._reporterState; + + state.path = state.path.slice(0, index - 1); +}; + +Reporter.prototype.leaveKey = function leaveKey(index, key, value) { + var state = this._reporterState; + + this.exitKey(index); + if (state.obj !== null) + state.obj[key] = value; +}; + +Reporter.prototype.path = function path() { + return this._reporterState.path.join('/'); +}; + +Reporter.prototype.enterObject = function enterObject() { + var state = this._reporterState; + + var prev = state.obj; + state.obj = {}; + return prev; +}; + +Reporter.prototype.leaveObject = function leaveObject(prev) { + var state = this._reporterState; + + var now = state.obj; + state.obj = prev; + return now; +}; + +Reporter.prototype.error = function error(msg) { + var err; + var state = this._reporterState; + + var inherited = msg instanceof ReporterError; + if (inherited) { + err = msg; + } else { + err = new ReporterError(state.path.map(function(elem) { + return '[' + JSON.stringify(elem) + ']'; + }).join(''), msg.message || msg, msg.stack); + } + + if (!state.options.partial) + throw err; + + if (!inherited) + state.errors.push(err); + + return err; +}; + +Reporter.prototype.wrapResult = function wrapResult(result) { + var state = this._reporterState; + if (!state.options.partial) + return result; + + return { + result: this.isError(result) ? null : result, + errors: state.errors + }; +}; + +function ReporterError(path, msg) { + this.path = path; + this.rethrow(msg); +}; +inherits(ReporterError, Error); + +ReporterError.prototype.rethrow = function rethrow(msg) { + this.message = msg + ' at: ' + (this.path || '(shallow)'); + if (Error.captureStackTrace) + Error.captureStackTrace(this, ReporterError); + + if (!this.stack) { + try { + // IE only adds stack when thrown + throw new Error(this.message); + } catch (e) { + this.stack = e.stack; + } + } + return this; +}; + +},{"inherits":101}],7:[function(require,module,exports){ +var constants = require('../constants'); + +exports.tagClass = { + 0: 'universal', + 1: 'application', + 2: 'context', + 3: 'private' +}; +exports.tagClassByName = constants._reverse(exports.tagClass); + +exports.tag = { + 0x00: 'end', + 0x01: 'bool', + 0x02: 'int', + 0x03: 'bitstr', + 0x04: 'octstr', + 0x05: 'null_', + 0x06: 'objid', + 0x07: 'objDesc', + 0x08: 'external', + 0x09: 'real', + 0x0a: 'enum', + 0x0b: 'embed', + 0x0c: 'utf8str', + 0x0d: 'relativeOid', + 0x10: 'seq', + 0x11: 'set', + 0x12: 'numstr', + 0x13: 'printstr', + 0x14: 't61str', + 0x15: 'videostr', + 0x16: 'ia5str', + 0x17: 'utctime', + 0x18: 'gentime', + 0x19: 'graphstr', + 0x1a: 'iso646str', + 0x1b: 'genstr', + 0x1c: 'unistr', + 0x1d: 'charstr', + 0x1e: 'bmpstr' +}; +exports.tagByName = constants._reverse(exports.tag); + +},{"../constants":8}],8:[function(require,module,exports){ +var constants = exports; + +// Helper +constants._reverse = function reverse(map) { + var res = {}; + + Object.keys(map).forEach(function(key) { + // Convert key to integer if it is stringified + if ((key | 0) == key) + key = key | 0; + + var value = map[key]; + res[value] = key; + }); + + return res; +}; + +constants.der = require('./der'); + +},{"./der":7}],9:[function(require,module,exports){ +var inherits = require('inherits'); + +var asn1 = require('../../asn1'); +var base = asn1.base; +var bignum = asn1.bignum; + +// Import DER constants +var der = asn1.constants.der; + +function DERDecoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DERDecoder; + +DERDecoder.prototype.decode = function decode(data, options) { + if (!(data instanceof base.DecoderBuffer)) + data = new base.DecoderBuffer(data, options); + + return this.tree._decode(data, options); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { + if (buffer.isEmpty()) + return false; + + var state = buffer.save(); + var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + buffer.restore(state); + + return decodedTag.tag === tag || decodedTag.tagStr === tag || + (decodedTag.tagStr + 'of') === tag || any; +}; + +DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { + var decodedTag = derDecodeTag(buffer, + 'Failed to decode tag of "' + tag + '"'); + if (buffer.isError(decodedTag)) + return decodedTag; + + var len = derDecodeLen(buffer, + decodedTag.primitive, + 'Failed to get length of "' + tag + '"'); + + // Failure + if (buffer.isError(len)) + return len; + + if (!any && + decodedTag.tag !== tag && + decodedTag.tagStr !== tag && + decodedTag.tagStr + 'of' !== tag) { + return buffer.error('Failed to match tag: "' + tag + '"'); + } + + if (decodedTag.primitive || len !== null) + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); + + // Indefinite length... find END tag + var state = buffer.save(); + var res = this._skipUntilEnd( + buffer, + 'Failed to skip indefinite length body: "' + this.tag + '"'); + if (buffer.isError(res)) + return res; + + len = buffer.offset - state.offset; + buffer.restore(state); + return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); +}; + +DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { + while (true) { + var tag = derDecodeTag(buffer, fail); + if (buffer.isError(tag)) + return tag; + var len = derDecodeLen(buffer, tag.primitive, fail); + if (buffer.isError(len)) + return len; + + var res; + if (tag.primitive || len !== null) + res = buffer.skip(len) + else + res = this._skipUntilEnd(buffer, fail); + + // Failure + if (buffer.isError(res)) + return res; + + if (tag.tagStr === 'end') + break; + } +}; + +DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, + options) { + var result = []; + while (!buffer.isEmpty()) { + var possibleEnd = this._peekTag(buffer, 'end'); + if (buffer.isError(possibleEnd)) + return possibleEnd; + + var res = decoder.decode(buffer, 'der', options); + if (buffer.isError(res) && possibleEnd) + break; + result.push(res); + } + return result; +}; + +DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { + if (tag === 'bitstr') { + var unused = buffer.readUInt8(); + if (buffer.isError(unused)) + return unused; + return { unused: unused, data: buffer.raw() }; + } else if (tag === 'bmpstr') { + var raw = buffer.raw(); + if (raw.length % 2 === 1) + return buffer.error('Decoding of string type: bmpstr length mismatch'); + + var str = ''; + for (var i = 0; i < raw.length / 2; i++) { + str += String.fromCharCode(raw.readUInt16BE(i * 2)); + } + return str; + } else if (tag === 'numstr') { + var numstr = buffer.raw().toString('ascii'); + if (!this._isNumstr(numstr)) { + return buffer.error('Decoding of string type: ' + + 'numstr unsupported characters'); + } + return numstr; + } else if (tag === 'octstr') { + return buffer.raw(); + } else if (tag === 'objDesc') { + return buffer.raw(); + } else if (tag === 'printstr') { + var printstr = buffer.raw().toString('ascii'); + if (!this._isPrintstr(printstr)) { + return buffer.error('Decoding of string type: ' + + 'printstr unsupported characters'); + } + return printstr; + } else if (/str$/.test(tag)) { + return buffer.raw().toString(); + } else { + return buffer.error('Decoding of string type: ' + tag + ' unsupported'); + } +}; + +DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { + var result; + var identifiers = []; + var ident = 0; + while (!buffer.isEmpty()) { + var subident = buffer.readUInt8(); + ident <<= 7; + ident |= subident & 0x7f; + if ((subident & 0x80) === 0) { + identifiers.push(ident); + ident = 0; + } + } + if (subident & 0x80) + identifiers.push(ident); + + var first = (identifiers[0] / 40) | 0; + var second = identifiers[0] % 40; + + if (relative) + result = identifiers; + else + result = [first, second].concat(identifiers.slice(1)); + + if (values) { + var tmp = values[result.join(' ')]; + if (tmp === undefined) + tmp = values[result.join('.')]; + if (tmp !== undefined) + result = tmp; + } + + return result; +}; + +DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { + var str = buffer.raw().toString(); + if (tag === 'gentime') { + var year = str.slice(0, 4) | 0; + var mon = str.slice(4, 6) | 0; + var day = str.slice(6, 8) | 0; + var hour = str.slice(8, 10) | 0; + var min = str.slice(10, 12) | 0; + var sec = str.slice(12, 14) | 0; + } else if (tag === 'utctime') { + var year = str.slice(0, 2) | 0; + var mon = str.slice(2, 4) | 0; + var day = str.slice(4, 6) | 0; + var hour = str.slice(6, 8) | 0; + var min = str.slice(8, 10) | 0; + var sec = str.slice(10, 12) | 0; + if (year < 70) + year = 2000 + year; + else + year = 1900 + year; + } else { + return buffer.error('Decoding ' + tag + ' time is not supported yet'); + } + + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); +}; + +DERNode.prototype._decodeNull = function decodeNull(buffer) { + return null; +}; + +DERNode.prototype._decodeBool = function decodeBool(buffer) { + var res = buffer.readUInt8(); + if (buffer.isError(res)) + return res; + else + return res !== 0; +}; + +DERNode.prototype._decodeInt = function decodeInt(buffer, values) { + // Bigint, return as it is (assume big endian) + var raw = buffer.raw(); + var res = new bignum(raw); + + if (values) + res = values[res.toString(10)] || res; + + return res; +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getDecoder('der').tree; +}; + +// Utility methods + +function derDecodeTag(buf, fail) { + var tag = buf.readUInt8(fail); + if (buf.isError(tag)) + return tag; + + var cls = der.tagClass[tag >> 6]; + var primitive = (tag & 0x20) === 0; + + // Multi-octet tag - load + if ((tag & 0x1f) === 0x1f) { + var oct = tag; + tag = 0; + while ((oct & 0x80) === 0x80) { + oct = buf.readUInt8(fail); + if (buf.isError(oct)) + return oct; + + tag <<= 7; + tag |= oct & 0x7f; + } + } else { + tag &= 0x1f; + } + var tagStr = der.tag[tag]; + + return { + cls: cls, + primitive: primitive, + tag: tag, + tagStr: tagStr + }; +} + +function derDecodeLen(buf, primitive, fail) { + var len = buf.readUInt8(fail); + if (buf.isError(len)) + return len; + + // Indefinite form + if (!primitive && len === 0x80) + return null; + + // Definite form + if ((len & 0x80) === 0) { + // Short form + return len; + } + + // Long form + var num = len & 0x7f; + if (num > 4) + return buf.error('length octect is too long'); + + len = 0; + for (var i = 0; i < num; i++) { + len <<= 8; + var j = buf.readUInt8(fail); + if (buf.isError(j)) + return j; + len |= j; + } + + return len; +} + +},{"../../asn1":1,"inherits":101}],10:[function(require,module,exports){ +var decoders = exports; + +decoders.der = require('./der'); +decoders.pem = require('./pem'); + +},{"./der":9,"./pem":11}],11:[function(require,module,exports){ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; + +var DERDecoder = require('./der'); + +function PEMDecoder(entity) { + DERDecoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMDecoder, DERDecoder); +module.exports = PEMDecoder; + +PEMDecoder.prototype.decode = function decode(data, options) { + var lines = data.toString().split(/[\r\n]+/g); + + var label = options.label.toUpperCase(); + + var re = /^-----(BEGIN|END) ([^-]+)-----$/; + var start = -1; + var end = -1; + for (var i = 0; i < lines.length; i++) { + var match = lines[i].match(re); + if (match === null) + continue; + + if (match[2] !== label) + continue; + + if (start === -1) { + if (match[1] !== 'BEGIN') + break; + start = i; + } else { + if (match[1] !== 'END') + break; + end = i; + break; + } + } + if (start === -1 || end === -1) + throw new Error('PEM section not found for: ' + label); + + var base64 = lines.slice(start + 1, end).join(''); + // Remove excessive symbols + base64.replace(/[^a-z0-9\+\/=]+/gi, ''); + + var input = new Buffer(base64, 'base64'); + return DERDecoder.prototype.decode.call(this, input, options); +}; + +},{"./der":9,"buffer":47,"inherits":101}],12:[function(require,module,exports){ +var inherits = require('inherits'); +var Buffer = require('buffer').Buffer; + +var asn1 = require('../../asn1'); +var base = asn1.base; + +// Import DER constants +var der = asn1.constants.der; + +function DEREncoder(entity) { + this.enc = 'der'; + this.name = entity.name; + this.entity = entity; + + // Construct base tree + this.tree = new DERNode(); + this.tree._init(entity.body); +}; +module.exports = DEREncoder; + +DEREncoder.prototype.encode = function encode(data, reporter) { + return this.tree._encode(data, reporter).join(); +}; + +// Tree methods + +function DERNode(parent) { + base.Node.call(this, 'der', parent); +} +inherits(DERNode, base.Node); + +DERNode.prototype._encodeComposite = function encodeComposite(tag, + primitive, + cls, + content) { + var encodedTag = encodeTag(tag, primitive, cls, this.reporter); + + // Short form + if (content.length < 0x80) { + var header = new Buffer(2); + header[0] = encodedTag; + header[1] = content.length; + return this._createEncoderBuffer([ header, content ]); + } + + // Long form + // Count octets required to store length + var lenOctets = 1; + for (var i = content.length; i >= 0x100; i >>= 8) + lenOctets++; + + var header = new Buffer(1 + 1 + lenOctets); + header[0] = encodedTag; + header[1] = 0x80 | lenOctets; + + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) + header[i] = j & 0xff; + + return this._createEncoderBuffer([ header, content ]); +}; + +DERNode.prototype._encodeStr = function encodeStr(str, tag) { + if (tag === 'bitstr') { + return this._createEncoderBuffer([ str.unused | 0, str.data ]); + } else if (tag === 'bmpstr') { + var buf = new Buffer(str.length * 2); + for (var i = 0; i < str.length; i++) { + buf.writeUInt16BE(str.charCodeAt(i), i * 2); + } + return this._createEncoderBuffer(buf); + } else if (tag === 'numstr') { + if (!this._isNumstr(str)) { + return this.reporter.error('Encoding of string type: numstr supports ' + + 'only digits and space'); + } + return this._createEncoderBuffer(str); + } else if (tag === 'printstr') { + if (!this._isPrintstr(str)) { + return this.reporter.error('Encoding of string type: printstr supports ' + + 'only latin upper and lower case letters, ' + + 'digits, space, apostrophe, left and rigth ' + + 'parenthesis, plus sign, comma, hyphen, ' + + 'dot, slash, colon, equal sign, ' + + 'question mark'); + } + return this._createEncoderBuffer(str); + } else if (/str$/.test(tag)) { + return this._createEncoderBuffer(str); + } else if (tag === 'objDesc') { + return this._createEncoderBuffer(str); + } else { + return this.reporter.error('Encoding of string type: ' + tag + + ' unsupported'); + } +}; + +DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { + if (typeof id === 'string') { + if (!values) + return this.reporter.error('string objid given, but no values map found'); + if (!values.hasOwnProperty(id)) + return this.reporter.error('objid not found in values map'); + id = values[id].split(/[\s\.]+/g); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } else if (Array.isArray(id)) { + id = id.slice(); + for (var i = 0; i < id.length; i++) + id[i] |= 0; + } + + if (!Array.isArray(id)) { + return this.reporter.error('objid() should be either array or string, ' + + 'got: ' + JSON.stringify(id)); + } + + if (!relative) { + if (id[1] >= 40) + return this.reporter.error('Second objid identifier OOB'); + id.splice(0, 2, id[0] * 40 + id[1]); + } + + // Count number of octets + var size = 0; + for (var i = 0; i < id.length; i++) { + var ident = id[i]; + for (size++; ident >= 0x80; ident >>= 7) + size++; + } + + var objid = new Buffer(size); + var offset = objid.length - 1; + for (var i = id.length - 1; i >= 0; i--) { + var ident = id[i]; + objid[offset--] = ident & 0x7f; + while ((ident >>= 7) > 0) + objid[offset--] = 0x80 | (ident & 0x7f); + } + + return this._createEncoderBuffer(objid); +}; + +function two(num) { + if (num < 10) + return '0' + num; + else + return num; +} + +DERNode.prototype._encodeTime = function encodeTime(time, tag) { + var str; + var date = new Date(time); + + if (tag === 'gentime') { + str = [ + two(date.getFullYear()), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else if (tag === 'utctime') { + str = [ + two(date.getFullYear() % 100), + two(date.getUTCMonth() + 1), + two(date.getUTCDate()), + two(date.getUTCHours()), + two(date.getUTCMinutes()), + two(date.getUTCSeconds()), + 'Z' + ].join(''); + } else { + this.reporter.error('Encoding ' + tag + ' time is not supported yet'); + } + + return this._encodeStr(str, 'octstr'); +}; + +DERNode.prototype._encodeNull = function encodeNull() { + return this._createEncoderBuffer(''); +}; + +DERNode.prototype._encodeInt = function encodeInt(num, values) { + if (typeof num === 'string') { + if (!values) + return this.reporter.error('String int or enum given, but no values map'); + if (!values.hasOwnProperty(num)) { + return this.reporter.error('Values map doesn\'t contain: ' + + JSON.stringify(num)); + } + num = values[num]; + } + + // Bignum, assume big endian + if (typeof num !== 'number' && !Buffer.isBuffer(num)) { + var numArray = num.toArray(); + if (!num.sign && numArray[0] & 0x80) { + numArray.unshift(0); + } + num = new Buffer(numArray); + } + + if (Buffer.isBuffer(num)) { + var size = num.length; + if (num.length === 0) + size++; + + var out = new Buffer(size); + num.copy(out); + if (num.length === 0) + out[0] = 0 + return this._createEncoderBuffer(out); + } + + if (num < 0x80) + return this._createEncoderBuffer(num); + + if (num < 0x100) + return this._createEncoderBuffer([0, num]); + + var size = 1; + for (var i = num; i >= 0x100; i >>= 8) + size++; + + var out = new Array(size); + for (var i = out.length - 1; i >= 0; i--) { + out[i] = num & 0xff; + num >>= 8; + } + if(out[0] & 0x80) { + out.unshift(0); + } + + return this._createEncoderBuffer(new Buffer(out)); +}; + +DERNode.prototype._encodeBool = function encodeBool(value) { + return this._createEncoderBuffer(value ? 0xff : 0); +}; + +DERNode.prototype._use = function use(entity, obj) { + if (typeof entity === 'function') + entity = entity(obj); + return entity._getEncoder('der').tree; +}; + +DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { + var state = this._baseState; + var i; + if (state['default'] === null) + return false; + + var data = dataBuffer.join(); + if (state.defaultBuffer === undefined) + state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); + + if (data.length !== state.defaultBuffer.length) + return false; + + for (i=0; i < data.length; i++) + if (data[i] !== state.defaultBuffer[i]) + return false; + + return true; +}; + +// Utility methods + +function encodeTag(tag, primitive, cls, reporter) { + var res; + + if (tag === 'seqof') + tag = 'seq'; + else if (tag === 'setof') + tag = 'set'; + + if (der.tagByName.hasOwnProperty(tag)) + res = der.tagByName[tag]; + else if (typeof tag === 'number' && (tag | 0) === tag) + res = tag; + else + return reporter.error('Unknown tag: ' + tag); + + if (res >= 0x1f) + return reporter.error('Multi-octet tag encoding unsupported'); + + if (!primitive) + res |= 0x20; + + res |= (der.tagClassByName[cls || 'universal'] << 6); + + return res; +} + +},{"../../asn1":1,"buffer":47,"inherits":101}],13:[function(require,module,exports){ +var encoders = exports; + +encoders.der = require('./der'); +encoders.pem = require('./pem'); + +},{"./der":12,"./pem":14}],14:[function(require,module,exports){ +var inherits = require('inherits'); + +var DEREncoder = require('./der'); + +function PEMEncoder(entity) { + DEREncoder.call(this, entity); + this.enc = 'pem'; +}; +inherits(PEMEncoder, DEREncoder); +module.exports = PEMEncoder; + +PEMEncoder.prototype.encode = function encode(data, options) { + var buf = DEREncoder.prototype.encode.call(this, data); + + var p = buf.toString('base64'); + var out = [ '-----BEGIN ' + options.label + '-----' ]; + for (var i = 0; i < p.length; i += 64) + out.push(p.slice(i, i + 64)); + out.push('-----END ' + options.label + '-----'); + return out.join('\n'); +}; + +},{"./der":12,"inherits":101}],15:[function(require,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + for (var i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + +},{}],16:[function(require,module,exports){ +(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 = require('buffer').Buffer; + } catch (e) { + } + + BN.isBN = function isBN (num) { + if (num instanceof BN) { + return true; + } + + return num !== null && typeof num === 'object' && + num.constructor.wordSize === BN.wordSize && 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 = (mid + Math.imul(ah0, bl0)) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; + w0 &= 0x3ffffff; + /* k = 1 */ + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = (mid + Math.imul(ah1, bl0)) | 0; + hi = Math.imul(ah1, bh0); + lo = (lo + Math.imul(al0, bl1)) | 0; + mid = (mid + Math.imul(al0, bh1)) | 0; + mid = (mid + Math.imul(ah0, bl1)) | 0; + hi = (hi + Math.imul(ah0, bh1)) | 0; + var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; + w1 &= 0x3ffffff; + /* k = 2 */ + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = (mid + Math.imul(ah2, bl0)) | 0; + hi = Math.imul(ah2, bh0); + lo = (lo + Math.imul(al1, bl1)) | 0; + mid = (mid + Math.imul(al1, bh1)) | 0; + mid = (mid + Math.imul(ah1, bl1)) | 0; + hi = (hi + Math.imul(ah1, bh1)) | 0; + lo = (lo + Math.imul(al0, bl2)) | 0; + mid = (mid + Math.imul(al0, bh2)) | 0; + mid = (mid + Math.imul(ah0, bl2)) | 0; + hi = (hi + Math.imul(ah0, bh2)) | 0; + var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; + w2 &= 0x3ffffff; + /* k = 3 */ + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = (mid + Math.imul(ah3, bl0)) | 0; + hi = Math.imul(ah3, bh0); + lo = (lo + Math.imul(al2, bl1)) | 0; + mid = (mid + Math.imul(al2, bh1)) | 0; + mid = (mid + Math.imul(ah2, bl1)) | 0; + hi = (hi + Math.imul(ah2, bh1)) | 0; + lo = (lo + Math.imul(al1, bl2)) | 0; + mid = (mid + Math.imul(al1, bh2)) | 0; + mid = (mid + Math.imul(ah1, bl2)) | 0; + hi = (hi + Math.imul(ah1, bh2)) | 0; + lo = (lo + Math.imul(al0, bl3)) | 0; + mid = (mid + Math.imul(al0, bh3)) | 0; + mid = (mid + Math.imul(ah0, bl3)) | 0; + hi = (hi + Math.imul(ah0, bh3)) | 0; + var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; + w3 &= 0x3ffffff; + /* k = 4 */ + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = (mid + Math.imul(ah4, bl0)) | 0; + hi = Math.imul(ah4, bh0); + lo = (lo + Math.imul(al3, bl1)) | 0; + mid = (mid + Math.imul(al3, bh1)) | 0; + mid = (mid + Math.imul(ah3, bl1)) | 0; + hi = (hi + Math.imul(ah3, bh1)) | 0; + lo = (lo + Math.imul(al2, bl2)) | 0; + mid = (mid + Math.imul(al2, bh2)) | 0; + mid = (mid + Math.imul(ah2, bl2)) | 0; + hi = (hi + Math.imul(ah2, bh2)) | 0; + lo = (lo + Math.imul(al1, bl3)) | 0; + mid = (mid + Math.imul(al1, bh3)) | 0; + mid = (mid + Math.imul(ah1, bl3)) | 0; + hi = (hi + Math.imul(ah1, bh3)) | 0; + lo = (lo + Math.imul(al0, bl4)) | 0; + mid = (mid + Math.imul(al0, bh4)) | 0; + mid = (mid + Math.imul(ah0, bl4)) | 0; + hi = (hi + Math.imul(ah0, bh4)) | 0; + var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; + w4 &= 0x3ffffff; + /* k = 5 */ + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = (mid + Math.imul(ah5, bl0)) | 0; + hi = Math.imul(ah5, bh0); + lo = (lo + Math.imul(al4, bl1)) | 0; + mid = (mid + Math.imul(al4, bh1)) | 0; + mid = (mid + Math.imul(ah4, bl1)) | 0; + hi = (hi + Math.imul(ah4, bh1)) | 0; + lo = (lo + Math.imul(al3, bl2)) | 0; + mid = (mid + Math.imul(al3, bh2)) | 0; + mid = (mid + Math.imul(ah3, bl2)) | 0; + hi = (hi + Math.imul(ah3, bh2)) | 0; + lo = (lo + Math.imul(al2, bl3)) | 0; + mid = (mid + Math.imul(al2, bh3)) | 0; + mid = (mid + Math.imul(ah2, bl3)) | 0; + hi = (hi + Math.imul(ah2, bh3)) | 0; + lo = (lo + Math.imul(al1, bl4)) | 0; + mid = (mid + Math.imul(al1, bh4)) | 0; + mid = (mid + Math.imul(ah1, bl4)) | 0; + hi = (hi + Math.imul(ah1, bh4)) | 0; + lo = (lo + Math.imul(al0, bl5)) | 0; + mid = (mid + Math.imul(al0, bh5)) | 0; + mid = (mid + Math.imul(ah0, bl5)) | 0; + hi = (hi + Math.imul(ah0, bh5)) | 0; + var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; + w5 &= 0x3ffffff; + /* k = 6 */ + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = (mid + Math.imul(ah6, bl0)) | 0; + hi = Math.imul(ah6, bh0); + lo = (lo + Math.imul(al5, bl1)) | 0; + mid = (mid + Math.imul(al5, bh1)) | 0; + mid = (mid + Math.imul(ah5, bl1)) | 0; + hi = (hi + Math.imul(ah5, bh1)) | 0; + lo = (lo + Math.imul(al4, bl2)) | 0; + mid = (mid + Math.imul(al4, bh2)) | 0; + mid = (mid + Math.imul(ah4, bl2)) | 0; + hi = (hi + Math.imul(ah4, bh2)) | 0; + lo = (lo + Math.imul(al3, bl3)) | 0; + mid = (mid + Math.imul(al3, bh3)) | 0; + mid = (mid + Math.imul(ah3, bl3)) | 0; + hi = (hi + Math.imul(ah3, bh3)) | 0; + lo = (lo + Math.imul(al2, bl4)) | 0; + mid = (mid + Math.imul(al2, bh4)) | 0; + mid = (mid + Math.imul(ah2, bl4)) | 0; + hi = (hi + Math.imul(ah2, bh4)) | 0; + lo = (lo + Math.imul(al1, bl5)) | 0; + mid = (mid + Math.imul(al1, bh5)) | 0; + mid = (mid + Math.imul(ah1, bl5)) | 0; + hi = (hi + Math.imul(ah1, bh5)) | 0; + lo = (lo + Math.imul(al0, bl6)) | 0; + mid = (mid + Math.imul(al0, bh6)) | 0; + mid = (mid + Math.imul(ah0, bl6)) | 0; + hi = (hi + Math.imul(ah0, bh6)) | 0; + var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; + w6 &= 0x3ffffff; + /* k = 7 */ + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = (mid + Math.imul(ah7, bl0)) | 0; + hi = Math.imul(ah7, bh0); + lo = (lo + Math.imul(al6, bl1)) | 0; + mid = (mid + Math.imul(al6, bh1)) | 0; + mid = (mid + Math.imul(ah6, bl1)) | 0; + hi = (hi + Math.imul(ah6, bh1)) | 0; + lo = (lo + Math.imul(al5, bl2)) | 0; + mid = (mid + Math.imul(al5, bh2)) | 0; + mid = (mid + Math.imul(ah5, bl2)) | 0; + hi = (hi + Math.imul(ah5, bh2)) | 0; + lo = (lo + Math.imul(al4, bl3)) | 0; + mid = (mid + Math.imul(al4, bh3)) | 0; + mid = (mid + Math.imul(ah4, bl3)) | 0; + hi = (hi + Math.imul(ah4, bh3)) | 0; + lo = (lo + Math.imul(al3, bl4)) | 0; + mid = (mid + Math.imul(al3, bh4)) | 0; + mid = (mid + Math.imul(ah3, bl4)) | 0; + hi = (hi + Math.imul(ah3, bh4)) | 0; + lo = (lo + Math.imul(al2, bl5)) | 0; + mid = (mid + Math.imul(al2, bh5)) | 0; + mid = (mid + Math.imul(ah2, bl5)) | 0; + hi = (hi + Math.imul(ah2, bh5)) | 0; + lo = (lo + Math.imul(al1, bl6)) | 0; + mid = (mid + Math.imul(al1, bh6)) | 0; + mid = (mid + Math.imul(ah1, bl6)) | 0; + hi = (hi + Math.imul(ah1, bh6)) | 0; + lo = (lo + Math.imul(al0, bl7)) | 0; + mid = (mid + Math.imul(al0, bh7)) | 0; + mid = (mid + Math.imul(ah0, bl7)) | 0; + hi = (hi + Math.imul(ah0, bh7)) | 0; + var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; + w7 &= 0x3ffffff; + /* k = 8 */ + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = (mid + Math.imul(ah8, bl0)) | 0; + hi = Math.imul(ah8, bh0); + lo = (lo + Math.imul(al7, bl1)) | 0; + mid = (mid + Math.imul(al7, bh1)) | 0; + mid = (mid + Math.imul(ah7, bl1)) | 0; + hi = (hi + Math.imul(ah7, bh1)) | 0; + lo = (lo + Math.imul(al6, bl2)) | 0; + mid = (mid + Math.imul(al6, bh2)) | 0; + mid = (mid + Math.imul(ah6, bl2)) | 0; + hi = (hi + Math.imul(ah6, bh2)) | 0; + lo = (lo + Math.imul(al5, bl3)) | 0; + mid = (mid + Math.imul(al5, bh3)) | 0; + mid = (mid + Math.imul(ah5, bl3)) | 0; + hi = (hi + Math.imul(ah5, bh3)) | 0; + lo = (lo + Math.imul(al4, bl4)) | 0; + mid = (mid + Math.imul(al4, bh4)) | 0; + mid = (mid + Math.imul(ah4, bl4)) | 0; + hi = (hi + Math.imul(ah4, bh4)) | 0; + lo = (lo + Math.imul(al3, bl5)) | 0; + mid = (mid + Math.imul(al3, bh5)) | 0; + mid = (mid + Math.imul(ah3, bl5)) | 0; + hi = (hi + Math.imul(ah3, bh5)) | 0; + lo = (lo + Math.imul(al2, bl6)) | 0; + mid = (mid + Math.imul(al2, bh6)) | 0; + mid = (mid + Math.imul(ah2, bl6)) | 0; + hi = (hi + Math.imul(ah2, bh6)) | 0; + lo = (lo + Math.imul(al1, bl7)) | 0; + mid = (mid + Math.imul(al1, bh7)) | 0; + mid = (mid + Math.imul(ah1, bl7)) | 0; + hi = (hi + Math.imul(ah1, bh7)) | 0; + lo = (lo + Math.imul(al0, bl8)) | 0; + mid = (mid + Math.imul(al0, bh8)) | 0; + mid = (mid + Math.imul(ah0, bl8)) | 0; + hi = (hi + Math.imul(ah0, bh8)) | 0; + var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; + w8 &= 0x3ffffff; + /* k = 9 */ + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = (mid + Math.imul(ah9, bl0)) | 0; + hi = Math.imul(ah9, bh0); + lo = (lo + Math.imul(al8, bl1)) | 0; + mid = (mid + Math.imul(al8, bh1)) | 0; + mid = (mid + Math.imul(ah8, bl1)) | 0; + hi = (hi + Math.imul(ah8, bh1)) | 0; + lo = (lo + Math.imul(al7, bl2)) | 0; + mid = (mid + Math.imul(al7, bh2)) | 0; + mid = (mid + Math.imul(ah7, bl2)) | 0; + hi = (hi + Math.imul(ah7, bh2)) | 0; + lo = (lo + Math.imul(al6, bl3)) | 0; + mid = (mid + Math.imul(al6, bh3)) | 0; + mid = (mid + Math.imul(ah6, bl3)) | 0; + hi = (hi + Math.imul(ah6, bh3)) | 0; + lo = (lo + Math.imul(al5, bl4)) | 0; + mid = (mid + Math.imul(al5, bh4)) | 0; + mid = (mid + Math.imul(ah5, bl4)) | 0; + hi = (hi + Math.imul(ah5, bh4)) | 0; + lo = (lo + Math.imul(al4, bl5)) | 0; + mid = (mid + Math.imul(al4, bh5)) | 0; + mid = (mid + Math.imul(ah4, bl5)) | 0; + hi = (hi + Math.imul(ah4, bh5)) | 0; + lo = (lo + Math.imul(al3, bl6)) | 0; + mid = (mid + Math.imul(al3, bh6)) | 0; + mid = (mid + Math.imul(ah3, bl6)) | 0; + hi = (hi + Math.imul(ah3, bh6)) | 0; + lo = (lo + Math.imul(al2, bl7)) | 0; + mid = (mid + Math.imul(al2, bh7)) | 0; + mid = (mid + Math.imul(ah2, bl7)) | 0; + hi = (hi + Math.imul(ah2, bh7)) | 0; + lo = (lo + Math.imul(al1, bl8)) | 0; + mid = (mid + Math.imul(al1, bh8)) | 0; + mid = (mid + Math.imul(ah1, bl8)) | 0; + hi = (hi + Math.imul(ah1, bh8)) | 0; + lo = (lo + Math.imul(al0, bl9)) | 0; + mid = (mid + Math.imul(al0, bh9)) | 0; + mid = (mid + Math.imul(ah0, bl9)) | 0; + hi = (hi + Math.imul(ah0, bh9)) | 0; + var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; + w9 &= 0x3ffffff; + /* k = 10 */ + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = (mid + Math.imul(ah9, bl1)) | 0; + hi = Math.imul(ah9, bh1); + lo = (lo + Math.imul(al8, bl2)) | 0; + mid = (mid + Math.imul(al8, bh2)) | 0; + mid = (mid + Math.imul(ah8, bl2)) | 0; + hi = (hi + Math.imul(ah8, bh2)) | 0; + lo = (lo + Math.imul(al7, bl3)) | 0; + mid = (mid + Math.imul(al7, bh3)) | 0; + mid = (mid + Math.imul(ah7, bl3)) | 0; + hi = (hi + Math.imul(ah7, bh3)) | 0; + lo = (lo + Math.imul(al6, bl4)) | 0; + mid = (mid + Math.imul(al6, bh4)) | 0; + mid = (mid + Math.imul(ah6, bl4)) | 0; + hi = (hi + Math.imul(ah6, bh4)) | 0; + lo = (lo + Math.imul(al5, bl5)) | 0; + mid = (mid + Math.imul(al5, bh5)) | 0; + mid = (mid + Math.imul(ah5, bl5)) | 0; + hi = (hi + Math.imul(ah5, bh5)) | 0; + lo = (lo + Math.imul(al4, bl6)) | 0; + mid = (mid + Math.imul(al4, bh6)) | 0; + mid = (mid + Math.imul(ah4, bl6)) | 0; + hi = (hi + Math.imul(ah4, bh6)) | 0; + lo = (lo + Math.imul(al3, bl7)) | 0; + mid = (mid + Math.imul(al3, bh7)) | 0; + mid = (mid + Math.imul(ah3, bl7)) | 0; + hi = (hi + Math.imul(ah3, bh7)) | 0; + lo = (lo + Math.imul(al2, bl8)) | 0; + mid = (mid + Math.imul(al2, bh8)) | 0; + mid = (mid + Math.imul(ah2, bl8)) | 0; + hi = (hi + Math.imul(ah2, bh8)) | 0; + lo = (lo + Math.imul(al1, bl9)) | 0; + mid = (mid + Math.imul(al1, bh9)) | 0; + mid = (mid + Math.imul(ah1, bl9)) | 0; + hi = (hi + Math.imul(ah1, bh9)) | 0; + var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; + w10 &= 0x3ffffff; + /* k = 11 */ + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = (mid + Math.imul(ah9, bl2)) | 0; + hi = Math.imul(ah9, bh2); + lo = (lo + Math.imul(al8, bl3)) | 0; + mid = (mid + Math.imul(al8, bh3)) | 0; + mid = (mid + Math.imul(ah8, bl3)) | 0; + hi = (hi + Math.imul(ah8, bh3)) | 0; + lo = (lo + Math.imul(al7, bl4)) | 0; + mid = (mid + Math.imul(al7, bh4)) | 0; + mid = (mid + Math.imul(ah7, bl4)) | 0; + hi = (hi + Math.imul(ah7, bh4)) | 0; + lo = (lo + Math.imul(al6, bl5)) | 0; + mid = (mid + Math.imul(al6, bh5)) | 0; + mid = (mid + Math.imul(ah6, bl5)) | 0; + hi = (hi + Math.imul(ah6, bh5)) | 0; + lo = (lo + Math.imul(al5, bl6)) | 0; + mid = (mid + Math.imul(al5, bh6)) | 0; + mid = (mid + Math.imul(ah5, bl6)) | 0; + hi = (hi + Math.imul(ah5, bh6)) | 0; + lo = (lo + Math.imul(al4, bl7)) | 0; + mid = (mid + Math.imul(al4, bh7)) | 0; + mid = (mid + Math.imul(ah4, bl7)) | 0; + hi = (hi + Math.imul(ah4, bh7)) | 0; + lo = (lo + Math.imul(al3, bl8)) | 0; + mid = (mid + Math.imul(al3, bh8)) | 0; + mid = (mid + Math.imul(ah3, bl8)) | 0; + hi = (hi + Math.imul(ah3, bh8)) | 0; + lo = (lo + Math.imul(al2, bl9)) | 0; + mid = (mid + Math.imul(al2, bh9)) | 0; + mid = (mid + Math.imul(ah2, bl9)) | 0; + hi = (hi + Math.imul(ah2, bh9)) | 0; + var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; + w11 &= 0x3ffffff; + /* k = 12 */ + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = (mid + Math.imul(ah9, bl3)) | 0; + hi = Math.imul(ah9, bh3); + lo = (lo + Math.imul(al8, bl4)) | 0; + mid = (mid + Math.imul(al8, bh4)) | 0; + mid = (mid + Math.imul(ah8, bl4)) | 0; + hi = (hi + Math.imul(ah8, bh4)) | 0; + lo = (lo + Math.imul(al7, bl5)) | 0; + mid = (mid + Math.imul(al7, bh5)) | 0; + mid = (mid + Math.imul(ah7, bl5)) | 0; + hi = (hi + Math.imul(ah7, bh5)) | 0; + lo = (lo + Math.imul(al6, bl6)) | 0; + mid = (mid + Math.imul(al6, bh6)) | 0; + mid = (mid + Math.imul(ah6, bl6)) | 0; + hi = (hi + Math.imul(ah6, bh6)) | 0; + lo = (lo + Math.imul(al5, bl7)) | 0; + mid = (mid + Math.imul(al5, bh7)) | 0; + mid = (mid + Math.imul(ah5, bl7)) | 0; + hi = (hi + Math.imul(ah5, bh7)) | 0; + lo = (lo + Math.imul(al4, bl8)) | 0; + mid = (mid + Math.imul(al4, bh8)) | 0; + mid = (mid + Math.imul(ah4, bl8)) | 0; + hi = (hi + Math.imul(ah4, bh8)) | 0; + lo = (lo + Math.imul(al3, bl9)) | 0; + mid = (mid + Math.imul(al3, bh9)) | 0; + mid = (mid + Math.imul(ah3, bl9)) | 0; + hi = (hi + Math.imul(ah3, bh9)) | 0; + var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; + w12 &= 0x3ffffff; + /* k = 13 */ + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = (mid + Math.imul(ah9, bl4)) | 0; + hi = Math.imul(ah9, bh4); + lo = (lo + Math.imul(al8, bl5)) | 0; + mid = (mid + Math.imul(al8, bh5)) | 0; + mid = (mid + Math.imul(ah8, bl5)) | 0; + hi = (hi + Math.imul(ah8, bh5)) | 0; + lo = (lo + Math.imul(al7, bl6)) | 0; + mid = (mid + Math.imul(al7, bh6)) | 0; + mid = (mid + Math.imul(ah7, bl6)) | 0; + hi = (hi + Math.imul(ah7, bh6)) | 0; + lo = (lo + Math.imul(al6, bl7)) | 0; + mid = (mid + Math.imul(al6, bh7)) | 0; + mid = (mid + Math.imul(ah6, bl7)) | 0; + hi = (hi + Math.imul(ah6, bh7)) | 0; + lo = (lo + Math.imul(al5, bl8)) | 0; + mid = (mid + Math.imul(al5, bh8)) | 0; + mid = (mid + Math.imul(ah5, bl8)) | 0; + hi = (hi + Math.imul(ah5, bh8)) | 0; + lo = (lo + Math.imul(al4, bl9)) | 0; + mid = (mid + Math.imul(al4, bh9)) | 0; + mid = (mid + Math.imul(ah4, bl9)) | 0; + hi = (hi + Math.imul(ah4, bh9)) | 0; + var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; + w13 &= 0x3ffffff; + /* k = 14 */ + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = (mid + Math.imul(ah9, bl5)) | 0; + hi = Math.imul(ah9, bh5); + lo = (lo + Math.imul(al8, bl6)) | 0; + mid = (mid + Math.imul(al8, bh6)) | 0; + mid = (mid + Math.imul(ah8, bl6)) | 0; + hi = (hi + Math.imul(ah8, bh6)) | 0; + lo = (lo + Math.imul(al7, bl7)) | 0; + mid = (mid + Math.imul(al7, bh7)) | 0; + mid = (mid + Math.imul(ah7, bl7)) | 0; + hi = (hi + Math.imul(ah7, bh7)) | 0; + lo = (lo + Math.imul(al6, bl8)) | 0; + mid = (mid + Math.imul(al6, bh8)) | 0; + mid = (mid + Math.imul(ah6, bl8)) | 0; + hi = (hi + Math.imul(ah6, bh8)) | 0; + lo = (lo + Math.imul(al5, bl9)) | 0; + mid = (mid + Math.imul(al5, bh9)) | 0; + mid = (mid + Math.imul(ah5, bl9)) | 0; + hi = (hi + Math.imul(ah5, bh9)) | 0; + var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; + w14 &= 0x3ffffff; + /* k = 15 */ + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = (mid + Math.imul(ah9, bl6)) | 0; + hi = Math.imul(ah9, bh6); + lo = (lo + Math.imul(al8, bl7)) | 0; + mid = (mid + Math.imul(al8, bh7)) | 0; + mid = (mid + Math.imul(ah8, bl7)) | 0; + hi = (hi + Math.imul(ah8, bh7)) | 0; + lo = (lo + Math.imul(al7, bl8)) | 0; + mid = (mid + Math.imul(al7, bh8)) | 0; + mid = (mid + Math.imul(ah7, bl8)) | 0; + hi = (hi + Math.imul(ah7, bh8)) | 0; + lo = (lo + Math.imul(al6, bl9)) | 0; + mid = (mid + Math.imul(al6, bh9)) | 0; + mid = (mid + Math.imul(ah6, bl9)) | 0; + hi = (hi + Math.imul(ah6, bh9)) | 0; + var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; + w15 &= 0x3ffffff; + /* k = 16 */ + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = (mid + Math.imul(ah9, bl7)) | 0; + hi = Math.imul(ah9, bh7); + lo = (lo + Math.imul(al8, bl8)) | 0; + mid = (mid + Math.imul(al8, bh8)) | 0; + mid = (mid + Math.imul(ah8, bl8)) | 0; + hi = (hi + Math.imul(ah8, bh8)) | 0; + lo = (lo + Math.imul(al7, bl9)) | 0; + mid = (mid + Math.imul(al7, bh9)) | 0; + mid = (mid + Math.imul(ah7, bl9)) | 0; + hi = (hi + Math.imul(ah7, bh9)) | 0; + var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; + w16 &= 0x3ffffff; + /* k = 17 */ + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = (mid + Math.imul(ah9, bl8)) | 0; + hi = Math.imul(ah9, bh8); + lo = (lo + Math.imul(al8, bl9)) | 0; + mid = (mid + Math.imul(al8, bh9)) | 0; + mid = (mid + Math.imul(ah8, bl9)) | 0; + hi = (hi + Math.imul(ah8, bh9)) | 0; + var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; + w17 &= 0x3ffffff; + /* k = 18 */ + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = (mid + Math.imul(ah9, bl9)) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; + c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; + 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 (this.length <= s) { + return this; + } + + 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).toRed(this); + 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); + +},{"buffer":18}],17:[function(require,module,exports){ +var r; + +module.exports = function rand(len) { + if (!r) + r = new Rand(null); + + return r.generate(len); +}; + +function Rand(rand) { + this.rand = rand; +} +module.exports.Rand = Rand; + +Rand.prototype.generate = function generate(len) { + return this._rand(len); +}; + +// Emulate crypto API using randy +Rand.prototype._rand = function _rand(n) { + if (this.rand.getBytes) + return this.rand.getBytes(n); + + var res = new Uint8Array(n); + for (var i = 0; i < res.length; i++) + res[i] = this.rand.getByte(); + return res; +}; + +if (typeof self === 'object') { + if (self.crypto && self.crypto.getRandomValues) { + // Modern browsers + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.crypto.getRandomValues(arr); + return arr; + }; + } else if (self.msCrypto && self.msCrypto.getRandomValues) { + // IE + Rand.prototype._rand = function _rand(n) { + var arr = new Uint8Array(n); + self.msCrypto.getRandomValues(arr); + return arr; + }; + + // Safari's WebWorkers do not have `crypto` + } else if (typeof window === 'object') { + // Old junk + Rand.prototype._rand = function() { + throw new Error('Not implemented yet'); + }; + } +} else { + // Node.js or Web worker with no crypto support + try { + var crypto = require('crypto'); + if (typeof crypto.randomBytes !== 'function') + throw new Error('Not supported'); + + Rand.prototype._rand = function _rand(n) { + return crypto.randomBytes(n); + }; + } catch (e) { + } +} + +},{"crypto":18}],18:[function(require,module,exports){ + +},{}],19:[function(require,module,exports){ +// based on the aes implimentation in triple sec +// https://github.com/keybase/triplesec +// which is in turn based on the one from crypto-js +// https://code.google.com/p/crypto-js/ + +var Buffer = require('safe-buffer').Buffer + +function asUInt32Array (buf) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) + + var len = (buf.length / 4) | 0 + var out = new Array(len) + + for (var i = 0; i < len; i++) { + out[i] = buf.readUInt32BE(i * 4) + } + + return out +} + +function scrubVec (v) { + for (var i = 0; i < v.length; v++) { + v[i] = 0 + } +} + +function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) { + var SUB_MIX0 = SUB_MIX[0] + var SUB_MIX1 = SUB_MIX[1] + var SUB_MIX2 = SUB_MIX[2] + var SUB_MIX3 = SUB_MIX[3] + + var s0 = M[0] ^ keySchedule[0] + var s1 = M[1] ^ keySchedule[1] + var s2 = M[2] ^ keySchedule[2] + var s3 = M[3] ^ keySchedule[3] + var t0, t1, t2, t3 + var ksRow = 4 + + for (var round = 1; round < nRounds; round++) { + t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] + t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] + t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] + t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] + s0 = t0 + s1 = t1 + s2 = t2 + s3 = t3 + } + + t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] + t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] + t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] + t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] + t0 = t0 >>> 0 + t1 = t1 >>> 0 + t2 = t2 >>> 0 + t3 = t3 >>> 0 + + return [t0, t1, t2, t3] +} + +// AES constants +var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] +var G = (function () { + // Compute double table + var d = new Array(256) + for (var j = 0; j < 256; j++) { + if (j < 128) { + d[j] = j << 1 + } else { + d[j] = (j << 1) ^ 0x11b + } + } + + var SBOX = [] + var INV_SBOX = [] + var SUB_MIX = [[], [], [], []] + var INV_SUB_MIX = [[], [], [], []] + + // Walk GF(2^8) + var x = 0 + var xi = 0 + for (var i = 0; i < 256; ++i) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 + SBOX[x] = sx + INV_SBOX[sx] = x + + // Compute multiplication + var x2 = d[x] + var x4 = d[x2] + var x8 = d[x4] + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100) + SUB_MIX[0][x] = (t << 24) | (t >>> 8) + SUB_MIX[1][x] = (t << 16) | (t >>> 16) + SUB_MIX[2][x] = (t << 8) | (t >>> 24) + SUB_MIX[3][x] = t + + // Compute inv sub bytes, inv mix columns tables + t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) + INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) + INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) + INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) + INV_SUB_MIX[3][sx] = t + + if (x === 0) { + x = xi = 1 + } else { + x = x2 ^ d[d[d[x8 ^ x2]]] + xi ^= d[d[xi]] + } + } + + return { + SBOX: SBOX, + INV_SBOX: INV_SBOX, + SUB_MIX: SUB_MIX, + INV_SUB_MIX: INV_SUB_MIX + } +})() + +function AES (key) { + this._key = asUInt32Array(key) + this._reset() +} + +AES.blockSize = 4 * 4 +AES.keySize = 256 / 8 +AES.prototype.blockSize = AES.blockSize +AES.prototype.keySize = AES.keySize +AES.prototype._reset = function () { + var keyWords = this._key + var keySize = keyWords.length + var nRounds = keySize + 6 + var ksRows = (nRounds + 1) * 4 + + var keySchedule = [] + for (var k = 0; k < keySize; k++) { + keySchedule[k] = keyWords[k] + } + + for (k = keySize; k < ksRows; k++) { + var t = keySchedule[k - 1] + + if (k % keySize === 0) { + t = (t << 8) | (t >>> 24) + t = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (G.SBOX[(t >>> 8) & 0xff] << 8) | + (G.SBOX[t & 0xff]) + + t ^= RCON[(k / keySize) | 0] << 24 + } else if (keySize > 6 && k % keySize === 4) { + t = + (G.SBOX[t >>> 24] << 24) | + (G.SBOX[(t >>> 16) & 0xff] << 16) | + (G.SBOX[(t >>> 8) & 0xff] << 8) | + (G.SBOX[t & 0xff]) + } + + keySchedule[k] = keySchedule[k - keySize] ^ t + } + + var invKeySchedule = [] + for (var ik = 0; ik < ksRows; ik++) { + var ksR = ksRows - ik + var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] + + if (ik < 4 || ksR <= 4) { + invKeySchedule[ik] = tt + } else { + invKeySchedule[ik] = + G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ + G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ + G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ + G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] + } + } + + this._nRounds = nRounds + this._keySchedule = keySchedule + this._invKeySchedule = invKeySchedule +} + +AES.prototype.encryptBlockRaw = function (M) { + M = asUInt32Array(M) + return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) +} + +AES.prototype.encryptBlock = function (M) { + var out = this.encryptBlockRaw(M) + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[1], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[3], 12) + return buf +} + +AES.prototype.decryptBlock = function (M) { + M = asUInt32Array(M) + + // swap + var m1 = M[1] + M[1] = M[3] + M[3] = m1 + + var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0], 0) + buf.writeUInt32BE(out[3], 4) + buf.writeUInt32BE(out[2], 8) + buf.writeUInt32BE(out[1], 12) + return buf +} + +AES.prototype.scrub = function () { + scrubVec(this._keySchedule) + scrubVec(this._invKeySchedule) + scrubVec(this._key) +} + +module.exports.AES = AES + +},{"safe-buffer":142}],20:[function(require,module,exports){ +var aes = require('./aes') +var Buffer = require('safe-buffer').Buffer +var Transform = require('cipher-base') +var inherits = require('inherits') +var GHASH = require('./ghash') +var xor = require('buffer-xor') +var incr32 = require('./incr32') + +function xorTest (a, b) { + var out = 0 + if (a.length !== b.length) out++ + + var len = Math.min(a.length, b.length) + for (var i = 0; i < len; ++i) { + out += (a[i] ^ b[i]) + } + + return out +} + +function calcIv (self, iv, ck) { + if (iv.length === 12) { + self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) + return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) + } + var ghash = new GHASH(ck) + var len = iv.length + var toPad = len % 16 + ghash.update(iv) + if (toPad) { + toPad = 16 - toPad + ghash.update(Buffer.alloc(toPad, 0)) + } + ghash.update(Buffer.alloc(8, 0)) + var ivBits = len * 8 + var tail = Buffer.alloc(8) + tail.writeUIntBE(ivBits, 0, 8) + ghash.update(tail) + self._finID = ghash.state + var out = Buffer.from(self._finID) + incr32(out) + return out +} +function StreamCipher (mode, key, iv, decrypt) { + Transform.call(this) + + var h = Buffer.alloc(4, 0) + + this._cipher = new aes.AES(key) + var ck = this._cipher.encryptBlock(h) + this._ghash = new GHASH(ck) + iv = calcIv(this, iv, ck) + + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) + this._decrypt = decrypt + this._alen = 0 + this._len = 0 + this._mode = mode + + this._authTag = null + this._called = false +} + +inherits(StreamCipher, Transform) + +StreamCipher.prototype._update = function (chunk) { + if (!this._called && this._alen) { + var rump = 16 - (this._alen % 16) + if (rump < 16) { + rump = Buffer.alloc(rump, 0) + this._ghash.update(rump) + } + } + + this._called = true + var out = this._mode.encrypt(this, chunk) + if (this._decrypt) { + this._ghash.update(chunk) + } else { + this._ghash.update(out) + } + this._len += chunk.length + return out +} + +StreamCipher.prototype._final = function () { + if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') + + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) + if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') + + this._authTag = tag + this._cipher.scrub() +} + +StreamCipher.prototype.getAuthTag = function getAuthTag () { + if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') + + return this._authTag +} + +StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { + if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') + + this._authTag = tag +} + +StreamCipher.prototype.setAAD = function setAAD (buf) { + if (this._called) throw new Error('Attempting to set AAD in unsupported state') + + this._ghash.update(buf) + this._alen += buf.length +} + +module.exports = StreamCipher + +},{"./aes":19,"./ghash":24,"./incr32":25,"buffer-xor":46,"cipher-base":48,"inherits":101,"safe-buffer":142}],21:[function(require,module,exports){ +var ciphers = require('./encrypter') +var deciphers = require('./decrypter') +var modes = require('./modes/list.json') + +function getCiphers () { + return Object.keys(modes) +} + +exports.createCipher = exports.Cipher = ciphers.createCipher +exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv +exports.createDecipher = exports.Decipher = deciphers.createDecipher +exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv +exports.listCiphers = exports.getCiphers = getCiphers + +},{"./decrypter":22,"./encrypter":23,"./modes/list.json":33}],22:[function(require,module,exports){ +var AuthCipher = require('./authCipher') +var Buffer = require('safe-buffer').Buffer +var MODES = require('./modes') +var StreamCipher = require('./streamCipher') +var Transform = require('cipher-base') +var aes = require('./aes') +var ebtk = require('evp_bytestokey') +var inherits = require('inherits') + +function Decipher (mode, key, iv) { + Transform.call(this) + + this._cache = new Splitter() + this._last = void 0 + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._mode = mode + this._autopadding = true +} + +inherits(Decipher, Transform) + +Decipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + while ((chunk = this._cache.get(this._autopadding))) { + thing = this._mode.decrypt(this, chunk) + out.push(thing) + } + return Buffer.concat(out) +} + +Decipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + return unpad(this._mode.decrypt(this, chunk)) + } else if (chunk) { + throw new Error('data not multiple of block length') + } +} + +Decipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} + +function Splitter () { + this.cache = Buffer.allocUnsafe(0) +} + +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function (autoPadding) { + var out + if (autoPadding) { + if (this.cache.length > 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } else { + if (this.cache.length >= 16) { + out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + } + + return null +} + +Splitter.prototype.flush = function () { + if (this.cache.length) return this.cache +} + +function unpad (last) { + var padded = last[15] + if (padded < 1 || padded > 16) { + throw new Error('unable to decrypt data') + } + var i = -1 + while (++i < padded) { + if (last[(i + (16 - padded))] !== padded) { + throw new Error('unable to decrypt data') + } + } + if (padded === 16) return + + return last.slice(0, 16 - padded) +} + +function createDecipheriv (suite, password, iv) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + if (typeof iv === 'string') iv = Buffer.from(iv) + if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) + + if (typeof password === 'string') password = Buffer.from(password) + if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) + + if (config.type === 'stream') { + return new StreamCipher(config.module, password, iv, true) + } else if (config.type === 'auth') { + return new AuthCipher(config.module, password, iv, true) + } + + return new Decipher(config.module, password, iv) +} + +function createDecipher (suite, password) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + var keys = ebtk(password, false, config.key, config.iv) + return createDecipheriv(suite, keys.key, keys.iv) +} + +exports.createDecipher = createDecipher +exports.createDecipheriv = createDecipheriv + +},{"./aes":19,"./authCipher":20,"./modes":32,"./streamCipher":35,"cipher-base":48,"evp_bytestokey":83,"inherits":101,"safe-buffer":142}],23:[function(require,module,exports){ +var MODES = require('./modes') +var AuthCipher = require('./authCipher') +var Buffer = require('safe-buffer').Buffer +var StreamCipher = require('./streamCipher') +var Transform = require('cipher-base') +var aes = require('./aes') +var ebtk = require('evp_bytestokey') +var inherits = require('inherits') + +function Cipher (mode, key, iv) { + Transform.call(this) + + this._cache = new Splitter() + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._mode = mode + this._autopadding = true +} + +inherits(Cipher, Transform) + +Cipher.prototype._update = function (data) { + this._cache.add(data) + var chunk + var thing + var out = [] + + while ((chunk = this._cache.get())) { + thing = this._mode.encrypt(this, chunk) + out.push(thing) + } + + return Buffer.concat(out) +} + +var PADDING = Buffer.alloc(16, 0x10) + +Cipher.prototype._final = function () { + var chunk = this._cache.flush() + if (this._autopadding) { + chunk = this._mode.encrypt(this, chunk) + this._cipher.scrub() + return chunk + } + + if (!chunk.equals(PADDING)) { + this._cipher.scrub() + throw new Error('data not multiple of block length') + } +} + +Cipher.prototype.setAutoPadding = function (setTo) { + this._autopadding = !!setTo + return this +} + +function Splitter () { + this.cache = Buffer.allocUnsafe(0) +} + +Splitter.prototype.add = function (data) { + this.cache = Buffer.concat([this.cache, data]) +} + +Splitter.prototype.get = function () { + if (this.cache.length > 15) { + var out = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + return out + } + return null +} + +Splitter.prototype.flush = function () { + var len = 16 - this.cache.length + var padBuff = Buffer.allocUnsafe(len) + + var i = -1 + while (++i < len) { + padBuff.writeUInt8(len, i) + } + + return Buffer.concat([this.cache, padBuff]) +} + +function createCipheriv (suite, password, iv) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + if (typeof password === 'string') password = Buffer.from(password) + if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) + + if (typeof iv === 'string') iv = Buffer.from(iv) + if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) + + if (config.type === 'stream') { + return new StreamCipher(config.module, password, iv) + } else if (config.type === 'auth') { + return new AuthCipher(config.module, password, iv) + } + + return new Cipher(config.module, password, iv) +} + +function createCipher (suite, password) { + var config = MODES[suite.toLowerCase()] + if (!config) throw new TypeError('invalid suite type') + + var keys = ebtk(password, false, config.key, config.iv) + return createCipheriv(suite, keys.key, keys.iv) +} + +exports.createCipheriv = createCipheriv +exports.createCipher = createCipher + +},{"./aes":19,"./authCipher":20,"./modes":32,"./streamCipher":35,"cipher-base":48,"evp_bytestokey":83,"inherits":101,"safe-buffer":142}],24:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer +var ZEROES = Buffer.alloc(16, 0) + +function toArray (buf) { + return [ + buf.readUInt32BE(0), + buf.readUInt32BE(4), + buf.readUInt32BE(8), + buf.readUInt32BE(12) + ] +} + +function fromArray (out) { + var buf = Buffer.allocUnsafe(16) + buf.writeUInt32BE(out[0] >>> 0, 0) + buf.writeUInt32BE(out[1] >>> 0, 4) + buf.writeUInt32BE(out[2] >>> 0, 8) + buf.writeUInt32BE(out[3] >>> 0, 12) + return buf +} + +function GHASH (key) { + this.h = key + this.state = Buffer.alloc(16, 0) + this.cache = Buffer.allocUnsafe(0) +} + +// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html +// by Juho Vähä-Herttua +GHASH.prototype.ghash = function (block) { + var i = -1 + while (++i < block.length) { + this.state[i] ^= block[i] + } + this._multiply() +} + +GHASH.prototype._multiply = function () { + var Vi = toArray(this.h) + var Zi = [0, 0, 0, 0] + var j, xi, lsbVi + var i = -1 + while (++i < 128) { + xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 + if (xi) { + // Z_i+1 = Z_i ^ V_i + Zi[0] ^= Vi[0] + Zi[1] ^= Vi[1] + Zi[2] ^= Vi[2] + Zi[3] ^= Vi[3] + } + + // Store the value of LSB(V_i) + lsbVi = (Vi[3] & 1) !== 0 + + // V_i+1 = V_i >> 1 + for (j = 3; j > 0; j--) { + Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) + } + Vi[0] = Vi[0] >>> 1 + + // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R + if (lsbVi) { + Vi[0] = Vi[0] ^ (0xe1 << 24) + } + } + this.state = fromArray(Zi) +} + +GHASH.prototype.update = function (buf) { + this.cache = Buffer.concat([this.cache, buf]) + var chunk + while (this.cache.length >= 16) { + chunk = this.cache.slice(0, 16) + this.cache = this.cache.slice(16) + this.ghash(chunk) + } +} + +GHASH.prototype.final = function (abl, bl) { + if (this.cache.length) { + this.ghash(Buffer.concat([this.cache, ZEROES], 16)) + } + + this.ghash(fromArray([0, abl, 0, bl])) + return this.state +} + +module.exports = GHASH + +},{"safe-buffer":142}],25:[function(require,module,exports){ +function incr32 (iv) { + var len = iv.length + var item + while (len--) { + item = iv.readUInt8(len) + if (item === 255) { + iv.writeUInt8(0, len) + } else { + item++ + iv.writeUInt8(item, len) + break + } + } +} +module.exports = incr32 + +},{}],26:[function(require,module,exports){ +var xor = require('buffer-xor') + +exports.encrypt = function (self, block) { + var data = xor(block, self._prev) + + self._prev = self._cipher.encryptBlock(data) + return self._prev +} + +exports.decrypt = function (self, block) { + var pad = self._prev + + self._prev = block + var out = self._cipher.decryptBlock(block) + + return xor(out, pad) +} + +},{"buffer-xor":46}],27:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer +var xor = require('buffer-xor') + +function encryptStart (self, data, decrypt) { + var len = data.length + var out = xor(data, self._cache) + self._cache = self._cache.slice(len) + self._prev = Buffer.concat([self._prev, decrypt ? data : out]) + return out +} + +exports.encrypt = function (self, data, decrypt) { + var out = Buffer.allocUnsafe(0) + var len + + while (data.length) { + if (self._cache.length === 0) { + self._cache = self._cipher.encryptBlock(self._prev) + self._prev = Buffer.allocUnsafe(0) + } + + if (self._cache.length <= data.length) { + len = self._cache.length + out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) + data = data.slice(len) + } else { + out = Buffer.concat([out, encryptStart(self, data, decrypt)]) + break + } + } + + return out +} + +},{"buffer-xor":46,"safe-buffer":142}],28:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer + +function encryptByte (self, byteParam, decrypt) { + var pad + var i = -1 + var len = 8 + var out = 0 + var bit, value + while (++i < len) { + pad = self._cipher.encryptBlock(self._prev) + bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 + value = pad[0] ^ bit + out += ((value & 0x80) >> (i % 8)) + self._prev = shiftIn(self._prev, decrypt ? bit : value) + } + return out +} + +function shiftIn (buffer, value) { + var len = buffer.length + var i = -1 + var out = Buffer.allocUnsafe(buffer.length) + buffer = Buffer.concat([buffer, Buffer.from([value])]) + + while (++i < len) { + out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) + } + + return out +} + +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = Buffer.allocUnsafe(len) + var i = -1 + + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + + return out +} + +},{"safe-buffer":142}],29:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer + +function encryptByte (self, byteParam, decrypt) { + var pad = self._cipher.encryptBlock(self._prev) + var out = pad[0] ^ byteParam + + self._prev = Buffer.concat([ + self._prev.slice(1), + Buffer.from([decrypt ? byteParam : out]) + ]) + + return out +} + +exports.encrypt = function (self, chunk, decrypt) { + var len = chunk.length + var out = Buffer.allocUnsafe(len) + var i = -1 + + while (++i < len) { + out[i] = encryptByte(self, chunk[i], decrypt) + } + + return out +} + +},{"safe-buffer":142}],30:[function(require,module,exports){ +var xor = require('buffer-xor') +var Buffer = require('safe-buffer').Buffer +var incr32 = require('../incr32') + +function getBlock (self) { + var out = self._cipher.encryptBlockRaw(self._prev) + incr32(self._prev) + return out +} + +var blockSize = 16 +exports.encrypt = function (self, chunk) { + var chunkNum = Math.ceil(chunk.length / blockSize) + var start = self._cache.length + self._cache = Buffer.concat([ + self._cache, + Buffer.allocUnsafe(chunkNum * blockSize) + ]) + for (var i = 0; i < chunkNum; i++) { + var out = getBlock(self) + var offset = start + i * blockSize + self._cache.writeUInt32BE(out[0], offset + 0) + self._cache.writeUInt32BE(out[1], offset + 4) + self._cache.writeUInt32BE(out[2], offset + 8) + self._cache.writeUInt32BE(out[3], offset + 12) + } + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} + +},{"../incr32":25,"buffer-xor":46,"safe-buffer":142}],31:[function(require,module,exports){ +exports.encrypt = function (self, block) { + return self._cipher.encryptBlock(block) +} + +exports.decrypt = function (self, block) { + return self._cipher.decryptBlock(block) +} + +},{}],32:[function(require,module,exports){ +var modeModules = { + ECB: require('./ecb'), + CBC: require('./cbc'), + CFB: require('./cfb'), + CFB8: require('./cfb8'), + CFB1: require('./cfb1'), + OFB: require('./ofb'), + CTR: require('./ctr'), + GCM: require('./ctr') +} + +var modes = require('./list.json') + +for (var key in modes) { + modes[key].module = modeModules[modes[key].mode] +} + +module.exports = modes + +},{"./cbc":26,"./cfb":27,"./cfb1":28,"./cfb8":29,"./ctr":30,"./ecb":31,"./list.json":33,"./ofb":34}],33:[function(require,module,exports){ +module.exports={ + "aes-128-ecb": { + "cipher": "AES", + "key": 128, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-192-ecb": { + "cipher": "AES", + "key": 192, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-256-ecb": { + "cipher": "AES", + "key": 256, + "iv": 0, + "mode": "ECB", + "type": "block" + }, + "aes-128-cbc": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-192-cbc": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-256-cbc": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes128": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes192": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes256": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CBC", + "type": "block" + }, + "aes-128-cfb": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-192-cfb": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-256-cfb": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB", + "type": "stream" + }, + "aes-128-cfb8": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-192-cfb8": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-256-cfb8": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB8", + "type": "stream" + }, + "aes-128-cfb1": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-192-cfb1": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-256-cfb1": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CFB1", + "type": "stream" + }, + "aes-128-ofb": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-192-ofb": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-256-ofb": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "OFB", + "type": "stream" + }, + "aes-128-ctr": { + "cipher": "AES", + "key": 128, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-192-ctr": { + "cipher": "AES", + "key": 192, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-256-ctr": { + "cipher": "AES", + "key": 256, + "iv": 16, + "mode": "CTR", + "type": "stream" + }, + "aes-128-gcm": { + "cipher": "AES", + "key": 128, + "iv": 12, + "mode": "GCM", + "type": "auth" + }, + "aes-192-gcm": { + "cipher": "AES", + "key": 192, + "iv": 12, + "mode": "GCM", + "type": "auth" + }, + "aes-256-gcm": { + "cipher": "AES", + "key": 256, + "iv": 12, + "mode": "GCM", + "type": "auth" + } +} + +},{}],34:[function(require,module,exports){ +(function (Buffer){ +var xor = require('buffer-xor') + +function getBlock (self) { + self._prev = self._cipher.encryptBlock(self._prev) + return self._prev +} + +exports.encrypt = function (self, chunk) { + while (self._cache.length < chunk.length) { + self._cache = Buffer.concat([self._cache, getBlock(self)]) + } + + var pad = self._cache.slice(0, chunk.length) + self._cache = self._cache.slice(chunk.length) + return xor(chunk, pad) +} + +}).call(this,require("buffer").Buffer) +},{"buffer":47,"buffer-xor":46}],35:[function(require,module,exports){ +var aes = require('./aes') +var Buffer = require('safe-buffer').Buffer +var Transform = require('cipher-base') +var inherits = require('inherits') + +function StreamCipher (mode, key, iv, decrypt) { + Transform.call(this) + + this._cipher = new aes.AES(key) + this._prev = Buffer.from(iv) + this._cache = Buffer.allocUnsafe(0) + this._secCache = Buffer.allocUnsafe(0) + this._decrypt = decrypt + this._mode = mode +} + +inherits(StreamCipher, Transform) + +StreamCipher.prototype._update = function (chunk) { + return this._mode.encrypt(this, chunk, this._decrypt) +} + +StreamCipher.prototype._final = function () { + this._cipher.scrub() +} + +module.exports = StreamCipher + +},{"./aes":19,"cipher-base":48,"inherits":101,"safe-buffer":142}],36:[function(require,module,exports){ +var DES = require('browserify-des') +var aes = require('browserify-aes/browser') +var aesModes = require('browserify-aes/modes') +var desModes = require('browserify-des/modes') +var ebtk = require('evp_bytestokey') + +function createCipher (suite, password) { + suite = suite.toLowerCase() + + var keyLen, ivLen + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + + var keys = ebtk(password, false, keyLen, ivLen) + return createCipheriv(suite, keys.key, keys.iv) +} + +function createDecipher (suite, password) { + suite = suite.toLowerCase() + + var keyLen, ivLen + if (aesModes[suite]) { + keyLen = aesModes[suite].key + ivLen = aesModes[suite].iv + } else if (desModes[suite]) { + keyLen = desModes[suite].key * 8 + ivLen = desModes[suite].iv + } else { + throw new TypeError('invalid suite type') + } + + var keys = ebtk(password, false, keyLen, ivLen) + return createDecipheriv(suite, keys.key, keys.iv) +} + +function createCipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) return aes.createCipheriv(suite, key, iv) + if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite }) + + throw new TypeError('invalid suite type') +} + +function createDecipheriv (suite, key, iv) { + suite = suite.toLowerCase() + if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv) + if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true }) + + throw new TypeError('invalid suite type') +} + +function getCiphers () { + return Object.keys(desModes).concat(aes.getCiphers()) +} + +exports.createCipher = exports.Cipher = createCipher +exports.createCipheriv = exports.Cipheriv = createCipheriv +exports.createDecipher = exports.Decipher = createDecipher +exports.createDecipheriv = exports.Decipheriv = createDecipheriv +exports.listCiphers = exports.getCiphers = getCiphers + +},{"browserify-aes/browser":21,"browserify-aes/modes":32,"browserify-des":37,"browserify-des/modes":38,"evp_bytestokey":83}],37:[function(require,module,exports){ +var CipherBase = require('cipher-base') +var des = require('des.js') +var inherits = require('inherits') +var Buffer = require('safe-buffer').Buffer + +var modes = { + 'des-ede3-cbc': des.CBC.instantiate(des.EDE), + 'des-ede3': des.EDE, + 'des-ede-cbc': des.CBC.instantiate(des.EDE), + 'des-ede': des.EDE, + 'des-cbc': des.CBC.instantiate(des.DES), + 'des-ecb': des.DES +} +modes.des = modes['des-cbc'] +modes.des3 = modes['des-ede3-cbc'] +module.exports = DES +inherits(DES, CipherBase) +function DES (opts) { + CipherBase.call(this) + var modeName = opts.mode.toLowerCase() + var mode = modes[modeName] + var type + if (opts.decrypt) { + type = 'decrypt' + } else { + type = 'encrypt' + } + var key = opts.key + if (!Buffer.isBuffer(key)) { + key = Buffer.from(key) + } + if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { + key = Buffer.concat([key, key.slice(0, 8)]) + } + var iv = opts.iv + if (!Buffer.isBuffer(iv)) { + iv = Buffer.from(iv) + } + this._des = mode.create({ + key: key, + iv: iv, + type: type + }) +} +DES.prototype._update = function (data) { + return Buffer.from(this._des.update(data)) +} +DES.prototype._final = function () { + return Buffer.from(this._des.final()) +} + +},{"cipher-base":48,"des.js":56,"inherits":101,"safe-buffer":142}],38:[function(require,module,exports){ +exports['des-ecb'] = { + key: 8, + iv: 0 +} +exports['des-cbc'] = exports.des = { + key: 8, + iv: 8 +} +exports['des-ede3-cbc'] = exports.des3 = { + key: 24, + iv: 8 +} +exports['des-ede3'] = { + key: 24, + iv: 0 +} +exports['des-ede-cbc'] = { + key: 16, + iv: 8 +} +exports['des-ede'] = { + key: 16, + iv: 0 +} + +},{}],39:[function(require,module,exports){ +(function (Buffer){ +var bn = require('bn.js'); +var randomBytes = require('randombytes'); +module.exports = crt; +function blind(priv) { + var r = getr(priv); + var blinder = r.toRed(bn.mont(priv.modulus)) + .redPow(new bn(priv.publicExponent)).fromRed(); + return { + blinder: blinder, + unblinder:r.invm(priv.modulus) + }; +} +function crt(msg, priv) { + var blinds = blind(priv); + var len = priv.modulus.byteLength(); + var mod = bn.mont(priv.modulus); + var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus); + var c1 = blinded.toRed(bn.mont(priv.prime1)); + var c2 = blinded.toRed(bn.mont(priv.prime2)); + var qinv = priv.coefficient; + var p = priv.prime1; + var q = priv.prime2; + var m1 = c1.redPow(priv.exponent1); + var m2 = c2.redPow(priv.exponent2); + m1 = m1.fromRed(); + m2 = m2.fromRed(); + var h = m1.isub(m2).imul(qinv).umod(p); + h.imul(q); + m2.iadd(h); + return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len)); +} +crt.getr = getr; +function getr(priv) { + var len = priv.modulus.byteLength(); + var r = new bn(randomBytes(len)); + while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) { + r = new bn(randomBytes(len)); + } + return r; +} + +}).call(this,require("buffer").Buffer) +},{"bn.js":16,"buffer":47,"randombytes":126}],40:[function(require,module,exports){ +module.exports = require('./browser/algorithms.json') + +},{"./browser/algorithms.json":41}],41:[function(require,module,exports){ +module.exports={ + "sha224WithRSAEncryption": { + "sign": "rsa", + "hash": "sha224", + "id": "302d300d06096086480165030402040500041c" + }, + "RSA-SHA224": { + "sign": "ecdsa/rsa", + "hash": "sha224", + "id": "302d300d06096086480165030402040500041c" + }, + "sha256WithRSAEncryption": { + "sign": "rsa", + "hash": "sha256", + "id": "3031300d060960864801650304020105000420" + }, + "RSA-SHA256": { + "sign": "ecdsa/rsa", + "hash": "sha256", + "id": "3031300d060960864801650304020105000420" + }, + "sha384WithRSAEncryption": { + "sign": "rsa", + "hash": "sha384", + "id": "3041300d060960864801650304020205000430" + }, + "RSA-SHA384": { + "sign": "ecdsa/rsa", + "hash": "sha384", + "id": "3041300d060960864801650304020205000430" + }, + "sha512WithRSAEncryption": { + "sign": "rsa", + "hash": "sha512", + "id": "3051300d060960864801650304020305000440" + }, + "RSA-SHA512": { + "sign": "ecdsa/rsa", + "hash": "sha512", + "id": "3051300d060960864801650304020305000440" + }, + "RSA-SHA1": { + "sign": "rsa", + "hash": "sha1", + "id": "3021300906052b0e03021a05000414" + }, + "ecdsa-with-SHA1": { + "sign": "ecdsa", + "hash": "sha1", + "id": "" + }, + "sha256": { + "sign": "ecdsa", + "hash": "sha256", + "id": "" + }, + "sha224": { + "sign": "ecdsa", + "hash": "sha224", + "id": "" + }, + "sha384": { + "sign": "ecdsa", + "hash": "sha384", + "id": "" + }, + "sha512": { + "sign": "ecdsa", + "hash": "sha512", + "id": "" + }, + "DSA-SHA": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA-SHA1": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA": { + "sign": "dsa", + "hash": "sha1", + "id": "" + }, + "DSA-WITH-SHA224": { + "sign": "dsa", + "hash": "sha224", + "id": "" + }, + "DSA-SHA224": { + "sign": "dsa", + "hash": "sha224", + "id": "" + }, + "DSA-WITH-SHA256": { + "sign": "dsa", + "hash": "sha256", + "id": "" + }, + "DSA-SHA256": { + "sign": "dsa", + "hash": "sha256", + "id": "" + }, + "DSA-WITH-SHA384": { + "sign": "dsa", + "hash": "sha384", + "id": "" + }, + "DSA-SHA384": { + "sign": "dsa", + "hash": "sha384", + "id": "" + }, + "DSA-WITH-SHA512": { + "sign": "dsa", + "hash": "sha512", + "id": "" + }, + "DSA-SHA512": { + "sign": "dsa", + "hash": "sha512", + "id": "" + }, + "DSA-RIPEMD160": { + "sign": "dsa", + "hash": "rmd160", + "id": "" + }, + "ripemd160WithRSA": { + "sign": "rsa", + "hash": "rmd160", + "id": "3021300906052b2403020105000414" + }, + "RSA-RIPEMD160": { + "sign": "rsa", + "hash": "rmd160", + "id": "3021300906052b2403020105000414" + }, + "md5WithRSAEncryption": { + "sign": "rsa", + "hash": "md5", + "id": "3020300c06082a864886f70d020505000410" + }, + "RSA-MD5": { + "sign": "rsa", + "hash": "md5", + "id": "3020300c06082a864886f70d020505000410" + } +} + +},{}],42:[function(require,module,exports){ +module.exports={ + "1.3.132.0.10": "secp256k1", + "1.3.132.0.33": "p224", + "1.2.840.10045.3.1.1": "p192", + "1.2.840.10045.3.1.7": "p256", + "1.3.132.0.34": "p384", + "1.3.132.0.35": "p521" +} + +},{}],43:[function(require,module,exports){ +(function (Buffer){ +var createHash = require('create-hash') +var stream = require('stream') +var inherits = require('inherits') +var sign = require('./sign') +var verify = require('./verify') + +var algorithms = require('./algorithms.json') +Object.keys(algorithms).forEach(function (key) { + algorithms[key].id = new Buffer(algorithms[key].id, 'hex') + algorithms[key.toLowerCase()] = algorithms[key] +}) + +function Sign (algorithm) { + stream.Writable.call(this) + + var data = algorithms[algorithm] + if (!data) throw new Error('Unknown message digest') + + this._hashType = data.hash + this._hash = createHash(data.hash) + this._tag = data.id + this._signType = data.sign +} +inherits(Sign, stream.Writable) + +Sign.prototype._write = function _write (data, _, done) { + this._hash.update(data) + done() +} + +Sign.prototype.update = function update (data, enc) { + if (typeof data === 'string') data = new Buffer(data, enc) + + this._hash.update(data) + return this +} + +Sign.prototype.sign = function signMethod (key, enc) { + this.end() + var hash = this._hash.digest() + var sig = sign(hash, key, this._hashType, this._signType, this._tag) + + return enc ? sig.toString(enc) : sig +} + +function Verify (algorithm) { + stream.Writable.call(this) + + var data = algorithms[algorithm] + if (!data) throw new Error('Unknown message digest') + + this._hash = createHash(data.hash) + this._tag = data.id + this._signType = data.sign +} +inherits(Verify, stream.Writable) + +Verify.prototype._write = function _write (data, _, done) { + this._hash.update(data) + done() +} + +Verify.prototype.update = function update (data, enc) { + if (typeof data === 'string') data = new Buffer(data, enc) + + this._hash.update(data) + return this +} + +Verify.prototype.verify = function verifyMethod (key, sig, enc) { + if (typeof sig === 'string') sig = new Buffer(sig, enc) + + this.end() + var hash = this._hash.digest() + return verify(sig, hash, key, this._signType, this._tag) +} + +function createSign (algorithm) { + return new Sign(algorithm) +} + +function createVerify (algorithm) { + return new Verify(algorithm) +} + +module.exports = { + Sign: createSign, + Verify: createVerify, + createSign: createSign, + createVerify: createVerify +} + +}).call(this,require("buffer").Buffer) +},{"./algorithms.json":41,"./sign":44,"./verify":45,"buffer":47,"create-hash":51,"inherits":101,"stream":151}],44:[function(require,module,exports){ +(function (Buffer){ +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var createHmac = require('create-hmac') +var crt = require('browserify-rsa') +var EC = require('elliptic').ec +var BN = require('bn.js') +var parseKeys = require('parse-asn1') +var curves = require('./curves.json') + +function sign (hash, key, hashType, signType, tag) { + var priv = parseKeys(key) + if (priv.curve) { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') + return ecSign(hash, priv) + } else if (priv.type === 'dsa') { + if (signType !== 'dsa') throw new Error('wrong private key type') + return dsaSign(hash, priv, hashType) + } else { + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') + } + hash = Buffer.concat([tag, hash]) + var len = priv.modulus.byteLength() + var pad = [ 0, 1 ] + while (hash.length + pad.length + 1 < len) pad.push(0xff) + pad.push(0x00) + var i = -1 + while (++i < hash.length) pad.push(hash[i]) + + var out = crt(pad, priv) + return out +} + +function ecSign (hash, priv) { + var curveId = curves[priv.curve.join('.')] + if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.')) + + var curve = new EC(curveId) + var key = curve.keyFromPrivate(priv.privateKey) + var out = key.sign(hash) + + return new Buffer(out.toDER()) +} + +function dsaSign (hash, priv, algo) { + var x = priv.params.priv_key + var p = priv.params.p + var q = priv.params.q + var g = priv.params.g + var r = new BN(0) + var k + var H = bits2int(hash, q).mod(q) + var s = false + var kv = getKey(x, q, hash, algo) + while (s === false) { + k = makeKey(q, kv, algo) + r = makeR(g, k, p, q) + s = k.invm(q).imul(H.add(x.mul(r))).mod(q) + if (s.cmpn(0) === 0) { + s = false + r = new BN(0) + } + } + return toDER(r, s) +} + +function toDER (r, s) { + r = r.toArray() + s = s.toArray() + + // Pad values + if (r[0] & 0x80) r = [ 0 ].concat(r) + if (s[0] & 0x80) s = [ 0 ].concat(s) + + var total = r.length + s.length + 4 + var res = [ 0x30, total, 0x02, r.length ] + res = res.concat(r, [ 0x02, s.length ], s) + return new Buffer(res) +} + +function getKey (x, q, hash, algo) { + x = new Buffer(x.toArray()) + if (x.length < q.byteLength()) { + var zeros = new Buffer(q.byteLength() - x.length) + zeros.fill(0) + x = Buffer.concat([ zeros, x ]) + } + var hlen = hash.length + var hbits = bits2octets(hash, q) + var v = new Buffer(hlen) + v.fill(1) + var k = new Buffer(hlen) + k.fill(0) + k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest() + v = createHmac(algo, k).update(v).digest() + k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest() + v = createHmac(algo, k).update(v).digest() + return { k: k, v: v } +} + +function bits2int (obits, q) { + var bits = new BN(obits) + var shift = (obits.length << 3) - q.bitLength() + if (shift > 0) bits.ishrn(shift) + return bits +} + +function bits2octets (bits, q) { + bits = bits2int(bits, q) + bits = bits.mod(q) + var out = new Buffer(bits.toArray()) + if (out.length < q.byteLength()) { + var zeros = new Buffer(q.byteLength() - out.length) + zeros.fill(0) + out = Buffer.concat([ zeros, out ]) + } + return out +} + +function makeKey (q, kv, algo) { + var t + var k + + do { + t = new Buffer(0) + + while (t.length * 8 < q.bitLength()) { + kv.v = createHmac(algo, kv.k).update(kv.v).digest() + t = Buffer.concat([ t, kv.v ]) + } + + k = bits2int(t, q) + kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest() + kv.v = createHmac(algo, kv.k).update(kv.v).digest() + } while (k.cmp(q) !== -1) + + return k +} + +function makeR (g, k, p, q) { + return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q) +} + +module.exports = sign +module.exports.getKey = getKey +module.exports.makeKey = makeKey + +}).call(this,require("buffer").Buffer) +},{"./curves.json":42,"bn.js":16,"browserify-rsa":39,"buffer":47,"create-hmac":53,"elliptic":66,"parse-asn1":112}],45:[function(require,module,exports){ +(function (Buffer){ +// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js +var BN = require('bn.js') +var EC = require('elliptic').ec +var parseKeys = require('parse-asn1') +var curves = require('./curves.json') + +function verify (sig, hash, key, signType, tag) { + var pub = parseKeys(key) + if (pub.type === 'ec') { + // rsa keys can be interpreted as ecdsa ones in openssl + if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') + return ecVerify(sig, hash, pub) + } else if (pub.type === 'dsa') { + if (signType !== 'dsa') throw new Error('wrong public key type') + return dsaVerify(sig, hash, pub) + } else { + if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') + } + hash = Buffer.concat([tag, hash]) + var len = pub.modulus.byteLength() + var pad = [ 1 ] + var padNum = 0 + while (hash.length + pad.length + 2 < len) { + pad.push(0xff) + padNum++ + } + pad.push(0x00) + var i = -1 + while (++i < hash.length) { + pad.push(hash[i]) + } + pad = new Buffer(pad) + var red = BN.mont(pub.modulus) + sig = new BN(sig).toRed(red) + + sig = sig.redPow(new BN(pub.publicExponent)) + sig = new Buffer(sig.fromRed().toArray()) + var out = padNum < 8 ? 1 : 0 + len = Math.min(sig.length, pad.length) + if (sig.length !== pad.length) out = 1 + + i = -1 + while (++i < len) out |= sig[i] ^ pad[i] + return out === 0 +} + +function ecVerify (sig, hash, pub) { + var curveId = curves[pub.data.algorithm.curve.join('.')] + if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')) + + var curve = new EC(curveId) + var pubkey = pub.data.subjectPrivateKey.data + + return curve.verify(hash, sig, pubkey) +} + +function dsaVerify (sig, hash, pub) { + var p = pub.data.p + var q = pub.data.q + var g = pub.data.g + var y = pub.data.pub_key + var unpacked = parseKeys.signature.decode(sig, 'der') + var s = unpacked.s + var r = unpacked.r + checkValue(s, q) + checkValue(r, q) + var montp = BN.mont(p) + var w = s.invm(q) + var v = g.toRed(montp) + .redPow(new BN(hash).mul(w).mod(q)) + .fromRed() + .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) + .mod(p) + .mod(q) + return v.cmp(r) === 0 +} + +function checkValue (b, q) { + if (b.cmpn(0) <= 0) throw new Error('invalid sig') + if (b.cmp(q) >= q) throw new Error('invalid sig') +} + +module.exports = verify + +}).call(this,require("buffer").Buffer) +},{"./curves.json":42,"bn.js":16,"buffer":47,"elliptic":66,"parse-asn1":112}],46:[function(require,module,exports){ +(function (Buffer){ +module.exports = function xor (a, b) { + var length = Math.min(a.length, b.length) + var buffer = new Buffer(length) + + for (var i = 0; i < length; ++i) { + buffer[i] = a[i] ^ b[i] + } + + return buffer +} + +}).call(this,require("buffer").Buffer) +},{"buffer":47}],47:[function(require,module,exports){ +(function (Buffer){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an 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+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * 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) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species != null && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value) + } + + if (value == null) { + throw TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof 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(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(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(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.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 === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + 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 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.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 (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf) + } + 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 (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + 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 mustMatch ? -1 : 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 'latin1': + case 'binary': + return latin1Slice(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 + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +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.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +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 + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + 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 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + 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 i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +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 + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(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 latin1Write (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 + } + } 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 'latin1': + case 'binary': + return latin1Write(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 latin1Slice (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 = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + 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) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + 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) { + offset = offset >>> 0 + 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) { + offset = offset >>> 0 + 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) { + offset = offset >>> 0 + 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) { + offset = offset >>> 0 + 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) { + offset = offset >>> 0 + 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) { + offset = offset >>> 0 + 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) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + 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) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + 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) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + 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) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + 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 (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) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + 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) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + 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) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + 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 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + 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) { + value = +value + offset = offset >>> 0 + 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) { + value = +value + offset = offset >>> 0 + 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 (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + 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('Index out of range') + 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 + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + 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 (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) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } 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 + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + 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 takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().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 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 +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +}).call(this,require("buffer").Buffer) +},{"base64-js":15,"buffer":47,"ieee754":100}],48:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer +var Transform = require('stream').Transform +var StringDecoder = require('string_decoder').StringDecoder +var inherits = require('inherits') + +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + if (this._final) { + this.__final = this._final + this._final = null + } + this._decoder = null + this._encoding = null +} +inherits(CipherBase, Transform) + +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc) + } + + var outData = this._update(data) + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this.__final()) + } catch (e) { + err = e + } + + done(err) +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0) + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + + return out +} + +module.exports = CipherBase + +},{"inherits":101,"safe-buffer":142,"stream":151,"string_decoder":152}],49:[function(require,module,exports){ +(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); +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":102}],50:[function(require,module,exports){ +(function (Buffer){ +var elliptic = require('elliptic') +var BN = require('bn.js') + +module.exports = function createECDH (curve) { + return new ECDH(curve) +} + +var aliases = { + secp256k1: { + name: 'secp256k1', + byteLength: 32 + }, + secp224r1: { + name: 'p224', + byteLength: 28 + }, + prime256v1: { + name: 'p256', + byteLength: 32 + }, + prime192v1: { + name: 'p192', + byteLength: 24 + }, + ed25519: { + name: 'ed25519', + byteLength: 32 + }, + secp384r1: { + name: 'p384', + byteLength: 48 + }, + secp521r1: { + name: 'p521', + byteLength: 66 + } +} + +aliases.p224 = aliases.secp224r1 +aliases.p256 = aliases.secp256r1 = aliases.prime256v1 +aliases.p192 = aliases.secp192r1 = aliases.prime192v1 +aliases.p384 = aliases.secp384r1 +aliases.p521 = aliases.secp521r1 + +function ECDH (curve) { + this.curveType = aliases[curve] + if (!this.curveType) { + this.curveType = { + name: curve + } + } + this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap + this.keys = void 0 +} + +ECDH.prototype.generateKeys = function (enc, format) { + this.keys = this.curve.genKeyPair() + return this.getPublicKey(enc, format) +} + +ECDH.prototype.computeSecret = function (other, inenc, enc) { + inenc = inenc || 'utf8' + if (!Buffer.isBuffer(other)) { + other = new Buffer(other, inenc) + } + var otherPub = this.curve.keyFromPublic(other).getPublic() + var out = otherPub.mul(this.keys.getPrivate()).getX() + return formatReturnValue(out, enc, this.curveType.byteLength) +} + +ECDH.prototype.getPublicKey = function (enc, format) { + var key = this.keys.getPublic(format === 'compressed', true) + if (format === 'hybrid') { + if (key[key.length - 1] % 2) { + key[0] = 7 + } else { + key[0] = 6 + } + } + return formatReturnValue(key, enc) +} + +ECDH.prototype.getPrivateKey = function (enc) { + return formatReturnValue(this.keys.getPrivate(), enc) +} + +ECDH.prototype.setPublicKey = function (pub, enc) { + enc = enc || 'utf8' + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc) + } + this.keys._importPublic(pub) + return this +} + +ECDH.prototype.setPrivateKey = function (priv, enc) { + enc = enc || 'utf8' + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc) + } + + var _priv = new BN(priv) + _priv = _priv.toString(16) + this.keys = this.curve.genKeyPair() + this.keys._importPrivate(_priv) + return this +} + +function formatReturnValue (bn, enc, len) { + if (!Array.isArray(bn)) { + bn = bn.toArray() + } + var buf = new Buffer(bn) + if (len && buf.length < len) { + var zeros = new Buffer(len - buf.length) + zeros.fill(0) + buf = Buffer.concat([zeros, buf]) + } + if (!enc) { + return buf + } else { + return buf.toString(enc) + } +} + +}).call(this,require("buffer").Buffer) +},{"bn.js":16,"buffer":47,"elliptic":66}],51:[function(require,module,exports){ +'use strict' +var inherits = require('inherits') +var MD5 = require('md5.js') +var RIPEMD160 = require('ripemd160') +var sha = require('sha.js') +var Base = require('cipher-base') + +function Hash (hash) { + Base.call(this, 'digest') + + this._hash = hash +} + +inherits(Hash, Base) + +Hash.prototype._update = function (data) { + this._hash.update(data) +} + +Hash.prototype._final = function () { + return this._hash.digest() +} + +module.exports = function createHash (alg) { + alg = alg.toLowerCase() + if (alg === 'md5') return new MD5() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() + + return new Hash(sha(alg)) +} + +},{"cipher-base":48,"inherits":101,"md5.js":104,"ripemd160":141,"sha.js":144}],52:[function(require,module,exports){ +var MD5 = require('md5.js') + +module.exports = function (buffer) { + return new MD5().update(buffer).digest() +} + +},{"md5.js":104}],53:[function(require,module,exports){ +'use strict' +var inherits = require('inherits') +var Legacy = require('./legacy') +var Base = require('cipher-base') +var Buffer = require('safe-buffer').Buffer +var md5 = require('create-hash/md5') +var RIPEMD160 = require('ripemd160') + +var sha = require('sha.js') + +var ZEROS = Buffer.alloc(128) + +function Hmac (alg, key) { + Base.call(this, 'digest') + if (typeof key === 'string') { + key = Buffer.from(key) + } + + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + this._alg = alg + this._key = key + if (key.length > blocksize) { + var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + key = hash.update(key).digest() + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) + this._hash.update(ipad) +} + +inherits(Hmac, Base) + +Hmac.prototype._update = function (data) { + this._hash.update(data) +} + +Hmac.prototype._final = function () { + var h = this._hash.digest() + var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) + return hash.update(this._opad).update(h).digest() +} + +module.exports = function createHmac (alg, key) { + alg = alg.toLowerCase() + if (alg === 'rmd160' || alg === 'ripemd160') { + return new Hmac('rmd160', key) + } + if (alg === 'md5') { + return new Legacy(md5, key) + } + return new Hmac(alg, key) +} + +},{"./legacy":54,"cipher-base":48,"create-hash/md5":52,"inherits":101,"ripemd160":141,"safe-buffer":142,"sha.js":144}],54:[function(require,module,exports){ +'use strict' +var inherits = require('inherits') +var Buffer = require('safe-buffer').Buffer + +var Base = require('cipher-base') + +var ZEROS = Buffer.alloc(128) +var blocksize = 64 + +function Hmac (alg, key) { + Base.call(this, 'digest') + if (typeof key === 'string') { + key = Buffer.from(key) + } + + this._alg = alg + this._key = key + + if (key.length > blocksize) { + key = alg(key) + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = this._ipad = Buffer.allocUnsafe(blocksize) + var opad = this._opad = Buffer.allocUnsafe(blocksize) + + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + this._hash = [ipad] +} + +inherits(Hmac, Base) + +Hmac.prototype._update = function (data) { + this._hash.push(data) +} + +Hmac.prototype._final = function () { + var h = this._alg(Buffer.concat(this._hash)) + return this._alg(Buffer.concat([this._opad, h])) +} +module.exports = Hmac + +},{"cipher-base":48,"inherits":101,"safe-buffer":142}],55:[function(require,module,exports){ +'use strict' + +exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes') +exports.createHash = exports.Hash = require('create-hash') +exports.createHmac = exports.Hmac = require('create-hmac') + +var algos = require('browserify-sign/algos') +var algoKeys = Object.keys(algos) +var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) +exports.getHashes = function () { + return hashes +} + +var p = require('pbkdf2') +exports.pbkdf2 = p.pbkdf2 +exports.pbkdf2Sync = p.pbkdf2Sync + +var aes = require('browserify-cipher') + +exports.Cipher = aes.Cipher +exports.createCipher = aes.createCipher +exports.Cipheriv = aes.Cipheriv +exports.createCipheriv = aes.createCipheriv +exports.Decipher = aes.Decipher +exports.createDecipher = aes.createDecipher +exports.Decipheriv = aes.Decipheriv +exports.createDecipheriv = aes.createDecipheriv +exports.getCiphers = aes.getCiphers +exports.listCiphers = aes.listCiphers + +var dh = require('diffie-hellman') + +exports.DiffieHellmanGroup = dh.DiffieHellmanGroup +exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup +exports.getDiffieHellman = dh.getDiffieHellman +exports.createDiffieHellman = dh.createDiffieHellman +exports.DiffieHellman = dh.DiffieHellman + +var sign = require('browserify-sign') + +exports.createSign = sign.createSign +exports.Sign = sign.Sign +exports.createVerify = sign.createVerify +exports.Verify = sign.Verify + +exports.createECDH = require('create-ecdh') + +var publicEncrypt = require('public-encrypt') + +exports.publicEncrypt = publicEncrypt.publicEncrypt +exports.privateEncrypt = publicEncrypt.privateEncrypt +exports.publicDecrypt = publicEncrypt.publicDecrypt +exports.privateDecrypt = publicEncrypt.privateDecrypt + +// the least I can do is make error messages for the rest of the node.js/crypto api. +// ;[ +// 'createCredentials' +// ].forEach(function (name) { +// exports[name] = function () { +// throw new Error([ +// 'sorry, ' + name + ' is not implemented yet', +// 'we accept pull requests', +// 'https://github.com/crypto-browserify/crypto-browserify' +// ].join('\n')) +// } +// }) + +var rf = require('randomfill') + +exports.randomFill = rf.randomFill +exports.randomFillSync = rf.randomFillSync + +exports.createCredentials = function () { + throw new Error([ + 'sorry, createCredentials is not implemented yet', + 'we accept pull requests', + 'https://github.com/crypto-browserify/crypto-browserify' + ].join('\n')) +} + +exports.constants = { + 'DH_CHECK_P_NOT_SAFE_PRIME': 2, + 'DH_CHECK_P_NOT_PRIME': 1, + 'DH_UNABLE_TO_CHECK_GENERATOR': 4, + 'DH_NOT_SUITABLE_GENERATOR': 8, + 'NPN_ENABLED': 1, + 'ALPN_ENABLED': 1, + 'RSA_PKCS1_PADDING': 1, + 'RSA_SSLV23_PADDING': 2, + 'RSA_NO_PADDING': 3, + 'RSA_PKCS1_OAEP_PADDING': 4, + 'RSA_X931_PADDING': 5, + 'RSA_PKCS1_PSS_PADDING': 6, + 'POINT_CONVERSION_COMPRESSED': 2, + 'POINT_CONVERSION_UNCOMPRESSED': 4, + 'POINT_CONVERSION_HYBRID': 6 +} + +},{"browserify-cipher":36,"browserify-sign":43,"browserify-sign/algos":40,"create-ecdh":50,"create-hash":51,"create-hmac":53,"diffie-hellman":62,"pbkdf2":113,"public-encrypt":120,"randombytes":126,"randomfill":127}],56:[function(require,module,exports){ +'use strict'; + +exports.utils = require('./des/utils'); +exports.Cipher = require('./des/cipher'); +exports.DES = require('./des/des'); +exports.CBC = require('./des/cbc'); +exports.EDE = require('./des/ede'); + +},{"./des/cbc":57,"./des/cipher":58,"./des/des":59,"./des/ede":60,"./des/utils":61}],57:[function(require,module,exports){ +'use strict'; + +var assert = require('minimalistic-assert'); +var inherits = require('inherits'); + +var proto = {}; + +function CBCState(iv) { + assert.equal(iv.length, 8, 'Invalid IV length'); + + this.iv = new Array(8); + for (var i = 0; i < this.iv.length; i++) + this.iv[i] = iv[i]; +} + +function instantiate(Base) { + function CBC(options) { + Base.call(this, options); + this._cbcInit(); + } + inherits(CBC, Base); + + var keys = Object.keys(proto); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + CBC.prototype[key] = proto[key]; + } + + CBC.create = function create(options) { + return new CBC(options); + }; + + return CBC; +} + +exports.instantiate = instantiate; + +proto._cbcInit = function _cbcInit() { + var state = new CBCState(this.options.iv); + this._cbcState = state; +}; + +proto._update = function _update(inp, inOff, out, outOff) { + var state = this._cbcState; + var superProto = this.constructor.super_.prototype; + + var iv = state.iv; + if (this.type === 'encrypt') { + for (var i = 0; i < this.blockSize; i++) + iv[i] ^= inp[inOff + i]; + + superProto._update.call(this, iv, 0, out, outOff); + + for (var i = 0; i < this.blockSize; i++) + iv[i] = out[outOff + i]; + } else { + superProto._update.call(this, inp, inOff, out, outOff); + + for (var i = 0; i < this.blockSize; i++) + out[outOff + i] ^= iv[i]; + + for (var i = 0; i < this.blockSize; i++) + iv[i] = inp[inOff + i]; + } +}; + +},{"inherits":101,"minimalistic-assert":106}],58:[function(require,module,exports){ +'use strict'; + +var assert = require('minimalistic-assert'); + +function Cipher(options) { + this.options = options; + + this.type = this.options.type; + this.blockSize = 8; + this._init(); + + this.buffer = new Array(this.blockSize); + this.bufferOff = 0; +} +module.exports = Cipher; + +Cipher.prototype._init = function _init() { + // Might be overrided +}; + +Cipher.prototype.update = function update(data) { + if (data.length === 0) + return []; + + if (this.type === 'decrypt') + return this._updateDecrypt(data); + else + return this._updateEncrypt(data); +}; + +Cipher.prototype._buffer = function _buffer(data, off) { + // Append data to buffer + var min = Math.min(this.buffer.length - this.bufferOff, data.length - off); + for (var i = 0; i < min; i++) + this.buffer[this.bufferOff + i] = data[off + i]; + this.bufferOff += min; + + // Shift next + return min; +}; + +Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { + this._update(this.buffer, 0, out, off); + this.bufferOff = 0; + return this.blockSize; +}; + +Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { + var inputOff = 0; + var outputOff = 0; + + var count = ((this.bufferOff + data.length) / this.blockSize) | 0; + var out = new Array(count * this.blockSize); + + if (this.bufferOff !== 0) { + inputOff += this._buffer(data, inputOff); + + if (this.bufferOff === this.buffer.length) + outputOff += this._flushBuffer(out, outputOff); + } + + // Write blocks + var max = data.length - ((data.length - inputOff) % this.blockSize); + for (; inputOff < max; inputOff += this.blockSize) { + this._update(data, inputOff, out, outputOff); + outputOff += this.blockSize; + } + + // Queue rest + for (; inputOff < data.length; inputOff++, this.bufferOff++) + this.buffer[this.bufferOff] = data[inputOff]; + + return out; +}; + +Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { + var inputOff = 0; + var outputOff = 0; + + var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; + var out = new Array(count * this.blockSize); + + // TODO(indutny): optimize it, this is far from optimal + for (; count > 0; count--) { + inputOff += this._buffer(data, inputOff); + outputOff += this._flushBuffer(out, outputOff); + } + + // Buffer rest of the input + inputOff += this._buffer(data, inputOff); + + return out; +}; + +Cipher.prototype.final = function final(buffer) { + var first; + if (buffer) + first = this.update(buffer); + + var last; + if (this.type === 'encrypt') + last = this._finalEncrypt(); + else + last = this._finalDecrypt(); + + if (first) + return first.concat(last); + else + return last; +}; + +Cipher.prototype._pad = function _pad(buffer, off) { + if (off === 0) + return false; + + while (off < buffer.length) + buffer[off++] = 0; + + return true; +}; + +Cipher.prototype._finalEncrypt = function _finalEncrypt() { + if (!this._pad(this.buffer, this.bufferOff)) + return []; + + var out = new Array(this.blockSize); + this._update(this.buffer, 0, out, 0); + return out; +}; + +Cipher.prototype._unpad = function _unpad(buffer) { + return buffer; +}; + +Cipher.prototype._finalDecrypt = function _finalDecrypt() { + assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); + var out = new Array(this.blockSize); + this._flushBuffer(out, 0); + + return this._unpad(out); +}; + +},{"minimalistic-assert":106}],59:[function(require,module,exports){ +'use strict'; + +var assert = require('minimalistic-assert'); +var inherits = require('inherits'); + +var des = require('../des'); +var utils = des.utils; +var Cipher = des.Cipher; + +function DESState() { + this.tmp = new Array(2); + this.keys = null; +} + +function DES(options) { + Cipher.call(this, options); + + var state = new DESState(); + this._desState = state; + + this.deriveKeys(state, options.key); +} +inherits(DES, Cipher); +module.exports = DES; + +DES.create = function create(options) { + return new DES(options); +}; + +var shiftTable = [ + 1, 1, 2, 2, 2, 2, 2, 2, + 1, 2, 2, 2, 2, 2, 2, 1 +]; + +DES.prototype.deriveKeys = function deriveKeys(state, key) { + state.keys = new Array(16 * 2); + + assert.equal(key.length, this.blockSize, 'Invalid key length'); + + var kL = utils.readUInt32BE(key, 0); + var kR = utils.readUInt32BE(key, 4); + + utils.pc1(kL, kR, state.tmp, 0); + kL = state.tmp[0]; + kR = state.tmp[1]; + for (var i = 0; i < state.keys.length; i += 2) { + var shift = shiftTable[i >>> 1]; + kL = utils.r28shl(kL, shift); + kR = utils.r28shl(kR, shift); + utils.pc2(kL, kR, state.keys, i); + } +}; + +DES.prototype._update = function _update(inp, inOff, out, outOff) { + var state = this._desState; + + var l = utils.readUInt32BE(inp, inOff); + var r = utils.readUInt32BE(inp, inOff + 4); + + // Initial Permutation + utils.ip(l, r, state.tmp, 0); + l = state.tmp[0]; + r = state.tmp[1]; + + if (this.type === 'encrypt') + this._encrypt(state, l, r, state.tmp, 0); + else + this._decrypt(state, l, r, state.tmp, 0); + + l = state.tmp[0]; + r = state.tmp[1]; + + utils.writeUInt32BE(out, l, outOff); + utils.writeUInt32BE(out, r, outOff + 4); +}; + +DES.prototype._pad = function _pad(buffer, off) { + var value = buffer.length - off; + for (var i = off; i < buffer.length; i++) + buffer[i] = value; + + return true; +}; + +DES.prototype._unpad = function _unpad(buffer) { + var pad = buffer[buffer.length - 1]; + for (var i = buffer.length - pad; i < buffer.length; i++) + assert.equal(buffer[i], pad); + + return buffer.slice(0, buffer.length - pad); +}; + +DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { + var l = lStart; + var r = rStart; + + // Apply f() x16 times + for (var i = 0; i < state.keys.length; i += 2) { + var keyL = state.keys[i]; + var keyR = state.keys[i + 1]; + + // f(r, k) + utils.expand(r, state.tmp, 0); + + keyL ^= state.tmp[0]; + keyR ^= state.tmp[1]; + var s = utils.substitute(keyL, keyR); + var f = utils.permute(s); + + var t = r; + r = (l ^ f) >>> 0; + l = t; + } + + // Reverse Initial Permutation + utils.rip(r, l, out, off); +}; + +DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { + var l = rStart; + var r = lStart; + + // Apply f() x16 times + for (var i = state.keys.length - 2; i >= 0; i -= 2) { + var keyL = state.keys[i]; + var keyR = state.keys[i + 1]; + + // f(r, k) + utils.expand(l, state.tmp, 0); + + keyL ^= state.tmp[0]; + keyR ^= state.tmp[1]; + var s = utils.substitute(keyL, keyR); + var f = utils.permute(s); + + var t = l; + l = (r ^ f) >>> 0; + r = t; + } + + // Reverse Initial Permutation + utils.rip(l, r, out, off); +}; + +},{"../des":56,"inherits":101,"minimalistic-assert":106}],60:[function(require,module,exports){ +'use strict'; + +var assert = require('minimalistic-assert'); +var inherits = require('inherits'); + +var des = require('../des'); +var Cipher = des.Cipher; +var DES = des.DES; + +function EDEState(type, key) { + assert.equal(key.length, 24, 'Invalid key length'); + + var k1 = key.slice(0, 8); + var k2 = key.slice(8, 16); + var k3 = key.slice(16, 24); + + if (type === 'encrypt') { + this.ciphers = [ + DES.create({ type: 'encrypt', key: k1 }), + DES.create({ type: 'decrypt', key: k2 }), + DES.create({ type: 'encrypt', key: k3 }) + ]; + } else { + this.ciphers = [ + DES.create({ type: 'decrypt', key: k3 }), + DES.create({ type: 'encrypt', key: k2 }), + DES.create({ type: 'decrypt', key: k1 }) + ]; + } +} + +function EDE(options) { + Cipher.call(this, options); + + var state = new EDEState(this.type, this.options.key); + this._edeState = state; +} +inherits(EDE, Cipher); + +module.exports = EDE; + +EDE.create = function create(options) { + return new EDE(options); +}; + +EDE.prototype._update = function _update(inp, inOff, out, outOff) { + var state = this._edeState; + + state.ciphers[0]._update(inp, inOff, out, outOff); + state.ciphers[1]._update(out, outOff, out, outOff); + state.ciphers[2]._update(out, outOff, out, outOff); +}; + +EDE.prototype._pad = DES.prototype._pad; +EDE.prototype._unpad = DES.prototype._unpad; + +},{"../des":56,"inherits":101,"minimalistic-assert":106}],61:[function(require,module,exports){ +'use strict'; + +exports.readUInt32BE = function readUInt32BE(bytes, off) { + var res = (bytes[0 + off] << 24) | + (bytes[1 + off] << 16) | + (bytes[2 + off] << 8) | + bytes[3 + off]; + return res >>> 0; +}; + +exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) { + bytes[0 + off] = value >>> 24; + bytes[1 + off] = (value >>> 16) & 0xff; + bytes[2 + off] = (value >>> 8) & 0xff; + bytes[3 + off] = value & 0xff; +}; + +exports.ip = function ip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >>> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + + for (var i = 6; i >= 0; i -= 2) { + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + } + for (var j = 1; j <= 25; j += 8) { + outR <<= 1; + outR |= (inL >>> (j + i)) & 1; + } + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.rip = function rip(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + for (var i = 0; i < 4; i++) { + for (var j = 24; j >= 0; j -= 8) { + outL <<= 1; + outL |= (inR >>> (j + i)) & 1; + outL <<= 1; + outL |= (inL >>> (j + i)) & 1; + } + } + for (var i = 4; i < 8; i++) { + for (var j = 24; j >= 0; j -= 8) { + outR <<= 1; + outR |= (inR >>> (j + i)) & 1; + outR <<= 1; + outR |= (inL >>> (j + i)) & 1; + } + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.pc1 = function pc1(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + // 7, 15, 23, 31, 39, 47, 55, 63 + // 6, 14, 22, 30, 39, 47, 55, 63 + // 5, 13, 21, 29, 39, 47, 55, 63 + // 4, 12, 20, 28 + for (var i = 7; i >= 5; i--) { + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outL <<= 1; + outL |= (inR >> (j + i)) & 1; + } + + // 1, 9, 17, 25, 33, 41, 49, 57 + // 2, 10, 18, 26, 34, 42, 50, 58 + // 3, 11, 19, 27, 35, 43, 51, 59 + // 36, 44, 52, 60 + for (var i = 1; i <= 3; i++) { + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inR >> (j + i)) & 1; + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + } + for (var j = 0; j <= 24; j += 8) { + outR <<= 1; + outR |= (inL >> (j + i)) & 1; + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.r28shl = function r28shl(num, shift) { + return ((num << shift) & 0xfffffff) | (num >>> (28 - shift)); +}; + +var pc2table = [ + // inL => outL + 14, 11, 17, 4, 27, 23, 25, 0, + 13, 22, 7, 18, 5, 9, 16, 24, + 2, 20, 12, 21, 1, 8, 15, 26, + + // inR => outR + 15, 4, 25, 19, 9, 1, 26, 16, + 5, 11, 23, 8, 12, 7, 17, 0, + 22, 3, 10, 14, 6, 20, 27, 24 +]; + +exports.pc2 = function pc2(inL, inR, out, off) { + var outL = 0; + var outR = 0; + + var len = pc2table.length >>> 1; + for (var i = 0; i < len; i++) { + outL <<= 1; + outL |= (inL >>> pc2table[i]) & 0x1; + } + for (var i = len; i < pc2table.length; i++) { + outR <<= 1; + outR |= (inR >>> pc2table[i]) & 0x1; + } + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +exports.expand = function expand(r, out, off) { + var outL = 0; + var outR = 0; + + outL = ((r & 1) << 5) | (r >>> 27); + for (var i = 23; i >= 15; i -= 4) { + outL <<= 6; + outL |= (r >>> i) & 0x3f; + } + for (var i = 11; i >= 3; i -= 4) { + outR |= (r >>> i) & 0x3f; + outR <<= 6; + } + outR |= ((r & 0x1f) << 1) | (r >>> 31); + + out[off + 0] = outL >>> 0; + out[off + 1] = outR >>> 0; +}; + +var sTable = [ + 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, + 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, + 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, + 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, + + 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, + 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, + 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, + 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, + + 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, + 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, + 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, + 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, + + 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, + 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, + 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, + 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, + + 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, + 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, + 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, + 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, + + 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, + 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, + 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, + 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, + + 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, + 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, + 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, + 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, + + 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, + 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, + 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, + 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 +]; + +exports.substitute = function substitute(inL, inR) { + var out = 0; + for (var i = 0; i < 4; i++) { + var b = (inL >>> (18 - i * 6)) & 0x3f; + var sb = sTable[i * 0x40 + b]; + + out <<= 4; + out |= sb; + } + for (var i = 0; i < 4; i++) { + var b = (inR >>> (18 - i * 6)) & 0x3f; + var sb = sTable[4 * 0x40 + i * 0x40 + b]; + + out <<= 4; + out |= sb; + } + return out >>> 0; +}; + +var permuteTable = [ + 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, + 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7 +]; + +exports.permute = function permute(num) { + var out = 0; + for (var i = 0; i < permuteTable.length; i++) { + out <<= 1; + out |= (num >>> permuteTable[i]) & 0x1; + } + return out >>> 0; +}; + +exports.padSplit = function padSplit(num, size, group) { + var str = num.toString(2); + while (str.length < size) + str = '0' + str; + + var out = []; + for (var i = 0; i < size; i += group) + out.push(str.slice(i, i + group)); + return out.join(' '); +}; + +},{}],62:[function(require,module,exports){ +(function (Buffer){ +var generatePrime = require('./lib/generatePrime') +var primes = require('./lib/primes.json') + +var DH = require('./lib/dh') + +function getDiffieHellman (mod) { + var prime = new Buffer(primes[mod].prime, 'hex') + var gen = new Buffer(primes[mod].gen, 'hex') + + return new DH(prime, gen) +} + +var ENCODINGS = { + 'binary': true, 'hex': true, 'base64': true +} + +function createDiffieHellman (prime, enc, generator, genc) { + if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { + return createDiffieHellman(prime, 'binary', enc, generator) + } + + enc = enc || 'binary' + genc = genc || 'binary' + generator = generator || new Buffer([2]) + + if (!Buffer.isBuffer(generator)) { + generator = new Buffer(generator, genc) + } + + if (typeof prime === 'number') { + return new DH(generatePrime(prime, generator), generator, true) + } + + if (!Buffer.isBuffer(prime)) { + prime = new Buffer(prime, enc) + } + + return new DH(prime, generator, true) +} + +exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman +exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman + +}).call(this,require("buffer").Buffer) +},{"./lib/dh":63,"./lib/generatePrime":64,"./lib/primes.json":65,"buffer":47}],63:[function(require,module,exports){ +(function (Buffer){ +var BN = require('bn.js'); +var MillerRabin = require('miller-rabin'); +var millerRabin = new MillerRabin(); +var TWENTYFOUR = new BN(24); +var ELEVEN = new BN(11); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var primes = require('./generatePrime'); +var randomBytes = require('randombytes'); +module.exports = DH; + +function setPublicKey(pub, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(pub)) { + pub = new Buffer(pub, enc); + } + this._pub = new BN(pub); + return this; +} + +function setPrivateKey(priv, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(priv)) { + priv = new Buffer(priv, enc); + } + this._priv = new BN(priv); + return this; +} + +var primeCache = {}; +function checkPrime(prime, generator) { + var gen = generator.toString('hex'); + var hex = [gen, prime.toString(16)].join('_'); + if (hex in primeCache) { + return primeCache[hex]; + } + var error = 0; + + if (prime.isEven() || + !primes.simpleSieve || + !primes.fermatTest(prime) || + !millerRabin.test(prime)) { + //not a prime so +1 + error += 1; + + if (gen === '02' || gen === '05') { + // we'd be able to check the generator + // it would fail so +8 + error += 8; + } else { + //we wouldn't be able to test the generator + // so +4 + error += 4; + } + primeCache[hex] = error; + return error; + } + if (!millerRabin.test(prime.shrn(1))) { + //not a safe prime + error += 2; + } + var rem; + switch (gen) { + case '02': + if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { + // unsuidable generator + error += 8; + } + break; + case '05': + rem = prime.mod(TEN); + if (rem.cmp(THREE) && rem.cmp(SEVEN)) { + // prime mod 10 needs to equal 3 or 7 + error += 8; + } + break; + default: + error += 4; + } + primeCache[hex] = error; + return error; +} + +function DH(prime, generator, malleable) { + this.setGenerator(generator); + this.__prime = new BN(prime); + this._prime = BN.mont(this.__prime); + this._primeLen = prime.length; + this._pub = undefined; + this._priv = undefined; + this._primeCode = undefined; + if (malleable) { + this.setPublicKey = setPublicKey; + this.setPrivateKey = setPrivateKey; + } else { + this._primeCode = 8; + } +} +Object.defineProperty(DH.prototype, 'verifyError', { + enumerable: true, + get: function () { + if (typeof this._primeCode !== 'number') { + this._primeCode = checkPrime(this.__prime, this.__gen); + } + return this._primeCode; + } +}); +DH.prototype.generateKeys = function () { + if (!this._priv) { + this._priv = new BN(randomBytes(this._primeLen)); + } + this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); + return this.getPublicKey(); +}; + +DH.prototype.computeSecret = function (other) { + other = new BN(other); + other = other.toRed(this._prime); + var secret = other.redPow(this._priv).fromRed(); + var out = new Buffer(secret.toArray()); + var prime = this.getPrime(); + if (out.length < prime.length) { + var front = new Buffer(prime.length - out.length); + front.fill(0); + out = Buffer.concat([front, out]); + } + return out; +}; + +DH.prototype.getPublicKey = function getPublicKey(enc) { + return formatReturnValue(this._pub, enc); +}; + +DH.prototype.getPrivateKey = function getPrivateKey(enc) { + return formatReturnValue(this._priv, enc); +}; + +DH.prototype.getPrime = function (enc) { + return formatReturnValue(this.__prime, enc); +}; + +DH.prototype.getGenerator = function (enc) { + return formatReturnValue(this._gen, enc); +}; + +DH.prototype.setGenerator = function (gen, enc) { + enc = enc || 'utf8'; + if (!Buffer.isBuffer(gen)) { + gen = new Buffer(gen, enc); + } + this.__gen = gen; + this._gen = new BN(gen); + return this; +}; + +function formatReturnValue(bn, enc) { + var buf = new Buffer(bn.toArray()); + if (!enc) { + return buf; + } else { + return buf.toString(enc); + } +} + +}).call(this,require("buffer").Buffer) +},{"./generatePrime":64,"bn.js":16,"buffer":47,"miller-rabin":105,"randombytes":126}],64:[function(require,module,exports){ +var randomBytes = require('randombytes'); +module.exports = findPrime; +findPrime.simpleSieve = simpleSieve; +findPrime.fermatTest = fermatTest; +var BN = require('bn.js'); +var TWENTYFOUR = new BN(24); +var MillerRabin = require('miller-rabin'); +var millerRabin = new MillerRabin(); +var ONE = new BN(1); +var TWO = new BN(2); +var FIVE = new BN(5); +var SIXTEEN = new BN(16); +var EIGHT = new BN(8); +var TEN = new BN(10); +var THREE = new BN(3); +var SEVEN = new BN(7); +var ELEVEN = new BN(11); +var FOUR = new BN(4); +var TWELVE = new BN(12); +var primes = null; + +function _getPrimes() { + if (primes !== null) + return primes; + + var limit = 0x100000; + var res = []; + res[0] = 2; + for (var i = 1, k = 3; k < limit; k += 2) { + var sqrt = Math.ceil(Math.sqrt(k)); + for (var j = 0; j < i && res[j] <= sqrt; j++) + if (k % res[j] === 0) + break; + + if (i !== j && res[j] <= sqrt) + continue; + + res[i++] = k; + } + primes = res; + return res; +} + +function simpleSieve(p) { + var primes = _getPrimes(); + + for (var i = 0; i < primes.length; i++) + if (p.modn(primes[i]) === 0) { + if (p.cmpn(primes[i]) === 0) { + return true; + } else { + return false; + } + } + + return true; +} + +function fermatTest(p) { + var red = BN.mont(p); + return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; +} + +function findPrime(bits, gen) { + if (bits < 16) { + // this is what openssl does + if (gen === 2 || gen === 5) { + return new BN([0x8c, 0x7b]); + } else { + return new BN([0x8c, 0x27]); + } + } + gen = new BN(gen); + + var num, n2; + + while (true) { + num = new BN(randomBytes(Math.ceil(bits / 8))); + while (num.bitLength() > bits) { + num.ishrn(1); + } + if (num.isEven()) { + num.iadd(ONE); + } + if (!num.testn(1)) { + num.iadd(TWO); + } + if (!gen.cmp(TWO)) { + while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { + num.iadd(FOUR); + } + } else if (!gen.cmp(FIVE)) { + while (num.mod(TEN).cmp(THREE)) { + num.iadd(FOUR); + } + } + n2 = num.shrn(1); + if (simpleSieve(n2) && simpleSieve(num) && + fermatTest(n2) && fermatTest(num) && + millerRabin.test(n2) && millerRabin.test(num)) { + return num; + } + } + +} + +},{"bn.js":16,"miller-rabin":105,"randombytes":126}],65:[function(require,module,exports){ +module.exports={ + "modp1": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" + }, + "modp2": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" + }, + "modp5": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" + }, + "modp14": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" + }, + "modp15": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" + }, + "modp16": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" + }, + "modp17": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" + }, + "modp18": { + "gen": "02", + "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" + } +} +},{}],66:[function(require,module,exports){ +'use strict'; + +var elliptic = exports; + +elliptic.version = require('../package.json').version; +elliptic.utils = require('./elliptic/utils'); +elliptic.rand = require('brorand'); +elliptic.curve = require('./elliptic/curve'); +elliptic.curves = require('./elliptic/curves'); + +// Protocols +elliptic.ec = require('./elliptic/ec'); +elliptic.eddsa = require('./elliptic/eddsa'); + +},{"../package.json":81,"./elliptic/curve":69,"./elliptic/curves":72,"./elliptic/ec":73,"./elliptic/eddsa":76,"./elliptic/utils":80,"brorand":17}],67:[function(require,module,exports){ +'use strict'; + +var BN = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var getNAF = utils.getNAF; +var getJSF = utils.getJSF; +var assert = utils.assert; + +function BaseCurve(type, conf) { + this.type = type; + this.p = new BN(conf.p, 16); + + // Use Montgomery, when there is no fast reduction for the prime + this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); + + // Useful for many curves + this.zero = new BN(0).toRed(this.red); + this.one = new BN(1).toRed(this.red); + this.two = new BN(2).toRed(this.red); + + // Curve configuration, optional + this.n = conf.n && new BN(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + + // Temporary arrays + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); + + // Generalized Greg Maxwell's trick + var adjustCount = this.n && this.p.div(this.n); + if (!adjustCount || adjustCount.cmpn(100) > 0) { + this.redN = null; + } else { + this._maxwellTrick = true; + this.redN = this.n.toRed(this.red); + } +} +module.exports = BaseCurve; + +BaseCurve.prototype.point = function point() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype.validate = function validate() { + throw new Error('Not implemented'); +}; + +BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert(p.precomputed); + var doubles = p._getDoubles(); + + var naf = getNAF(k, 1); + var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + + // Translate into more windowed form + var repr = []; + for (var j = 0; j < naf.length; j += doubles.step) { + var nafW = 0; + for (var k = j + doubles.step - 1; k >= j; k--) + nafW = (nafW << 1) + naf[k]; + repr.push(nafW); + } + + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for (var i = I; i > 0; i--) { + for (var j = 0; j < repr.length; j++) { + var nafW = repr[j]; + if (nafW === i) + b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) + b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); +}; + +BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + + // Precompute window + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + + // Get NAF form + var naf = getNAF(k, w); + + // Add `this`*(N+1) for every w-NAF index + var acc = this.jpoint(null, null, null); + for (var i = naf.length - 1; i >= 0; i--) { + // Count zeroes + for (var k = 0; i >= 0 && naf[i] === 0; i--) + k++; + if (i >= 0) + k++; + acc = acc.dblp(k); + + if (i < 0) + break; + var z = naf[i]; + assert(z !== 0); + if (p.type === 'affine') { + // J +- P + if (z > 0) + acc = acc.mixedAdd(wnd[(z - 1) >> 1]); + else + acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); + } else { + // J +- J + if (z > 0) + acc = acc.add(wnd[(z - 1) >> 1]); + else + acc = acc.add(wnd[(-z - 1) >> 1].neg()); + } + } + return p.type === 'affine' ? acc.toP() : acc; +}; + +BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, + points, + coeffs, + len, + jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + + // Fill all arrays + var max = 0; + for (var i = 0; i < len; i++) { + var p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + + // Comb small window NAFs + for (var i = len - 1; i >= 1; i -= 2) { + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a]); + naf[b] = getNAF(coeffs[b], wndWidth[b]); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + + var comb = [ + points[a], /* 1 */ + null, /* 3 */ + null, /* 5 */ + points[b] /* 7 */ + ]; + + // Try to avoid Projective points, if possible + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + + var index = [ + -3, /* -1 -1 */ + -1, /* -1 0 */ + -5, /* -1 1 */ + -7, /* 0 -1 */ + 0, /* 0 0 */ + 7, /* 0 1 */ + 5, /* 1 -1 */ + 1, /* 1 0 */ + 3 /* 1 1 */ + ]; + + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for (var j = 0; j < max; j++) { + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for (var i = max; i >= 0; i--) { + var k = 0; + + while (i >= 0) { + var zero = true; + for (var j = 0; j < len; j++) { + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) + zero = false; + } + if (!zero) + break; + k++; + i--; + } + if (i >= 0) + k++; + acc = acc.dblp(k); + if (i < 0) + break; + + for (var j = 0; j < len; j++) { + var z = tmp[j]; + var p; + if (z === 0) + continue; + else if (z > 0) + p = wnd[j][(z - 1) >> 1]; + else if (z < 0) + p = wnd[j][(-z - 1) >> 1].neg(); + + if (p.type === 'affine') + acc = acc.mixedAdd(p); + else + acc = acc.add(p); + } + } + // Zeroify references + for (var i = 0; i < len; i++) + wnd[i] = null; + + if (jacobianResult) + return acc; + else + return acc.toP(); +}; + +function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; +} +BaseCurve.BasePoint = BasePoint; + +BasePoint.prototype.eq = function eq(/*other*/) { + throw new Error('Not implemented'); +}; + +BasePoint.prototype.validate = function validate() { + return this.curve.validate(this); +}; + +BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + bytes = utils.toArray(bytes, enc); + + var len = this.p.byteLength(); + + // uncompressed, hybrid-odd, hybrid-even + if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && + bytes.length - 1 === 2 * len) { + if (bytes[0] === 0x06) + assert(bytes[bytes.length - 1] % 2 === 0); + else if (bytes[0] === 0x07) + assert(bytes[bytes.length - 1] % 2 === 1); + + var res = this.point(bytes.slice(1, 1 + len), + bytes.slice(1 + len, 1 + 2 * len)); + + return res; + } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && + bytes.length - 1 === len) { + return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); + } + throw new Error('Unknown point format'); +}; + +BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); +}; + +BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray('be', len); + + if (compact) + return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); + + return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; +}; + +BasePoint.prototype.encode = function encode(enc, compact) { + return utils.encode(this._encode(compact), enc); +}; + +BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) + return this; + + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + + return this; +}; + +BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) + return false; + + var doubles = this.precomputed.doubles; + if (!doubles) + return false; + + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); +}; + +BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + + var doubles = [ this ]; + var acc = this; + for (var i = 0; i < power; i += step) { + for (var j = 0; j < step; j++) + acc = acc.dbl(); + doubles.push(acc); + } + return { + step: step, + points: doubles + }; +}; + +BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + + var res = [ this ]; + var max = (1 << wnd) - 1; + var dbl = max === 1 ? null : this.dbl(); + for (var i = 1; i < max; i++) + res[i] = res[i - 1].add(dbl); + return { + wnd: wnd, + points: res + }; +}; + +BasePoint.prototype._getBeta = function _getBeta() { + return null; +}; + +BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for (var i = 0; i < k; i++) + r = r.dbl(); + return r; +}; + +},{"../../elliptic":66,"bn.js":16}],68:[function(require,module,exports){ +'use strict'; + +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var BN = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var assert = elliptic.utils.assert; + +function EdwardsCurve(conf) { + // NOTE: Important as we are creating point in Base.call() + this.twisted = (conf.a | 0) !== 1; + this.mOneA = this.twisted && (conf.a | 0) === -1; + this.extended = this.mOneA; + + Base.call(this, 'edwards', conf); + + this.a = new BN(conf.a, 16).umod(this.red.m); + this.a = this.a.toRed(this.red); + this.c = new BN(conf.c, 16).toRed(this.red); + this.c2 = this.c.redSqr(); + this.d = new BN(conf.d, 16).toRed(this.red); + this.dd = this.d.redAdd(this.d); + + assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); + this.oneC = (conf.c | 0) === 1; +} +inherits(EdwardsCurve, Base); +module.exports = EdwardsCurve; + +EdwardsCurve.prototype._mulA = function _mulA(num) { + if (this.mOneA) + return num.redNeg(); + else + return this.a.redMul(num); +}; + +EdwardsCurve.prototype._mulC = function _mulC(num) { + if (this.oneC) + return num; + else + return this.c.redMul(num); +}; + +// Just for compatibility with Short curve +EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { + return this.point(x, y, z, t); +}; + +EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var x2 = x.redSqr(); + var rhs = this.c2.redSub(this.a.redMul(x2)); + var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); + + var y2 = rhs.redMul(lhs.redInvm()); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { + y = new BN(y, 16); + if (!y.red) + y = y.toRed(this.red); + + // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) + var y2 = y.redSqr(); + var lhs = y2.redSub(this.c2); + var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); + var x2 = lhs.redMul(rhs.redInvm()); + + if (x2.cmp(this.zero) === 0) { + if (odd) + throw new Error('invalid point'); + else + return this.point(this.zero, y); + } + + var x = x2.redSqrt(); + if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + if (x.fromRed().isOdd() !== odd) + x = x.redNeg(); + + return this.point(x, y); +}; + +EdwardsCurve.prototype.validate = function validate(point) { + if (point.isInfinity()) + return true; + + // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) + point.normalize(); + + var x2 = point.x.redSqr(); + var y2 = point.y.redSqr(); + var lhs = x2.redMul(this.a).redAdd(y2); + var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); + + return lhs.cmp(rhs) === 0; +}; + +function Point(curve, x, y, z, t) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && y === null && z === null) { + this.x = this.curve.zero; + this.y = this.curve.one; + this.z = this.curve.one; + this.t = this.curve.zero; + this.zOne = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = z ? new BN(z, 16) : this.curve.one; + this.t = t && new BN(t, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + if (this.t && !this.t.red) + this.t = this.t.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; + + // Use extended coordinates + if (this.curve.extended && !this.t) { + this.t = this.x.redMul(this.y); + if (!this.zOne) + this.t = this.t.redMul(this.z.redInvm()); + } + } +} +inherits(Point, Base.BasePoint); + +EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +EdwardsCurve.prototype.point = function point(x, y, z, t) { + return new Point(this, x, y, z, t); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1], obj[2]); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.x.cmpn(0) === 0 && + (this.y.cmp(this.z) === 0 || + (this.zOne && this.y.cmp(this.curve.c) === 0)); +}; + +Point.prototype._extDbl = function _extDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #doubling-dbl-2008-hwcd + // 4M + 4S + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = 2 * Z1^2 + var c = this.z.redSqr(); + c = c.redIAdd(c); + // D = a * A + var d = this.curve._mulA(a); + // E = (X1 + Y1)^2 - A - B + var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); + // G = D + B + var g = d.redAdd(b); + // F = G - C + var f = g.redSub(c); + // H = D - B + var h = d.redSub(b); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projDbl = function _projDbl() { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #doubling-dbl-2008-bbjlp + // #doubling-dbl-2007-bl + // and others + // Generally 3M + 4S or 2M + 4S + + // B = (X1 + Y1)^2 + var b = this.x.redAdd(this.y).redSqr(); + // C = X1^2 + var c = this.x.redSqr(); + // D = Y1^2 + var d = this.y.redSqr(); + + var nx; + var ny; + var nz; + if (this.curve.twisted) { + // E = a * C + var e = this.curve._mulA(c); + // F = E + D + var f = e.redAdd(d); + if (this.zOne) { + // X3 = (B - C - D) * (F - 2) + nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F^2 - 2 * F + nz = f.redSqr().redSub(f).redSub(f); + } else { + // H = Z1^2 + var h = this.z.redSqr(); + // J = F - 2 * H + var j = f.redSub(h).redISub(h); + // X3 = (B-C-D)*J + nx = b.redSub(c).redISub(d).redMul(j); + // Y3 = F * (E - D) + ny = f.redMul(e.redSub(d)); + // Z3 = F * J + nz = f.redMul(j); + } + } else { + // E = C + D + var e = c.redAdd(d); + // H = (c * Z1)^2 + var h = this.curve._mulC(this.z).redSqr(); + // J = E - 2 * H + var j = e.redSub(h).redSub(h); + // X3 = c * (B - E) * J + nx = this.curve._mulC(b.redISub(e)).redMul(j); + // Y3 = c * E * (C - D) + ny = this.curve._mulC(e).redMul(c.redISub(d)); + // Z3 = E * J + nz = e.redMul(j); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + // Double in extended coordinates + if (this.curve.extended) + return this._extDbl(); + else + return this._projDbl(); +}; + +Point.prototype._extAdd = function _extAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html + // #addition-add-2008-hwcd-3 + // 8M + + // A = (Y1 - X1) * (Y2 - X2) + var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); + // B = (Y1 + X1) * (Y2 + X2) + var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); + // C = T1 * k * T2 + var c = this.t.redMul(this.curve.dd).redMul(p.t); + // D = Z1 * 2 * Z2 + var d = this.z.redMul(p.z.redAdd(p.z)); + // E = B - A + var e = b.redSub(a); + // F = D - C + var f = d.redSub(c); + // G = D + C + var g = d.redAdd(c); + // H = B + A + var h = b.redAdd(a); + // X3 = E * F + var nx = e.redMul(f); + // Y3 = G * H + var ny = g.redMul(h); + // T3 = E * H + var nt = e.redMul(h); + // Z3 = F * G + var nz = f.redMul(g); + return this.curve.point(nx, ny, nz, nt); +}; + +Point.prototype._projAdd = function _projAdd(p) { + // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html + // #addition-add-2008-bbjlp + // #addition-add-2007-bl + // 10M + 1S + + // A = Z1 * Z2 + var a = this.z.redMul(p.z); + // B = A^2 + var b = a.redSqr(); + // C = X1 * X2 + var c = this.x.redMul(p.x); + // D = Y1 * Y2 + var d = this.y.redMul(p.y); + // E = d * C * D + var e = this.curve.d.redMul(c).redMul(d); + // F = B - E + var f = b.redSub(e); + // G = B + E + var g = b.redAdd(e); + // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) + var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); + var nx = a.redMul(f).redMul(tmp); + var ny; + var nz; + if (this.curve.twisted) { + // Y3 = A * G * (D - a * C) + ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); + // Z3 = F * G + nz = f.redMul(g); + } else { + // Y3 = A * G * (D - C) + ny = a.redMul(g).redMul(d.redSub(c)); + // Z3 = c * F * G + nz = this.curve._mulC(f).redMul(g); + } + return this.curve.point(nx, ny, nz); +}; + +Point.prototype.add = function add(p) { + if (this.isInfinity()) + return p; + if (p.isInfinity()) + return this; + + if (this.curve.extended) + return this._extAdd(p); + else + return this._projAdd(p); +}; + +Point.prototype.mul = function mul(k) { + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { + return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); +}; + +Point.prototype.normalize = function normalize() { + if (this.zOne) + return this; + + // Normalize coordinates + var zi = this.z.redInvm(); + this.x = this.x.redMul(zi); + this.y = this.y.redMul(zi); + if (this.t) + this.t = this.t.redMul(zi); + this.z = this.curve.one; + this.zOne = true; + return this; +}; + +Point.prototype.neg = function neg() { + return this.curve.point(this.x.redNeg(), + this.y, + this.z, + this.t && this.t.redNeg()); +}; + +Point.prototype.getX = function getX() { + this.normalize(); + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + this.normalize(); + return this.y.fromRed(); +}; + +Point.prototype.eq = function eq(other) { + return this === other || + this.getX().cmp(other.getX()) === 0 && + this.getY().cmp(other.getY()) === 0; +}; + +Point.prototype.eqXToP = function eqXToP(x) { + var rx = x.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(this.z); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +// Compatibility with BaseCurve +Point.prototype.toP = Point.prototype.normalize; +Point.prototype.mixedAdd = Point.prototype.add; + +},{"../../elliptic":66,"../curve":69,"bn.js":16,"inherits":101}],69:[function(require,module,exports){ +'use strict'; + +var curve = exports; + +curve.base = require('./base'); +curve.short = require('./short'); +curve.mont = require('./mont'); +curve.edwards = require('./edwards'); + +},{"./base":67,"./edwards":68,"./mont":70,"./short":71}],70:[function(require,module,exports){ +'use strict'; + +var curve = require('../curve'); +var BN = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; + +function MontCurve(conf) { + Base.call(this, 'mont', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.i4 = new BN(4).toRed(this.red).redInvm(); + this.two = new BN(2).toRed(this.red); + this.a24 = this.i4.redMul(this.a.redAdd(this.two)); +} +inherits(MontCurve, Base); +module.exports = MontCurve; + +MontCurve.prototype.validate = function validate(point) { + var x = point.normalize().x; + var x2 = x.redSqr(); + var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); + var y = rhs.redSqrt(); + + return y.redSqr().cmp(rhs) === 0; +}; + +function Point(curve, x, z) { + Base.BasePoint.call(this, curve, 'projective'); + if (x === null && z === null) { + this.x = this.curve.one; + this.z = this.curve.zero; + } else { + this.x = new BN(x, 16); + this.z = new BN(z, 16); + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + } +} +inherits(Point, Base.BasePoint); + +MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { + return this.point(utils.toArray(bytes, enc), 1); +}; + +MontCurve.prototype.point = function point(x, z) { + return new Point(this, x, z); +}; + +MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { + return Point.fromJSON(this, obj); +}; + +Point.prototype.precompute = function precompute() { + // No-op +}; + +Point.prototype._encode = function _encode() { + return this.getX().toArray('be', this.curve.p.byteLength()); +}; + +Point.fromJSON = function fromJSON(curve, obj) { + return new Point(curve, obj[0], obj[1] || curve.one); +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +Point.prototype.dbl = function dbl() { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 + // 2M + 2S + 4A + + // A = X1 + Z1 + var a = this.x.redAdd(this.z); + // AA = A^2 + var aa = a.redSqr(); + // B = X1 - Z1 + var b = this.x.redSub(this.z); + // BB = B^2 + var bb = b.redSqr(); + // C = AA - BB + var c = aa.redSub(bb); + // X3 = AA * BB + var nx = aa.redMul(bb); + // Z3 = C * (BB + A24 * C) + var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); + return this.curve.point(nx, nz); +}; + +Point.prototype.add = function add() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.diffAdd = function diffAdd(p, diff) { + // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 + // 4M + 2S + 6A + + // A = X2 + Z2 + var a = this.x.redAdd(this.z); + // B = X2 - Z2 + var b = this.x.redSub(this.z); + // C = X3 + Z3 + var c = p.x.redAdd(p.z); + // D = X3 - Z3 + var d = p.x.redSub(p.z); + // DA = D * A + var da = d.redMul(a); + // CB = C * B + var cb = c.redMul(b); + // X5 = Z1 * (DA + CB)^2 + var nx = diff.z.redMul(da.redAdd(cb).redSqr()); + // Z5 = X1 * (DA - CB)^2 + var nz = diff.x.redMul(da.redISub(cb).redSqr()); + return this.curve.point(nx, nz); +}; + +Point.prototype.mul = function mul(k) { + var t = k.clone(); + var a = this; // (N / 2) * Q + Q + var b = this.curve.point(null, null); // (N / 2) * Q + var c = this; // Q + + for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) + bits.push(t.andln(1)); + + for (var i = bits.length - 1; i >= 0; i--) { + if (bits[i] === 0) { + // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q + a = a.diffAdd(b, c); + // N * Q = 2 * ((N / 2) * Q + Q)) + b = b.dbl(); + } else { + // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) + b = a.diffAdd(b, c); + // N * Q + Q = 2 * ((N / 2) * Q + Q) + a = a.dbl(); + } + } + return b; +}; + +Point.prototype.mulAdd = function mulAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.jumlAdd = function jumlAdd() { + throw new Error('Not supported on Montgomery curve'); +}; + +Point.prototype.eq = function eq(other) { + return this.getX().cmp(other.getX()) === 0; +}; + +Point.prototype.normalize = function normalize() { + this.x = this.x.redMul(this.z.redInvm()); + this.z = this.curve.one; + return this; +}; + +Point.prototype.getX = function getX() { + // Normalize coordinates + this.normalize(); + + return this.x.fromRed(); +}; + +},{"../../elliptic":66,"../curve":69,"bn.js":16,"inherits":101}],71:[function(require,module,exports){ +'use strict'; + +var curve = require('../curve'); +var elliptic = require('../../elliptic'); +var BN = require('bn.js'); +var inherits = require('inherits'); +var Base = curve.base; + +var assert = elliptic.utils.assert; + +function ShortCurve(conf) { + Base.call(this, 'short', conf); + + this.a = new BN(conf.a, 16).toRed(this.red); + this.b = new BN(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + + // If the curve is endomorphic, precalculate beta and lambda + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits(ShortCurve, Base); +module.exports = ShortCurve; + +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + // No efficient endomorphism + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) + return; + + // Compute beta and lambda, that lambda * P = (beta * Px; Py) + var beta; + var lambda; + if (conf.beta) { + beta = new BN(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + // Choose the smallest beta + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new BN(conf.lambda, 16); + } else { + // Choose the lambda that is matching selected beta + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + + // Get basis vectors, used for balanced length-two representation + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new BN(vec.a, 16), + b: new BN(vec.b, 16) + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + + return { + beta: beta, + lambda: lambda, + basis: basis + }; +}; + +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + // Find roots of for x^2 + x + 1 in F + // Root = (-1 +- Sqrt(-3)) / 2 + // + var red = num === this.p ? this.red : BN.mont(num); + var tinv = new BN(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + + var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); + + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ l1, l2 ]; +}; + +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + // aprxSqrt >= sqrt(this.n) + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + + // 3.74 + // Run EGCD, until r(L + 1) < aprxSqrt + var u = lambda; + var v = this.n.clone(); + var x1 = new BN(1); + var y1 = new BN(0); + var x2 = new BN(0); + var y2 = new BN(1); + + // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) + var a0; + var b0; + // First vector + var a1; + var b1; + // Second vector + var a2; + var b2; + + var prevR; + var i = 0; + var r; + var x; + while (u.cmpn(0) !== 0) { + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + + // Normalize signs + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); + } + + return [ + { a: a1, b: b1 }, + { a: a2, b: b2 } + ]; +}; + +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + + // Calculate answer + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { k1: k1, k2: k2 }; +}; + +ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new BN(x, 16); + if (!x.red) + x = x.toRed(this.red); + + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) + throw new Error('invalid point'); + + // XXX Is there any way to tell if the number is odd without converting it + // to non-red form? + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) + y = y.redNeg(); + + return this.point(x, y); +}; + +ShortCurve.prototype.validate = function validate(point) { + if (point.inf) + return true; + + var x = point.x; + var y = point.y; + + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; + +ShortCurve.prototype._endoWnafMulAdd = + function _endoWnafMulAdd(points, coeffs, jacobianResult) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for (var i = 0; i < points.length; i++) { + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + + // Clean-up references to points and coefficients + for (var j = 0; j < i * 2; j++) { + npoints[j] = null; + ncoeffs[j] = null; + } + return res; +}; + +function Point(curve, x, y, isRed) { + Base.BasePoint.call(this, curve, 'affine'); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + // Force redgomery representation when loading from JSON + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + this.inf = false; + } +} +inherits(Point, Base.BasePoint); + +ShortCurve.prototype.point = function point(x, y, isRed) { + return new Point(this, x, y, isRed); +}; + +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; + +Point.prototype._getBeta = function _getBeta() { + if (!this.curve.endo) + return; + + var pre = this.precomputed; + if (pre && pre.beta) + return pre.beta; + + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; +}; + +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) + return [ this.x, this.y ]; + + return [ this.x, this.y, this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) + } + } ]; +}; + +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === 'string') + obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) + return res; + + function obj2point(obj) { + return curve.point(obj[0], obj[1], red); + } + + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ res ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ res ].concat(pre.naf.points.map(obj2point)) + } + }; + return res; +}; + +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; + +Point.prototype.add = function add(p) { + // O + P = P + if (this.inf) + return p; + + // P + O = P + if (p.inf) + return this; + + // P + P = 2P + if (this.eq(p)) + return this.dbl(); + + // P + (-P) = O + if (this.neg().eq(p)) + return this.curve.point(null, null); + + // P + Q = O + if (this.x.cmp(p.x) === 0) + return this.curve.point(null, null); + + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) + c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.dbl = function dbl() { + if (this.inf) + return this; + + // 2P = O + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) + return this.curve.point(null, null); + + var a = this.curve.a; + + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; + +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; + +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; + +Point.prototype.mul = function mul(k) { + k = new BN(k, 16); + + if (this._hasDoubles(k)) + return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) + return this.curve._endoWnafMulAdd([ this ], [ k ]); + else + return this.curve._wnafMul(this, k); +}; + +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; + +Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { + var points = [ this, p2 ]; + var coeffs = [ k1, k2 ]; + if (this.curve.endo) + return this.curve._endoWnafMulAdd(points, coeffs, true); + else + return this.curve._wnafMulAdd(1, points, coeffs, 2, true); +}; + +Point.prototype.eq = function eq(p) { + return this === p || + this.inf === p.inf && + (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; + +Point.prototype.neg = function neg(_precompute) { + if (this.inf) + return this; + + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) + } + }; + } + return res; +}; + +Point.prototype.toJ = function toJ() { + if (this.inf) + return this.curve.jpoint(null, null, null); + + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; + +function JPoint(curve, x, y, z) { + Base.BasePoint.call(this, curve, 'jacobian'); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new BN(0); + } else { + this.x = new BN(x, 16); + this.y = new BN(y, 16); + this.z = new BN(z, 16); + } + if (!this.x.red) + this.x = this.x.toRed(this.curve.red); + if (!this.y.red) + this.y = this.y.toRed(this.curve.red); + if (!this.z.red) + this.z = this.z.toRed(this.curve.red); + + this.zOne = this.z === this.curve.one; +} +inherits(JPoint, Base.BasePoint); + +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; + +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) + return this.curve.point(null, null); + + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + + return this.curve.point(ax, ay); +}; + +JPoint.prototype.neg = function neg() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; + +JPoint.prototype.add = function add(p) { + // O + P = P + if (this.isInfinity()) + return p; + + // P + O = P + if (p.isInfinity()) + return this; + + // 12M + 4S + 7A + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mixedAdd = function mixedAdd(p) { + // O + P = P + if (this.isInfinity()) + return p.toJ(); + + // P + O = P + if (p.isInfinity()) + return this; + + // 8M + 3S + 7A + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) + return this.curve.jpoint(null, null, null); + else + return this.dbl(); + } + + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.dblp = function dblp(pow) { + if (pow === 0) + return this; + if (this.isInfinity()) + return this; + if (!pow) + return this.dbl(); + + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for (var i = 0; i < pow; i++) + r = r.dbl(); + return r; + } + + // 1M + 2S + 1A + N * (4S + 5M + 8A) + // N = 1 => 6M + 6S + 9A + var a = this.curve.a; + var tinv = this.curve.tinv; + + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + // Reuse results + var jyd = jy.redAdd(jy); + for (var i = 0; i < pow; i++) { + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) + jz4 = jz4.redMul(jyd4); + + jx = nx; + jz = nz; + jyd = dny; + } + + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; + +JPoint.prototype.dbl = function dbl() { + if (this.isInfinity()) + return this; + + if (this.curve.zeroA) + return this._zeroDbl(); + else if (this.curve.threeA) + return this._threeDbl(); + else + return this._dbl(); +}; + +JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 14A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // T = M ^ 2 - 2*S + var t = m.redSqr().redISub(s).redISub(s); + + // 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2*Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html + // #doubling-dbl-2009-l + // 2M + 5S + 13A + + // A = X1^2 + var a = this.x.redSqr(); + // B = Y1^2 + var b = this.y.redSqr(); + // C = B^2 + var c = b.redSqr(); + // D = 2 * ((X1 + B)^2 - A - C) + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + // E = 3 * A + var e = a.redAdd(a).redIAdd(a); + // F = E^2 + var f = e.redSqr(); + + // 8 * C + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + + // X3 = F - 2 * D + nx = f.redISub(d).redISub(d); + // Y3 = E * (D - X3) - 8 * C + ny = e.redMul(d.redISub(nx)).redISub(c8); + // Z3 = 2 * Y1 * Z1 + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + // Z = 1 + if (this.zOne) { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html + // #doubling-mdbl-2007-bl + // 1M + 5S + 15A + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // S = 2 * ((X1 + YY)^2 - XX - YYYY) + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + // M = 3 * XX + a + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + // T = M^2 - 2 * S + var t = m.redSqr().redISub(s).redISub(s); + // X3 = T + nx = t; + // Y3 = M * (S - T) - 8 * YYYY + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + // Z3 = 2 * Y1 + nz = this.y.redAdd(this.y); + } else { + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b + // 3M + 5S + + // delta = Z1^2 + var delta = this.z.redSqr(); + // gamma = Y1^2 + var gamma = this.y.redSqr(); + // beta = X1 * gamma + var beta = this.x.redMul(gamma); + // alpha = 3 * (X1 - delta) * (X1 + delta) + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + // X3 = alpha^2 - 8 * beta + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + // Z3 = (Y1 + Z1)^2 - gamma - delta + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + + // 4M + 6S + 10A + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) + return this.dbl().add(this); + + // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl + // 5M + 10S + ... + + // XX = X1^2 + var xx = this.x.redSqr(); + // YY = Y1^2 + var yy = this.y.redSqr(); + // ZZ = Z1^2 + var zz = this.z.redSqr(); + // YYYY = YY^2 + var yyyy = yy.redSqr(); + // M = 3 * XX + a * ZZ2; a = 0 + var m = xx.redAdd(xx).redIAdd(xx); + // MM = M^2 + var mm = m.redSqr(); + // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + // EE = E^2 + var ee = e.redSqr(); + // T = 16*YYYY + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + // U = (M + E)^2 - MM - EE - T + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + // X3 = 4 * (X1 * EE - 4 * YY * U) + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + // Y3 = 8 * Y1 * (U * (T - U) - E * EE) + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + // Z3 = (Z1 + E)^2 - ZZ - EE + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + + return this.curve.jpoint(nx, ny, nz); +}; + +JPoint.prototype.mul = function mul(k, kbase) { + k = new BN(k, kbase); + + return this.curve._wnafMul(this, k); +}; + +JPoint.prototype.eq = function eq(p) { + if (p.type === 'affine') + return this.eq(p.toJ()); + + if (this === p) + return true; + + // x1 * z2^2 == x2 * z1^2 + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) + return false; + + // y1 * z2^3 == y2 * z1^3 + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; + +JPoint.prototype.eqXToP = function eqXToP(x) { + var zs = this.z.redSqr(); + var rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) + return true; + + var xc = x.clone(); + var t = this.curve.redN.redMul(zs); + for (;;) { + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) + return false; + + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) + return true; + } +}; + +JPoint.prototype.inspect = function inspect() { + if (this.isInfinity()) + return ''; + return ''; +}; + +JPoint.prototype.isInfinity = function isInfinity() { + // XXX This code assumes that zero is always zero in red + return this.z.cmpn(0) === 0; +}; + +},{"../../elliptic":66,"../curve":69,"bn.js":16,"inherits":101}],72:[function(require,module,exports){ +'use strict'; + +var curves = exports; + +var hash = require('hash.js'); +var elliptic = require('../elliptic'); + +var assert = elliptic.utils.assert; + +function PresetCurve(options) { + if (options.type === 'short') + this.curve = new elliptic.curve.short(options); + else if (options.type === 'edwards') + this.curve = new elliptic.curve.edwards(options); + else + this.curve = new elliptic.curve.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + + assert(this.g.validate(), 'Invalid curve'); + assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); +} +curves.PresetCurve = PresetCurve; + +function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve + }); + return curve; + } + }); +} + +defineCurve('p192', { + type: 'short', + prime: 'p192', + p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', + b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', + n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', + hash: hash.sha256, + gRed: false, + g: [ + '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', + '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' + ] +}); + +defineCurve('p224', { + type: 'short', + prime: 'p224', + p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', + a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', + b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', + n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', + hash: hash.sha256, + gRed: false, + g: [ + 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', + 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' + ] +}); + +defineCurve('p256', { + type: 'short', + prime: null, + p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', + a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', + b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', + n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', + hash: hash.sha256, + gRed: false, + g: [ + '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' + ] +}); + +defineCurve('p384', { + type: 'short', + prime: null, + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 ffffffff', + a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'fffffffe ffffffff 00000000 00000000 fffffffc', + b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + + '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', + n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + + 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', + hash: hash.sha384, + gRed: false, + g: [ + 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + + '5502f25d bf55296c 3a545e38 72760ab7', + '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' + ] +}); + +defineCurve('p521', { + type: 'short', + prime: null, + p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff', + a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff ffffffff ffffffff fffffffc', + b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + + '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + + '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', + n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + + 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + + 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', + hash: hash.sha512, + gRed: false, + g: [ + '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + + '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + + 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', + '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + + '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + + '3fad0761 353c7086 a272c240 88be9476 9fd16650' + ] +}); + +defineCurve('curve25519', { + type: 'mont', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '76d06', + b: '1', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '9' + ] +}); + +defineCurve('ed25519', { + type: 'edwards', + prime: 'p25519', + p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', + a: '-1', + c: '1', + // -121665 * (121666^(-1)) (mod P) + d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', + n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', + hash: hash.sha256, + gRed: false, + g: [ + '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', + + // 4/5 + '6666666666666666666666666666666666666666666666666666666666666658' + ] +}); + +var pre; +try { + pre = require('./precomputed/secp256k1'); +} catch (e) { + pre = undefined; +} + +defineCurve('secp256k1', { + type: 'short', + prime: 'k256', + p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', + a: '0', + b: '7', + n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', + h: '1', + hash: hash.sha256, + + // Precomputed endomorphism + beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', + lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', + basis: [ + { + a: '3086d221a7d46bcde86c90e49284eb15', + b: '-e4437ed6010e88286f547fa90abfe4c3' + }, + { + a: '114ca50f7a8e2f3f657c1108d9d44cfd8', + b: '3086d221a7d46bcde86c90e49284eb15' + } + ], + + gRed: false, + g: [ + '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', + '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', + pre + ] +}); + +},{"../elliptic":66,"./precomputed/secp256k1":79,"hash.js":87}],73:[function(require,module,exports){ +'use strict'; + +var BN = require('bn.js'); +var HmacDRBG = require('hmac-drbg'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +var KeyPair = require('./key'); +var Signature = require('./signature'); + +function EC(options) { + if (!(this instanceof EC)) + return new EC(options); + + // Shortcut `elliptic.ec(curve-name)` + if (typeof options === 'string') { + assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); + + options = elliptic.curves[options]; + } + + // Shortcut for `elliptic.ec(elliptic.curves.curveName)` + if (options instanceof elliptic.curves.PresetCurve) + options = { curve: options }; + + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.ushrn(1); + this.g = this.curve.g; + + // Point on curve + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + + // Hash for function for DRBG + this.hash = options.hash || options.curve.hash; +} +module.exports = EC; + +EC.prototype.keyPair = function keyPair(options) { + return new KeyPair(this, options); +}; + +EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return KeyPair.fromPrivate(this, priv, enc); +}; + +EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return KeyPair.fromPublic(this, pub, enc); +}; + +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) + options = {}; + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + pers: options.pers, + persEnc: options.persEnc || 'utf8', + entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || 'utf8', + nonce: this.n.toArray() + }); + + var bytes = this.n.byteLength(); + var ns2 = this.n.sub(new BN(2)); + do { + var priv = new BN(drbg.generate(bytes)); + if (priv.cmp(ns2) > 0) + continue; + + priv.iaddn(1); + return this.keyFromPrivate(priv); + } while (true); +}; + +EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) + msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) + return msg.sub(this.n); + else + return msg; +}; + +EC.prototype.sign = function sign(msg, key, enc, options) { + if (typeof enc === 'object') { + options = enc; + enc = null; + } + if (!options) + options = {}; + + key = this.keyFromPrivate(key, enc); + msg = this._truncateToN(new BN(msg, 16)); + + // Zero-extend key to provide enough entropy + var bytes = this.n.byteLength(); + var bkey = key.getPrivate().toArray('be', bytes); + + // Zero-extend nonce to have the same byte size as N + var nonce = msg.toArray('be', bytes); + + // Instantiate Hmac_DRBG + var drbg = new HmacDRBG({ + hash: this.hash, + entropy: bkey, + nonce: nonce, + pers: options.pers, + persEnc: options.persEnc || 'utf8' + }); + + // Number of bytes to generate + var ns1 = this.n.sub(new BN(1)); + + for (var iter = 0; true; iter++) { + var k = options.k ? + options.k(iter) : + new BN(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) + continue; + + var kp = this.g.mul(k); + if (kp.isInfinity()) + continue; + + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) + continue; + + var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) + continue; + + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | + (kpX.cmp(r) !== 0 ? 2 : 0); + + // Use complement of `s`, if it is > `n / 2` + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + + return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); + } +}; + +EC.prototype.verify = function verify(msg, signature, key, enc) { + msg = this._truncateToN(new BN(msg, 16)); + key = this.keyFromPublic(key, enc); + signature = new Signature(signature, 'hex'); + + // Perform primitive values validation + var r = signature.r; + var s = signature.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) + return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) + return false; + + // Validate signature + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + + if (!this.curve._maxwellTrick) { + var p = this.g.mulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + return p.getX().umod(this.n).cmp(r) === 0; + } + + // NOTE: Greg Maxwell's trick, inspired by: + // https://git.io/vad3K + + var p = this.g.jmulAdd(u1, key.getPublic(), u2); + if (p.isInfinity()) + return false; + + // Compare `p.x` of Jacobian point with `r`, + // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the + // inverse of `p.z^2` + return p.eqXToP(r); +}; + +EC.prototype.recoverPubKey = function(msg, signature, j, enc) { + assert((3 & j) === j, 'The recovery param is more than two bits'); + signature = new Signature(signature, enc); + + var n = this.n; + var e = new BN(msg); + var r = signature.r; + var s = signature.s; + + // A set LSB signifies that the y-coordinate is odd + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) + throw new Error('Unable to find sencond key candinate'); + + // 1.1. Let x = r + jn. + if (isSecondKey) + r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else + r = this.curve.pointFromX(r, isYOdd); + + var rInv = signature.r.invm(n); + var s1 = n.sub(e).mul(rInv).umod(n); + var s2 = s.mul(rInv).umod(n); + + // 1.6.1 Compute Q = r^-1 (sR - eG) + // Q = r^-1 (sR + -eG) + return this.g.mulAdd(s1, r, s2); +}; + +EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { + signature = new Signature(signature, enc); + if (signature.recoveryParam !== null) + return signature.recoveryParam; + + for (var i = 0; i < 4; i++) { + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature, i); + } catch (e) { + continue; + } + + if (Qprime.eq(Q)) + return i; + } + throw new Error('Unable to find valid recovery factor'); +}; + +},{"../../elliptic":66,"./key":74,"./signature":75,"bn.js":16,"hmac-drbg":99}],74:[function(require,module,exports){ +'use strict'; + +var BN = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +function KeyPair(ec, options) { + this.ec = ec; + this.priv = null; + this.pub = null; + + // KeyPair(ec, { priv: ..., pub: ... }) + if (options.priv) + this._importPrivate(options.priv, options.privEnc); + if (options.pub) + this._importPublic(options.pub, options.pubEnc); +} +module.exports = KeyPair; + +KeyPair.fromPublic = function fromPublic(ec, pub, enc) { + if (pub instanceof KeyPair) + return pub; + + return new KeyPair(ec, { + pub: pub, + pubEnc: enc + }); +}; + +KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { + if (priv instanceof KeyPair) + return priv; + + return new KeyPair(ec, { + priv: priv, + privEnc: enc + }); +}; + +KeyPair.prototype.validate = function validate() { + var pub = this.getPublic(); + + if (pub.isInfinity()) + return { result: false, reason: 'Invalid public key' }; + if (!pub.validate()) + return { result: false, reason: 'Public key is not a point' }; + if (!pub.mul(this.ec.curve.n).isInfinity()) + return { result: false, reason: 'Public key * N != O' }; + + return { result: true, reason: null }; +}; + +KeyPair.prototype.getPublic = function getPublic(compact, enc) { + // compact is optional argument + if (typeof compact === 'string') { + enc = compact; + compact = null; + } + + if (!this.pub) + this.pub = this.ec.g.mul(this.priv); + + if (!enc) + return this.pub; + + return this.pub.encode(enc, compact); +}; + +KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === 'hex') + return this.priv.toString(16, 2); + else + return this.priv; +}; + +KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { + this.priv = new BN(key, enc || 16); + + // Ensure that the priv won't be bigger than n, otherwise we may fail + // in fixed multiplication method + this.priv = this.priv.umod(this.ec.curve.n); +}; + +KeyPair.prototype._importPublic = function _importPublic(key, enc) { + if (key.x || key.y) { + // Montgomery points only have an `x` coordinate. + // Weierstrass/Edwards points on the other hand have both `x` and + // `y` coordinates. + if (this.ec.curve.type === 'mont') { + assert(key.x, 'Need x coordinate'); + } else if (this.ec.curve.type === 'short' || + this.ec.curve.type === 'edwards') { + assert(key.x && key.y, 'Need both x and y coordinate'); + } + this.pub = this.ec.curve.point(key.x, key.y); + return; + } + this.pub = this.ec.curve.decodePoint(key, enc); +}; + +// ECDH +KeyPair.prototype.derive = function derive(pub) { + return pub.mul(this.priv).getX(); +}; + +// ECDSA +KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); +}; + +KeyPair.prototype.verify = function verify(msg, signature) { + return this.ec.verify(msg, signature, this); +}; + +KeyPair.prototype.inspect = function inspect() { + return ''; +}; + +},{"../../elliptic":66,"bn.js":16}],75:[function(require,module,exports){ +'use strict'; + +var BN = require('bn.js'); + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; + +function Signature(options, enc) { + if (options instanceof Signature) + return options; + + if (this._importDER(options, enc)) + return; + + assert(options.r && options.s, 'Signature without r or s'); + this.r = new BN(options.r, 16); + this.s = new BN(options.s, 16); + if (options.recoveryParam === undefined) + this.recoveryParam = null; + else + this.recoveryParam = options.recoveryParam; +} +module.exports = Signature; + +function Position() { + this.place = 0; +} + +function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 0x80)) { + return initial; + } + var octetLen = initial & 0xf; + var val = 0; + for (var i = 0, off = p.place; i < octetLen; i++, off++) { + val <<= 8; + val |= buf[off]; + } + p.place = off; + return val; +} + +function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); +} + +Signature.prototype._importDER = function _importDER(data, enc) { + data = utils.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 0x30) { + return false; + } + var len = getLength(data, p); + if ((len + p.place) !== data.length) { + return false; + } + if (data[p.place++] !== 0x02) { + return false; + } + var rlen = getLength(data, p); + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 0x02) { + return false; + } + var slen = getLength(data, p); + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0 && (r[1] & 0x80)) { + r = r.slice(1); + } + if (s[0] === 0 && (s[1] & 0x80)) { + s = s.slice(1); + } + + this.r = new BN(r); + this.s = new BN(s); + this.recoveryParam = null; + + return true; +}; + +function constructLength(arr, len) { + if (len < 0x80) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 0x80); + while (--octets) { + arr.push((len >>> (octets << 3)) & 0xff); + } + arr.push(len); +} + +Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + + // Pad values + if (r[0] & 0x80) + r = [ 0 ].concat(r); + // Pad values + if (s[0] & 0x80) + s = [ 0 ].concat(s); + + r = rmPadding(r); + s = rmPadding(s); + + while (!s[0] && !(s[1] & 0x80)) { + s = s.slice(1); + } + var arr = [ 0x02 ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(0x02); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ 0x30 ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils.encode(res, enc); +}; + +},{"../../elliptic":66,"bn.js":16}],76:[function(require,module,exports){ +'use strict'; + +var hash = require('hash.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var KeyPair = require('./key'); +var Signature = require('./signature'); + +function EDDSA(curve) { + assert(curve === 'ed25519', 'only tested with ed25519 so far'); + + if (!(this instanceof EDDSA)) + return new EDDSA(curve); + + var curve = elliptic.curves[curve].curve; + this.curve = curve; + this.g = curve.g; + this.g.precompute(curve.n.bitLength() + 1); + + this.pointClass = curve.point().constructor; + this.encodingLength = Math.ceil(curve.n.bitLength() / 8); + this.hash = hash.sha512; +} + +module.exports = EDDSA; + +/** +* @param {Array|String} message - message bytes +* @param {Array|String|KeyPair} secret - secret bytes or a keypair +* @returns {Signature} - signature +*/ +EDDSA.prototype.sign = function sign(message, secret) { + message = parseBytes(message); + var key = this.keyFromSecret(secret); + var r = this.hashInt(key.messagePrefix(), message); + var R = this.g.mul(r); + var Rencoded = this.encodePoint(R); + var s_ = this.hashInt(Rencoded, key.pubBytes(), message) + .mul(key.priv()); + var S = r.add(s_).umod(this.curve.n); + return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); +}; + +/** +* @param {Array} message - message bytes +* @param {Array|String|Signature} sig - sig bytes +* @param {Array|String|Point|KeyPair} pub - public key +* @returns {Boolean} - true if public key matches sig of message +*/ +EDDSA.prototype.verify = function verify(message, sig, pub) { + message = parseBytes(message); + sig = this.makeSignature(sig); + var key = this.keyFromPublic(pub); + var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); + var SG = this.g.mul(sig.S()); + var RplusAh = sig.R().add(key.pub().mul(h)); + return RplusAh.eq(SG); +}; + +EDDSA.prototype.hashInt = function hashInt() { + var hash = this.hash(); + for (var i = 0; i < arguments.length; i++) + hash.update(arguments[i]); + return utils.intFromLE(hash.digest()).umod(this.curve.n); +}; + +EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { + return KeyPair.fromPublic(this, pub); +}; + +EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { + return KeyPair.fromSecret(this, secret); +}; + +EDDSA.prototype.makeSignature = function makeSignature(sig) { + if (sig instanceof Signature) + return sig; + return new Signature(this, sig); +}; + +/** +* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 +* +* EDDSA defines methods for encoding and decoding points and integers. These are +* helper convenience methods, that pass along to utility functions implied +* parameters. +* +*/ +EDDSA.prototype.encodePoint = function encodePoint(point) { + var enc = point.getY().toArray('le', this.encodingLength); + enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; + return enc; +}; + +EDDSA.prototype.decodePoint = function decodePoint(bytes) { + bytes = utils.parseBytes(bytes); + + var lastIx = bytes.length - 1; + var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); + var xIsOdd = (bytes[lastIx] & 0x80) !== 0; + + var y = utils.intFromLE(normed); + return this.curve.pointFromY(y, xIsOdd); +}; + +EDDSA.prototype.encodeInt = function encodeInt(num) { + return num.toArray('le', this.encodingLength); +}; + +EDDSA.prototype.decodeInt = function decodeInt(bytes) { + return utils.intFromLE(bytes); +}; + +EDDSA.prototype.isPoint = function isPoint(val) { + return val instanceof this.pointClass; +}; + +},{"../../elliptic":66,"./key":77,"./signature":78,"hash.js":87}],77:[function(require,module,exports){ +'use strict'; + +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var parseBytes = utils.parseBytes; +var cachedProperty = utils.cachedProperty; + +/** +* @param {EDDSA} eddsa - instance +* @param {Object} params - public/private key parameters +* +* @param {Array} [params.secret] - secret seed bytes +* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) +* @param {Array} [params.pub] - public key point encoded as bytes +* +*/ +function KeyPair(eddsa, params) { + this.eddsa = eddsa; + this._secret = parseBytes(params.secret); + if (eddsa.isPoint(params.pub)) + this._pub = params.pub; + else + this._pubBytes = parseBytes(params.pub); +} + +KeyPair.fromPublic = function fromPublic(eddsa, pub) { + if (pub instanceof KeyPair) + return pub; + return new KeyPair(eddsa, { pub: pub }); +}; + +KeyPair.fromSecret = function fromSecret(eddsa, secret) { + if (secret instanceof KeyPair) + return secret; + return new KeyPair(eddsa, { secret: secret }); +}; + +KeyPair.prototype.secret = function secret() { + return this._secret; +}; + +cachedProperty(KeyPair, 'pubBytes', function pubBytes() { + return this.eddsa.encodePoint(this.pub()); +}); + +cachedProperty(KeyPair, 'pub', function pub() { + if (this._pubBytes) + return this.eddsa.decodePoint(this._pubBytes); + return this.eddsa.g.mul(this.priv()); +}); + +cachedProperty(KeyPair, 'privBytes', function privBytes() { + var eddsa = this.eddsa; + var hash = this.hash(); + var lastIx = eddsa.encodingLength - 1; + + var a = hash.slice(0, eddsa.encodingLength); + a[0] &= 248; + a[lastIx] &= 127; + a[lastIx] |= 64; + + return a; +}); + +cachedProperty(KeyPair, 'priv', function priv() { + return this.eddsa.decodeInt(this.privBytes()); +}); + +cachedProperty(KeyPair, 'hash', function hash() { + return this.eddsa.hash().update(this.secret()).digest(); +}); + +cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { + return this.hash().slice(this.eddsa.encodingLength); +}); + +KeyPair.prototype.sign = function sign(message) { + assert(this._secret, 'KeyPair can only verify'); + return this.eddsa.sign(message, this); +}; + +KeyPair.prototype.verify = function verify(message, sig) { + return this.eddsa.verify(message, sig, this); +}; + +KeyPair.prototype.getSecret = function getSecret(enc) { + assert(this._secret, 'KeyPair is public only'); + return utils.encode(this.secret(), enc); +}; + +KeyPair.prototype.getPublic = function getPublic(enc) { + return utils.encode(this.pubBytes(), enc); +}; + +module.exports = KeyPair; + +},{"../../elliptic":66}],78:[function(require,module,exports){ +'use strict'; + +var BN = require('bn.js'); +var elliptic = require('../../elliptic'); +var utils = elliptic.utils; +var assert = utils.assert; +var cachedProperty = utils.cachedProperty; +var parseBytes = utils.parseBytes; + +/** +* @param {EDDSA} eddsa - eddsa instance +* @param {Array|Object} sig - +* @param {Array|Point} [sig.R] - R point as Point or bytes +* @param {Array|bn} [sig.S] - S scalar as bn or bytes +* @param {Array} [sig.Rencoded] - R point encoded +* @param {Array} [sig.Sencoded] - S scalar encoded +*/ +function Signature(eddsa, sig) { + this.eddsa = eddsa; + + if (typeof sig !== 'object') + sig = parseBytes(sig); + + if (Array.isArray(sig)) { + sig = { + R: sig.slice(0, eddsa.encodingLength), + S: sig.slice(eddsa.encodingLength) + }; + } + + assert(sig.R && sig.S, 'Signature without R or S'); + + if (eddsa.isPoint(sig.R)) + this._R = sig.R; + if (sig.S instanceof BN) + this._S = sig.S; + + this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; + this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; +} + +cachedProperty(Signature, 'S', function S() { + return this.eddsa.decodeInt(this.Sencoded()); +}); + +cachedProperty(Signature, 'R', function R() { + return this.eddsa.decodePoint(this.Rencoded()); +}); + +cachedProperty(Signature, 'Rencoded', function Rencoded() { + return this.eddsa.encodePoint(this.R()); +}); + +cachedProperty(Signature, 'Sencoded', function Sencoded() { + return this.eddsa.encodeInt(this.S()); +}); + +Signature.prototype.toBytes = function toBytes() { + return this.Rencoded().concat(this.Sencoded()); +}; + +Signature.prototype.toHex = function toHex() { + return utils.encode(this.toBytes(), 'hex').toUpperCase(); +}; + +module.exports = Signature; + +},{"../../elliptic":66,"bn.js":16}],79:[function(require,module,exports){ +module.exports = { + doubles: { + step: 4, + points: [ + [ + 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', + 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' + ], + [ + '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', + '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' + ], + [ + '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', + 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' + ], + [ + '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', + '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' + ], + [ + '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', + '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' + ], + [ + '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', + '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' + ], + [ + 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', + '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' + ], + [ + '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', + 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' + ], + [ + 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', + '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' + ], + [ + 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', + 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' + ], + [ + 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', + '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' + ], + [ + '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', + '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' + ], + [ + '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', + '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' + ], + [ + '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', + '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' + ], + [ + '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', + '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' + ], + [ + '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', + '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' + ], + [ + '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', + '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' + ], + [ + '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', + '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' + ], + [ + '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', + 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' + ], + [ + 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', + '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' + ], + [ + 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', + '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' + ], + [ + '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', + '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' + ], + [ + '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', + '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' + ], + [ + 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', + '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' + ], + [ + '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', + 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' + ], + [ + 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', + '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' + ], + [ + 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', + 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' + ], + [ + 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', + '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' + ], + [ + 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', + 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' + ], + [ + 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', + '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' + ], + [ + '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', + 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' + ], + [ + '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', + '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' + ], + [ + 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', + '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' + ], + [ + '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', + 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' + ], + [ + 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', + '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' + ], + [ + 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', + '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' + ], + [ + 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', + 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' + ], + [ + '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', + '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' + ], + [ + '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', + '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' + ], + [ + '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', + 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' + ], + [ + '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', + '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' + ], + [ + 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', + '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' + ], + [ + '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', + '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' + ], + [ + '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', + 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' + ], + [ + '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', + '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' + ], + [ + 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', + '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' + ], + [ + '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', + 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' + ], + [ + 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', + 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' + ], + [ + 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', + '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' + ], + [ + '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', + 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' + ], + [ + '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', + 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' + ], + [ + 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', + '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' + ], + [ + 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', + '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' + ], + [ + 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', + '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' + ], + [ + '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', + 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' + ], + [ + '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', + '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' + ], + [ + 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', + 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' + ], + [ + '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', + 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' + ], + [ + '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', + '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' + ], + [ + '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', + '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' + ], + [ + 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', + 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' + ], + [ + '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', + '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' + ], + [ + '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', + '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' + ], + [ + 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', + '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' + ], + [ + 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', + 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' + ] + ] + }, + naf: { + wnd: 7, + points: [ + [ + 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', + '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' + ], + [ + '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', + 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' + ], + [ + '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', + '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' + ], + [ + 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', + 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' + ], + [ + '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', + 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' + ], + [ + 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', + 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' + ], + [ + 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', + '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' + ], + [ + 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', + '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' + ], + [ + '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', + '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' + ], + [ + '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', + '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' + ], + [ + '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', + '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' + ], + [ + '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', + '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' + ], + [ + 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', + 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' + ], + [ + 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', + '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' + ], + [ + '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', + 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' + ], + [ + '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', + 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' + ], + [ + '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', + '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' + ], + [ + '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', + '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' + ], + [ + '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', + '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' + ], + [ + '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', + 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' + ], + [ + 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', + 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' + ], + [ + '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', + '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' + ], + [ + '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', + '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' + ], + [ + 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', + 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' + ], + [ + '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', + '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' + ], + [ + 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', + 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' + ], + [ + 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', + 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' + ], + [ + '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', + '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' + ], + [ + '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', + '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' + ], + [ + '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', + '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' + ], + [ + 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', + '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' + ], + [ + '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', + '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' + ], + [ + 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', + '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' + ], + [ + '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', + 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' + ], + [ + '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', + 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' + ], + [ + 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', + 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' + ], + [ + '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', + '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' + ], + [ + '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', + 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' + ], + [ + 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', + 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' + ], + [ + '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', + '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' + ], + [ + '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', + 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' + ], + [ + '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', + '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' + ], + [ + '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', + 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' + ], + [ + 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', + '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' + ], + [ + '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', + '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' + ], + [ + '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', + 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' + ], + [ + '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', + 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' + ], + [ + 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', + 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' + ], + [ + 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', + 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' + ], + [ + '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', + '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' + ], + [ + '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', + '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' + ], + [ + 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', + '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' + ], + [ + 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', + 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' + ], + [ + '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', + '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' + ], + [ + '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', + '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' + ], + [ + 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', + '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' + ], + [ + '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', + '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' + ], + [ + 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', + 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' + ], + [ + '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', + 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' + ], + [ + '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', + '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' + ], + [ + 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', + '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' + ], + [ + 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', + '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' + ], + [ + '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', + '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' + ], + [ + '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', + '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' + ], + [ + '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', + 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' + ], + [ + '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', + 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' + ], + [ + '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', + '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' + ], + [ + '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', + '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' + ], + [ + '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', + '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' + ], + [ + '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', + 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' + ], + [ + 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', + 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' + ], + [ + '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', + 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' + ], + [ + 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', + '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' + ], + [ + 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', + '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' + ], + [ + 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', + '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' + ], + [ + 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', + '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' + ], + [ + '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', + 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' + ], + [ + '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', + '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' + ], + [ + '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', + 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' + ], + [ + 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', + 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' + ], + [ + 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', + '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' + ], + [ + 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', + 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' + ], + [ + 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', + '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' + ], + [ + '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', + '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' + ], + [ + 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', + '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' + ], + [ + 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', + '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' + ], + [ + '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', + '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' + ], + [ + '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', + 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' + ], + [ + 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', + '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' + ], + [ + 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', + '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' + ], + [ + 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', + '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' + ], + [ + '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', + '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' + ], + [ + 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', + 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' + ], + [ + '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', + 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' + ], + [ + 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', + 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' + ], + [ + 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', + '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' + ], + [ + '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', + 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' + ], + [ + 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', + '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' + ], + [ + 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', + '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' + ], + [ + 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', + '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' + ], + [ + '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', + 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' + ], + [ + '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', + 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' + ], + [ + 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', + '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' + ], + [ + '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', + 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' + ], + [ + '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', + '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' + ], + [ + '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', + 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' + ], + [ + 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', + 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' + ], + [ + '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', + 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' + ], + [ + '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', + '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' + ], + [ + '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', + 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' + ], + [ + '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', + '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' + ], + [ + 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', + 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' + ], + [ + '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', + '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' + ], + [ + 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', + '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' + ], + [ + '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', + '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' + ], + [ + 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', + 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' + ], + [ + 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', + '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' + ], + [ + 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', + 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' + ], + [ + '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', + 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' + ], + [ + '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', + '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' + ], + [ + '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', + 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' + ], + [ + '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', + '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' + ], + [ + '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', + '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' + ], + [ + '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', + 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' + ], + [ + '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', + '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' + ], + [ + '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', + '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' + ], + [ + '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', + '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' + ] + ] + } +}; + +},{}],80:[function(require,module,exports){ +'use strict'; + +var utils = exports; +var BN = require('bn.js'); +var minAssert = require('minimalistic-assert'); +var minUtils = require('minimalistic-crypto-utils'); + +utils.assert = minAssert; +utils.toArray = minUtils.toArray; +utils.zero2 = minUtils.zero2; +utils.toHex = minUtils.toHex; +utils.encode = minUtils.encode; + +// Represent num in a w-NAF form +function getNAF(num, w) { + var naf = []; + var ws = 1 << (w + 1); + var k = num.clone(); + while (k.cmpn(1) >= 0) { + var z; + if (k.isOdd()) { + var mod = k.andln(ws - 1); + if (mod > (ws >> 1) - 1) + z = (ws >> 1) - mod; + else + z = mod; + k.isubn(z); + } else { + z = 0; + } + naf.push(z); + + // Optimization, shift by word if possible + var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; + for (var i = 1; i < shift; i++) + naf.push(0); + k.iushrn(shift); + } + + return naf; +} +utils.getNAF = getNAF; + +// Represent k1, k2 in a Joint Sparse Form +function getJSF(k1, k2) { + var jsf = [ + [], + [] + ]; + + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { + + // First phase + var m14 = (k1.andln(3) + d1) & 3; + var m24 = (k2.andln(3) + d2) & 3; + if (m14 === 3) + m14 = -1; + if (m24 === 3) + m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + var m8 = (k1.andln(7) + d1) & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) + u1 = -m14; + else + u1 = m14; + } + jsf[0].push(u1); + + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + var m8 = (k2.andln(7) + d2) & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) + u2 = -m24; + else + u2 = m24; + } + jsf[1].push(u2); + + // Second phase + if (2 * d1 === u1 + 1) + d1 = 1 - d1; + if (2 * d2 === u2 + 1) + d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + + return jsf; +} +utils.getJSF = getJSF; + +function cachedProperty(obj, name, computer) { + var key = '_' + name; + obj.prototype[name] = function cachedProperty() { + return this[key] !== undefined ? this[key] : + this[key] = computer.call(this); + }; +} +utils.cachedProperty = cachedProperty; + +function parseBytes(bytes) { + return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : + bytes; +} +utils.parseBytes = parseBytes; + +function intFromLE(bytes) { + return new BN(bytes, 'hex', 'le'); +} +utils.intFromLE = intFromLE; + + +},{"bn.js":16,"minimalistic-assert":106,"minimalistic-crypto-utils":107}],81:[function(require,module,exports){ +module.exports={ + "_from": "elliptic@^6.0.0", + "_id": "elliptic@6.4.1", + "_inBundle": false, + "_integrity": "sha512-BsXLz5sqX8OHcsh7CqBMztyXARmGQ3LWPtGjJi6DiJHq5C/qvi9P3OqgswKSDftbu8+IoI/QDTAm2fFnQ9SZSQ==", + "_location": "/elliptic", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "elliptic@^6.0.0", + "name": "elliptic", + "escapedName": "elliptic", + "rawSpec": "^6.0.0", + "saveSpec": null, + "fetchSpec": "^6.0.0" + }, + "_requiredBy": [ + "/browserify-sign", + "/create-ecdh" + ], + "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.1.tgz", + "_shasum": "c2d0b7776911b86722c632c3c06c60f2f819939a", + "_spec": "elliptic@^6.0.0", + "_where": "/Users/mjyc/hcrlab/jammer.js/node_modules/browserify-sign", + "author": { + "name": "Fedor Indutny", + "email": "fedor@indutny.com" + }, + "bugs": { + "url": "https://github.com/indutny/elliptic/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" + }, + "deprecated": false, + "description": "EC cryptography", + "devDependencies": { + "brfs": "^1.4.3", + "coveralls": "^2.11.3", + "grunt": "^0.4.5", + "grunt-browserify": "^5.0.0", + "grunt-cli": "^1.2.0", + "grunt-contrib-connect": "^1.0.0", + "grunt-contrib-copy": "^1.0.0", + "grunt-contrib-uglify": "^1.0.1", + "grunt-mocha-istanbul": "^3.0.1", + "grunt-saucelabs": "^8.6.2", + "istanbul": "^0.4.2", + "jscs": "^2.9.0", + "jshint": "^2.6.0", + "mocha": "^2.1.0" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/indutny/elliptic", + "keywords": [ + "EC", + "Elliptic", + "curve", + "Cryptography" + ], + "license": "MIT", + "main": "lib/elliptic.js", + "name": "elliptic", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indutny/elliptic.git" + }, + "scripts": { + "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", + "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", + "lint": "npm run jscs && npm run jshint", + "test": "npm run lint && npm run unit", + "unit": "istanbul test _mocha --reporter=spec test/index.js", + "version": "grunt dist && git add dist/" + }, + "version": "6.4.1" +} + +},{}],82:[function(require,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. + +var objectCreate = Object.create || objectCreatePolyfill +var objectKeys = Object.keys || objectKeysPolyfill +var bind = Function.prototype.bind || functionBindPolyfill + +function EventEmitter() { + if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { + this._events = objectCreate(null); + this._eventsCount = 0; + } + + 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. +var defaultMaxListeners = 10; + +var hasDefineProperty; +try { + var o = {}; + if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); + hasDefineProperty = o.x === 0; +} catch (err) { hasDefineProperty = false } +if (hasDefineProperty) { + Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + // check whether the input is a positive number (whose value is zero or + // greater and not a NaN). + if (typeof arg !== 'number' || arg < 0 || arg !== arg) + throw new TypeError('"defaultMaxListeners" must be a positive number'); + defaultMaxListeners = arg; + } + }); +} else { + EventEmitter.defaultMaxListeners = defaultMaxListeners; +} + +// 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 setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + if (arguments.length > 1) + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Unhandled "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = objectCreate(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' "' + String(type) + '" listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit.'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + if (typeof console === 'object' && console.warn) { + console.warn('%s: %s', w.name, w.message); + } + } + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + switch (arguments.length) { + case 0: + return this.listener.call(this.target); + case 1: + return this.listener.call(this.target, arguments[0]); + case 2: + return this.listener.call(this.target, arguments[0], arguments[1]); + case 3: + return this.listener.call(this.target, arguments[0], arguments[1], + arguments[2]); + default: + var args = new Array(arguments.length); + for (var i = 0; i < args.length; ++i) + args[i] = arguments[i]; + this.listener.apply(this.target, args); + } + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = bind.call(onceWrapper, state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = objectCreate(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else + spliceOne(list, position); + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = objectCreate(null); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = objectCreate(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = objectKeys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = objectCreate(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (!events) + return []; + + var evlistener = events[type]; + if (!evlistener) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function objectCreatePolyfill(proto) { + var F = function() {}; + F.prototype = proto; + return new F; +} +function objectKeysPolyfill(obj) { + var keys = []; + for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { + keys.push(k); + } + return k; +} +function functionBindPolyfill(context) { + var fn = this; + return function () { + return fn.apply(context, arguments); + }; +} + +},{}],83:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer +var MD5 = require('md5.js') + +/* eslint-disable camelcase */ +function EVP_BytesToKey (password, salt, keyBits, ivLen) { + if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') + if (salt) { + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') + if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') + } + + var keyLen = keyBits / 8 + var key = Buffer.alloc(keyLen) + var iv = Buffer.alloc(ivLen || 0) + var tmp = Buffer.alloc(0) + + while (keyLen > 0 || ivLen > 0) { + var hash = new MD5() + hash.update(tmp) + hash.update(password) + if (salt) hash.update(salt) + tmp = hash.digest() + + var used = 0 + + if (keyLen > 0) { + var keyStart = key.length - keyLen + used = Math.min(keyLen, tmp.length) + tmp.copy(key, keyStart, 0, used) + keyLen -= used + } + + if (used < tmp.length && ivLen > 0) { + var ivStart = iv.length - ivLen + var length = Math.min(ivLen, tmp.length - used) + tmp.copy(iv, ivStart, used, used + length) + ivLen -= length + } + } + + tmp.fill(0) + return { key: key, iv: iv } +} + +module.exports = EVP_BytesToKey + +},{"md5.js":104,"safe-buffer":142}],84:[function(require,module,exports){ +/*! Hammer.JS - v2.0.7 - 2016-04-22 + * http://hammerjs.github.io/ + * + * Copyright (c) 2016 Jorik Tangelder; + * Licensed under the MIT license */ +(function(window, document, exportName, undefined) { + 'use strict'; + +var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o']; +var TEST_ELEMENT = document.createElement('div'); + +var TYPE_FUNCTION = 'function'; + +var round = Math.round; +var abs = Math.abs; +var now = Date.now; + +/** + * set a timeout with a given scope + * @param {Function} fn + * @param {Number} timeout + * @param {Object} context + * @returns {number} + */ +function setTimeoutContext(fn, timeout, context) { + return setTimeout(bindFn(fn, context), timeout); +} + +/** + * if the argument is an array, we want to execute the fn on each entry + * if it aint an array we don't want to do a thing. + * this is used by all the methods that accept a single and array argument. + * @param {*|Array} arg + * @param {String} fn + * @param {Object} [context] + * @returns {Boolean} + */ +function invokeArrayArg(arg, fn, context) { + if (Array.isArray(arg)) { + each(arg, context[fn], context); + return true; + } + return false; +} + +/** + * walk objects and arrays + * @param {Object} obj + * @param {Function} iterator + * @param {Object} context + */ +function each(obj, iterator, context) { + var i; + + if (!obj) { + return; + } + + if (obj.forEach) { + obj.forEach(iterator, context); + } else if (obj.length !== undefined) { + i = 0; + while (i < obj.length) { + iterator.call(context, obj[i], i, obj); + i++; + } + } else { + for (i in obj) { + obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); + } + } +} + +/** + * wrap a method with a deprecation warning and stack trace + * @param {Function} method + * @param {String} name + * @param {String} message + * @returns {Function} A new function wrapping the supplied method. + */ +function deprecate(method, name, message) { + var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n'; + return function() { + var e = new Error('get-stack-trace'); + var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '') + .replace(/^\s+at\s+/gm, '') + .replace(/^Object.\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace'; + + var log = window.console && (window.console.warn || window.console.log); + if (log) { + log.call(window.console, deprecationMessage, stack); + } + return method.apply(this, arguments); + }; +} + +/** + * extend object. + * means that properties in dest will be overwritten by the ones in src. + * @param {Object} target + * @param {...Object} objects_to_assign + * @returns {Object} target + */ +var assign; +if (typeof Object.assign !== 'function') { + assign = function assign(target) { + if (target === undefined || target === null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + + var output = Object(target); + for (var index = 1; index < arguments.length; index++) { + var source = arguments[index]; + if (source !== undefined && source !== null) { + for (var nextKey in source) { + if (source.hasOwnProperty(nextKey)) { + output[nextKey] = source[nextKey]; + } + } + } + } + return output; + }; +} else { + assign = Object.assign; +} + +/** + * extend object. + * means that properties in dest will be overwritten by the ones in src. + * @param {Object} dest + * @param {Object} src + * @param {Boolean} [merge=false] + * @returns {Object} dest + */ +var extend = deprecate(function extend(dest, src, merge) { + var keys = Object.keys(src); + var i = 0; + while (i < keys.length) { + if (!merge || (merge && dest[keys[i]] === undefined)) { + dest[keys[i]] = src[keys[i]]; + } + i++; + } + return dest; +}, 'extend', 'Use `assign`.'); + +/** + * merge the values from src in the dest. + * means that properties that exist in dest will not be overwritten by src + * @param {Object} dest + * @param {Object} src + * @returns {Object} dest + */ +var merge = deprecate(function merge(dest, src) { + return extend(dest, src, true); +}, 'merge', 'Use `assign`.'); + +/** + * simple class inheritance + * @param {Function} child + * @param {Function} base + * @param {Object} [properties] + */ +function inherit(child, base, properties) { + var baseP = base.prototype, + childP; + + childP = child.prototype = Object.create(baseP); + childP.constructor = child; + childP._super = baseP; + + if (properties) { + assign(childP, properties); + } +} + +/** + * simple function bind + * @param {Function} fn + * @param {Object} context + * @returns {Function} + */ +function bindFn(fn, context) { + return function boundFn() { + return fn.apply(context, arguments); + }; +} + +/** + * let a boolean value also be a function that must return a boolean + * this first item in args will be used as the context + * @param {Boolean|Function} val + * @param {Array} [args] + * @returns {Boolean} + */ +function boolOrFn(val, args) { + if (typeof val == TYPE_FUNCTION) { + return val.apply(args ? args[0] || undefined : undefined, args); + } + return val; +} + +/** + * use the val2 when val1 is undefined + * @param {*} val1 + * @param {*} val2 + * @returns {*} + */ +function ifUndefined(val1, val2) { + return (val1 === undefined) ? val2 : val1; +} + +/** + * addEventListener with multiple events at once + * @param {EventTarget} target + * @param {String} types + * @param {Function} handler + */ +function addEventListeners(target, types, handler) { + each(splitStr(types), function(type) { + target.addEventListener(type, handler, false); + }); +} + +/** + * removeEventListener with multiple events at once + * @param {EventTarget} target + * @param {String} types + * @param {Function} handler + */ +function removeEventListeners(target, types, handler) { + each(splitStr(types), function(type) { + target.removeEventListener(type, handler, false); + }); +} + +/** + * find if a node is in the given parent + * @method hasParent + * @param {HTMLElement} node + * @param {HTMLElement} parent + * @return {Boolean} found + */ +function hasParent(node, parent) { + while (node) { + if (node == parent) { + return true; + } + node = node.parentNode; + } + return false; +} + +/** + * small indexOf wrapper + * @param {String} str + * @param {String} find + * @returns {Boolean} found + */ +function inStr(str, find) { + return str.indexOf(find) > -1; +} + +/** + * split string on whitespace + * @param {String} str + * @returns {Array} words + */ +function splitStr(str) { + return str.trim().split(/\s+/g); +} + +/** + * find if a array contains the object using indexOf or a simple polyFill + * @param {Array} src + * @param {String} find + * @param {String} [findByKey] + * @return {Boolean|Number} false when not found, or the index + */ +function inArray(src, find, findByKey) { + if (src.indexOf && !findByKey) { + return src.indexOf(find); + } else { + var i = 0; + while (i < src.length) { + if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { + return i; + } + i++; + } + return -1; + } +} + +/** + * convert array-like objects to real arrays + * @param {Object} obj + * @returns {Array} + */ +function toArray(obj) { + return Array.prototype.slice.call(obj, 0); +} + +/** + * unique array with objects based on a key (like 'id') or just by the array's value + * @param {Array} src [{id:1},{id:2},{id:1}] + * @param {String} [key] + * @param {Boolean} [sort=False] + * @returns {Array} [{id:1},{id:2}] + */ +function uniqueArray(src, key, sort) { + var results = []; + var values = []; + var i = 0; + + while (i < src.length) { + var val = key ? src[i][key] : src[i]; + if (inArray(values, val) < 0) { + results.push(src[i]); + } + values[i] = val; + i++; + } + + if (sort) { + if (!key) { + results = results.sort(); + } else { + results = results.sort(function sortUniqueArray(a, b) { + return a[key] > b[key]; + }); + } + } + + return results; +} + +/** + * get the prefixed property + * @param {Object} obj + * @param {String} property + * @returns {String|Undefined} prefixed + */ +function prefixed(obj, property) { + var prefix, prop; + var camelProp = property[0].toUpperCase() + property.slice(1); + + var i = 0; + while (i < VENDOR_PREFIXES.length) { + prefix = VENDOR_PREFIXES[i]; + prop = (prefix) ? prefix + camelProp : property; + + if (prop in obj) { + return prop; + } + i++; + } + return undefined; +} + +/** + * get a unique id + * @returns {number} uniqueId + */ +var _uniqueId = 1; +function uniqueId() { + return _uniqueId++; +} + +/** + * get the window object of an element + * @param {HTMLElement} element + * @returns {DocumentView|Window} + */ +function getWindowForElement(element) { + var doc = element.ownerDocument || element; + return (doc.defaultView || doc.parentWindow || window); +} + +var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; + +var SUPPORT_TOUCH = ('ontouchstart' in window); +var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; +var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); + +var INPUT_TYPE_TOUCH = 'touch'; +var INPUT_TYPE_PEN = 'pen'; +var INPUT_TYPE_MOUSE = 'mouse'; +var INPUT_TYPE_KINECT = 'kinect'; + +var COMPUTE_INTERVAL = 25; + +var INPUT_START = 1; +var INPUT_MOVE = 2; +var INPUT_END = 4; +var INPUT_CANCEL = 8; + +var DIRECTION_NONE = 1; +var DIRECTION_LEFT = 2; +var DIRECTION_RIGHT = 4; +var DIRECTION_UP = 8; +var DIRECTION_DOWN = 16; + +var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; +var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; +var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; + +var PROPS_XY = ['x', 'y']; +var PROPS_CLIENT_XY = ['clientX', 'clientY']; + +/** + * create new input type manager + * @param {Manager} manager + * @param {Function} callback + * @returns {Input} + * @constructor + */ +function Input(manager, callback) { + var self = this; + this.manager = manager; + this.callback = callback; + this.element = manager.element; + this.target = manager.options.inputTarget; + + // smaller wrapper around the handler, for the scope and the enabled state of the manager, + // so when disabled the input events are completely bypassed. + this.domHandler = function(ev) { + if (boolOrFn(manager.options.enable, [manager])) { + self.handler(ev); + } + }; + + this.init(); + +} + +Input.prototype = { + /** + * should handle the inputEvent data and trigger the callback + * @virtual + */ + handler: function() { }, + + /** + * bind the events + */ + init: function() { + this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); + this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); + this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); + }, + + /** + * unbind the events + */ + destroy: function() { + this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); + this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); + this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); + } +}; + +/** + * create new input type manager + * called by the Manager constructor + * @param {Hammer} manager + * @returns {Input} + */ +function createInputInstance(manager) { + var Type; + var inputClass = manager.options.inputClass; + + if (inputClass) { + Type = inputClass; + } else if (SUPPORT_POINTER_EVENTS) { + Type = PointerEventInput; + } else if (SUPPORT_ONLY_TOUCH) { + Type = TouchInput; + } else if (!SUPPORT_TOUCH) { + Type = MouseInput; + } else { + Type = TouchMouseInput; + } + return new (Type)(manager, inputHandler); +} + +/** + * handle input events + * @param {Manager} manager + * @param {String} eventType + * @param {Object} input + */ +function inputHandler(manager, eventType, input) { + var pointersLen = input.pointers.length; + var changedPointersLen = input.changedPointers.length; + var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); + var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); + + input.isFirst = !!isFirst; + input.isFinal = !!isFinal; + + if (isFirst) { + manager.session = {}; + } + + // source event is the normalized value of the domEvents + // like 'touchstart, mouseup, pointerdown' + input.eventType = eventType; + + // compute scale, rotation etc + computeInputData(manager, input); + + // emit secret event + manager.emit('hammer.input', input); + + manager.recognize(input); + manager.session.prevInput = input; +} + +/** + * extend the data with some usable properties like scale, rotate, velocity etc + * @param {Object} manager + * @param {Object} input + */ +function computeInputData(manager, input) { + var session = manager.session; + var pointers = input.pointers; + var pointersLength = pointers.length; + + // store the first input to calculate the distance and direction + if (!session.firstInput) { + session.firstInput = simpleCloneInputData(input); + } + + // to compute scale and rotation we need to store the multiple touches + if (pointersLength > 1 && !session.firstMultiple) { + session.firstMultiple = simpleCloneInputData(input); + } else if (pointersLength === 1) { + session.firstMultiple = false; + } + + var firstInput = session.firstInput; + var firstMultiple = session.firstMultiple; + var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; + + var center = input.center = getCenter(pointers); + input.timeStamp = now(); + input.deltaTime = input.timeStamp - firstInput.timeStamp; + + input.angle = getAngle(offsetCenter, center); + input.distance = getDistance(offsetCenter, center); + + computeDeltaXY(session, input); + input.offsetDirection = getDirection(input.deltaX, input.deltaY); + + var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY); + input.overallVelocityX = overallVelocity.x; + input.overallVelocityY = overallVelocity.y; + input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y; + + input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; + input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; + + input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length > + session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers); + + computeIntervalInputData(session, input); + + // find the correct target + var target = manager.element; + if (hasParent(input.srcEvent.target, target)) { + target = input.srcEvent.target; + } + input.target = target; +} + +function computeDeltaXY(session, input) { + var center = input.center; + var offset = session.offsetDelta || {}; + var prevDelta = session.prevDelta || {}; + var prevInput = session.prevInput || {}; + + if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { + prevDelta = session.prevDelta = { + x: prevInput.deltaX || 0, + y: prevInput.deltaY || 0 + }; + + offset = session.offsetDelta = { + x: center.x, + y: center.y + }; + } + + input.deltaX = prevDelta.x + (center.x - offset.x); + input.deltaY = prevDelta.y + (center.y - offset.y); +} + +/** + * velocity is calculated every x ms + * @param {Object} session + * @param {Object} input + */ +function computeIntervalInputData(session, input) { + var last = session.lastInterval || input, + deltaTime = input.timeStamp - last.timeStamp, + velocity, velocityX, velocityY, direction; + + if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { + var deltaX = input.deltaX - last.deltaX; + var deltaY = input.deltaY - last.deltaY; + + var v = getVelocity(deltaTime, deltaX, deltaY); + velocityX = v.x; + velocityY = v.y; + velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; + direction = getDirection(deltaX, deltaY); + + session.lastInterval = input; + } else { + // use latest velocity info if it doesn't overtake a minimum period + velocity = last.velocity; + velocityX = last.velocityX; + velocityY = last.velocityY; + direction = last.direction; + } + + input.velocity = velocity; + input.velocityX = velocityX; + input.velocityY = velocityY; + input.direction = direction; +} + +/** + * create a simple clone from the input used for storage of firstInput and firstMultiple + * @param {Object} input + * @returns {Object} clonedInputData + */ +function simpleCloneInputData(input) { + // make a simple copy of the pointers because we will get a reference if we don't + // we only need clientXY for the calculations + var pointers = []; + var i = 0; + while (i < input.pointers.length) { + pointers[i] = { + clientX: round(input.pointers[i].clientX), + clientY: round(input.pointers[i].clientY) + }; + i++; + } + + return { + timeStamp: now(), + pointers: pointers, + center: getCenter(pointers), + deltaX: input.deltaX, + deltaY: input.deltaY + }; +} + +/** + * get the center of all the pointers + * @param {Array} pointers + * @return {Object} center contains `x` and `y` properties + */ +function getCenter(pointers) { + var pointersLength = pointers.length; + + // no need to loop when only one touch + if (pointersLength === 1) { + return { + x: round(pointers[0].clientX), + y: round(pointers[0].clientY) + }; + } + + var x = 0, y = 0, i = 0; + while (i < pointersLength) { + x += pointers[i].clientX; + y += pointers[i].clientY; + i++; + } + + return { + x: round(x / pointersLength), + y: round(y / pointersLength) + }; +} + +/** + * calculate the velocity between two points. unit is in px per ms. + * @param {Number} deltaTime + * @param {Number} x + * @param {Number} y + * @return {Object} velocity `x` and `y` + */ +function getVelocity(deltaTime, x, y) { + return { + x: x / deltaTime || 0, + y: y / deltaTime || 0 + }; +} + +/** + * get the direction between two points + * @param {Number} x + * @param {Number} y + * @return {Number} direction + */ +function getDirection(x, y) { + if (x === y) { + return DIRECTION_NONE; + } + + if (abs(x) >= abs(y)) { + return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; + } + return y < 0 ? DIRECTION_UP : DIRECTION_DOWN; +} + +/** + * calculate the absolute distance between two points + * @param {Object} p1 {x, y} + * @param {Object} p2 {x, y} + * @param {Array} [props] containing x and y keys + * @return {Number} distance + */ +function getDistance(p1, p2, props) { + if (!props) { + props = PROPS_XY; + } + var x = p2[props[0]] - p1[props[0]], + y = p2[props[1]] - p1[props[1]]; + + return Math.sqrt((x * x) + (y * y)); +} + +/** + * calculate the angle between two coordinates + * @param {Object} p1 + * @param {Object} p2 + * @param {Array} [props] containing x and y keys + * @return {Number} angle + */ +function getAngle(p1, p2, props) { + if (!props) { + props = PROPS_XY; + } + var x = p2[props[0]] - p1[props[0]], + y = p2[props[1]] - p1[props[1]]; + return Math.atan2(y, x) * 180 / Math.PI; +} + +/** + * calculate the rotation degrees between two pointersets + * @param {Array} start array of pointers + * @param {Array} end array of pointers + * @return {Number} rotation + */ +function getRotation(start, end) { + return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY); +} + +/** + * calculate the scale factor between two pointersets + * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out + * @param {Array} start array of pointers + * @param {Array} end array of pointers + * @return {Number} scale + */ +function getScale(start, end) { + return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY); +} + +var MOUSE_INPUT_MAP = { + mousedown: INPUT_START, + mousemove: INPUT_MOVE, + mouseup: INPUT_END +}; + +var MOUSE_ELEMENT_EVENTS = 'mousedown'; +var MOUSE_WINDOW_EVENTS = 'mousemove mouseup'; + +/** + * Mouse events input + * @constructor + * @extends Input + */ +function MouseInput() { + this.evEl = MOUSE_ELEMENT_EVENTS; + this.evWin = MOUSE_WINDOW_EVENTS; + + this.pressed = false; // mousedown state + + Input.apply(this, arguments); +} + +inherit(MouseInput, Input, { + /** + * handle mouse events + * @param {Object} ev + */ + handler: function MEhandler(ev) { + var eventType = MOUSE_INPUT_MAP[ev.type]; + + // on start we want to have the left mouse button down + if (eventType & INPUT_START && ev.button === 0) { + this.pressed = true; + } + + if (eventType & INPUT_MOVE && ev.which !== 1) { + eventType = INPUT_END; + } + + // mouse must be down + if (!this.pressed) { + return; + } + + if (eventType & INPUT_END) { + this.pressed = false; + } + + this.callback(this.manager, eventType, { + pointers: [ev], + changedPointers: [ev], + pointerType: INPUT_TYPE_MOUSE, + srcEvent: ev + }); + } +}); + +var POINTER_INPUT_MAP = { + pointerdown: INPUT_START, + pointermove: INPUT_MOVE, + pointerup: INPUT_END, + pointercancel: INPUT_CANCEL, + pointerout: INPUT_CANCEL +}; + +// in IE10 the pointer types is defined as an enum +var IE10_POINTER_TYPE_ENUM = { + 2: INPUT_TYPE_TOUCH, + 3: INPUT_TYPE_PEN, + 4: INPUT_TYPE_MOUSE, + 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816 +}; + +var POINTER_ELEMENT_EVENTS = 'pointerdown'; +var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; + +// IE10 has prefixed support, and case-sensitive +if (window.MSPointerEvent && !window.PointerEvent) { + POINTER_ELEMENT_EVENTS = 'MSPointerDown'; + POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel'; +} + +/** + * Pointer events input + * @constructor + * @extends Input + */ +function PointerEventInput() { + this.evEl = POINTER_ELEMENT_EVENTS; + this.evWin = POINTER_WINDOW_EVENTS; + + Input.apply(this, arguments); + + this.store = (this.manager.session.pointerEvents = []); +} + +inherit(PointerEventInput, Input, { + /** + * handle mouse events + * @param {Object} ev + */ + handler: function PEhandler(ev) { + var store = this.store; + var removePointer = false; + + var eventTypeNormalized = ev.type.toLowerCase().replace('ms', ''); + var eventType = POINTER_INPUT_MAP[eventTypeNormalized]; + var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType; + + var isTouch = (pointerType == INPUT_TYPE_TOUCH); + + // get index of the event in the store + var storeIndex = inArray(store, ev.pointerId, 'pointerId'); + + // start and mouse must be down + if (eventType & INPUT_START && (ev.button === 0 || isTouch)) { + if (storeIndex < 0) { + store.push(ev); + storeIndex = store.length - 1; + } + } else if (eventType & (INPUT_END | INPUT_CANCEL)) { + removePointer = true; + } + + // it not found, so the pointer hasn't been down (so it's probably a hover) + if (storeIndex < 0) { + return; + } + + // update the event in the store + store[storeIndex] = ev; + + this.callback(this.manager, eventType, { + pointers: store, + changedPointers: [ev], + pointerType: pointerType, + srcEvent: ev + }); + + if (removePointer) { + // remove from the store + store.splice(storeIndex, 1); + } + } +}); + +var SINGLE_TOUCH_INPUT_MAP = { + touchstart: INPUT_START, + touchmove: INPUT_MOVE, + touchend: INPUT_END, + touchcancel: INPUT_CANCEL +}; + +var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart'; +var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel'; + +/** + * Touch events input + * @constructor + * @extends Input + */ +function SingleTouchInput() { + this.evTarget = SINGLE_TOUCH_TARGET_EVENTS; + this.evWin = SINGLE_TOUCH_WINDOW_EVENTS; + this.started = false; + + Input.apply(this, arguments); +} + +inherit(SingleTouchInput, Input, { + handler: function TEhandler(ev) { + var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; + + // should we handle the touch events? + if (type === INPUT_START) { + this.started = true; + } + + if (!this.started) { + return; + } + + var touches = normalizeSingleTouches.call(this, ev, type); + + // when done, reset the started state + if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) { + this.started = false; + } + + this.callback(this.manager, type, { + pointers: touches[0], + changedPointers: touches[1], + pointerType: INPUT_TYPE_TOUCH, + srcEvent: ev + }); + } +}); + +/** + * @this {TouchInput} + * @param {Object} ev + * @param {Number} type flag + * @returns {undefined|Array} [all, changed] + */ +function normalizeSingleTouches(ev, type) { + var all = toArray(ev.touches); + var changed = toArray(ev.changedTouches); + + if (type & (INPUT_END | INPUT_CANCEL)) { + all = uniqueArray(all.concat(changed), 'identifier', true); + } + + return [all, changed]; +} + +var TOUCH_INPUT_MAP = { + touchstart: INPUT_START, + touchmove: INPUT_MOVE, + touchend: INPUT_END, + touchcancel: INPUT_CANCEL +}; + +var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel'; + +/** + * Multi-user touch events input + * @constructor + * @extends Input + */ +function TouchInput() { + this.evTarget = TOUCH_TARGET_EVENTS; + this.targetIds = {}; + + Input.apply(this, arguments); +} + +inherit(TouchInput, Input, { + handler: function MTEhandler(ev) { + var type = TOUCH_INPUT_MAP[ev.type]; + var touches = getTouches.call(this, ev, type); + if (!touches) { + return; + } + + this.callback(this.manager, type, { + pointers: touches[0], + changedPointers: touches[1], + pointerType: INPUT_TYPE_TOUCH, + srcEvent: ev + }); + } +}); + +/** + * @this {TouchInput} + * @param {Object} ev + * @param {Number} type flag + * @returns {undefined|Array} [all, changed] + */ +function getTouches(ev, type) { + var allTouches = toArray(ev.touches); + var targetIds = this.targetIds; + + // when there is only one touch, the process can be simplified + if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) { + targetIds[allTouches[0].identifier] = true; + return [allTouches, allTouches]; + } + + var i, + targetTouches, + changedTouches = toArray(ev.changedTouches), + changedTargetTouches = [], + target = this.target; + + // get target touches from touches + targetTouches = allTouches.filter(function(touch) { + return hasParent(touch.target, target); + }); + + // collect touches + if (type === INPUT_START) { + i = 0; + while (i < targetTouches.length) { + targetIds[targetTouches[i].identifier] = true; + i++; + } + } + + // filter changed touches to only contain touches that exist in the collected target ids + i = 0; + while (i < changedTouches.length) { + if (targetIds[changedTouches[i].identifier]) { + changedTargetTouches.push(changedTouches[i]); + } + + // cleanup removed touches + if (type & (INPUT_END | INPUT_CANCEL)) { + delete targetIds[changedTouches[i].identifier]; + } + i++; + } + + if (!changedTargetTouches.length) { + return; + } + + return [ + // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel' + uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), + changedTargetTouches + ]; +} + +/** + * Combined touch and mouse input + * + * Touch has a higher priority then mouse, and while touching no mouse events are allowed. + * This because touch devices also emit mouse events while doing a touch. + * + * @constructor + * @extends Input + */ + +var DEDUP_TIMEOUT = 2500; +var DEDUP_DISTANCE = 25; + +function TouchMouseInput() { + Input.apply(this, arguments); + + var handler = bindFn(this.handler, this); + this.touch = new TouchInput(this.manager, handler); + this.mouse = new MouseInput(this.manager, handler); + + this.primaryTouch = null; + this.lastTouches = []; +} + +inherit(TouchMouseInput, Input, { + /** + * handle mouse and touch events + * @param {Hammer} manager + * @param {String} inputEvent + * @param {Object} inputData + */ + handler: function TMEhandler(manager, inputEvent, inputData) { + var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), + isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); + + if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) { + return; + } + + // when we're in a touch event, record touches to de-dupe synthetic mouse event + if (isTouch) { + recordTouches.call(this, inputEvent, inputData); + } else if (isMouse && isSyntheticEvent.call(this, inputData)) { + return; + } + + this.callback(manager, inputEvent, inputData); + }, + + /** + * remove the event listeners + */ + destroy: function destroy() { + this.touch.destroy(); + this.mouse.destroy(); + } +}); + +function recordTouches(eventType, eventData) { + if (eventType & INPUT_START) { + this.primaryTouch = eventData.changedPointers[0].identifier; + setLastTouch.call(this, eventData); + } else if (eventType & (INPUT_END | INPUT_CANCEL)) { + setLastTouch.call(this, eventData); + } +} + +function setLastTouch(eventData) { + var touch = eventData.changedPointers[0]; + + if (touch.identifier === this.primaryTouch) { + var lastTouch = {x: touch.clientX, y: touch.clientY}; + this.lastTouches.push(lastTouch); + var lts = this.lastTouches; + var removeLastTouch = function() { + var i = lts.indexOf(lastTouch); + if (i > -1) { + lts.splice(i, 1); + } + }; + setTimeout(removeLastTouch, DEDUP_TIMEOUT); + } +} + +function isSyntheticEvent(eventData) { + var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY; + for (var i = 0; i < this.lastTouches.length; i++) { + var t = this.lastTouches[i]; + var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y); + if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) { + return true; + } + } + return false; +} + +var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); +var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; + +// magical touchAction value +var TOUCH_ACTION_COMPUTE = 'compute'; +var TOUCH_ACTION_AUTO = 'auto'; +var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented +var TOUCH_ACTION_NONE = 'none'; +var TOUCH_ACTION_PAN_X = 'pan-x'; +var TOUCH_ACTION_PAN_Y = 'pan-y'; +var TOUCH_ACTION_MAP = getTouchActionProps(); + +/** + * Touch Action + * sets the touchAction property or uses the js alternative + * @param {Manager} manager + * @param {String} value + * @constructor + */ +function TouchAction(manager, value) { + this.manager = manager; + this.set(value); +} + +TouchAction.prototype = { + /** + * set the touchAction value on the element or enable the polyfill + * @param {String} value + */ + set: function(value) { + // find out the touch-action by the event handlers + if (value == TOUCH_ACTION_COMPUTE) { + value = this.compute(); + } + + if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) { + this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; + } + this.actions = value.toLowerCase().trim(); + }, + + /** + * just re-set the touchAction value + */ + update: function() { + this.set(this.manager.options.touchAction); + }, + + /** + * compute the value for the touchAction property based on the recognizer's settings + * @returns {String} value + */ + compute: function() { + var actions = []; + each(this.manager.recognizers, function(recognizer) { + if (boolOrFn(recognizer.options.enable, [recognizer])) { + actions = actions.concat(recognizer.getTouchAction()); + } + }); + return cleanTouchActions(actions.join(' ')); + }, + + /** + * this method is called on each input cycle and provides the preventing of the browser behavior + * @param {Object} input + */ + preventDefaults: function(input) { + var srcEvent = input.srcEvent; + var direction = input.offsetDirection; + + // if the touch action did prevented once this session + if (this.manager.session.prevented) { + srcEvent.preventDefault(); + return; + } + + var actions = this.actions; + var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE]; + var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y]; + var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X]; + + if (hasNone) { + //do not prevent defaults if this is a tap gesture + + var isTapPointer = input.pointers.length === 1; + var isTapMovement = input.distance < 2; + var isTapTouchTime = input.deltaTime < 250; + + if (isTapPointer && isTapMovement && isTapTouchTime) { + return; + } + } + + if (hasPanX && hasPanY) { + // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent + return; + } + + if (hasNone || + (hasPanY && direction & DIRECTION_HORIZONTAL) || + (hasPanX && direction & DIRECTION_VERTICAL)) { + return this.preventSrc(srcEvent); + } + }, + + /** + * call preventDefault to prevent the browser's default behavior (scrolling in most cases) + * @param {Object} srcEvent + */ + preventSrc: function(srcEvent) { + this.manager.session.prevented = true; + srcEvent.preventDefault(); + } +}; + +/** + * when the touchActions are collected they are not a valid value, so we need to clean things up. * + * @param {String} actions + * @returns {*} + */ +function cleanTouchActions(actions) { + // none + if (inStr(actions, TOUCH_ACTION_NONE)) { + return TOUCH_ACTION_NONE; + } + + var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); + var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); + + // if both pan-x and pan-y are set (different recognizers + // for different directions, e.g. horizontal pan but vertical swipe?) + // we need none (as otherwise with pan-x pan-y combined none of these + // recognizers will work, since the browser would handle all panning + if (hasPanX && hasPanY) { + return TOUCH_ACTION_NONE; + } + + // pan-x OR pan-y + if (hasPanX || hasPanY) { + return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; + } + + // manipulation + if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { + return TOUCH_ACTION_MANIPULATION; + } + + return TOUCH_ACTION_AUTO; +} + +function getTouchActionProps() { + if (!NATIVE_TOUCH_ACTION) { + return false; + } + var touchMap = {}; + var cssSupports = window.CSS && window.CSS.supports; + ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) { + + // If css.supports is not supported but there is native touch-action assume it supports + // all values. This is the case for IE 10 and 11. + touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true; + }); + return touchMap; +} + +/** + * Recognizer flow explained; * + * All recognizers have the initial state of POSSIBLE when a input session starts. + * The definition of a input session is from the first input until the last input, with all it's movement in it. * + * Example session for mouse-input: mousedown -> mousemove -> mouseup + * + * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed + * which determines with state it should be. + * + * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to + * POSSIBLE to give it another change on the next cycle. + * + * Possible + * | + * +-----+---------------+ + * | | + * +-----+-----+ | + * | | | + * Failed Cancelled | + * +-------+------+ + * | | + * Recognized Began + * | + * Changed + * | + * Ended/Recognized + */ +var STATE_POSSIBLE = 1; +var STATE_BEGAN = 2; +var STATE_CHANGED = 4; +var STATE_ENDED = 8; +var STATE_RECOGNIZED = STATE_ENDED; +var STATE_CANCELLED = 16; +var STATE_FAILED = 32; + +/** + * Recognizer + * Every recognizer needs to extend from this class. + * @constructor + * @param {Object} options + */ +function Recognizer(options) { + this.options = assign({}, this.defaults, options || {}); + + this.id = uniqueId(); + + this.manager = null; + + // default is enable true + this.options.enable = ifUndefined(this.options.enable, true); + + this.state = STATE_POSSIBLE; + + this.simultaneous = {}; + this.requireFail = []; +} + +Recognizer.prototype = { + /** + * @virtual + * @type {Object} + */ + defaults: {}, + + /** + * set options + * @param {Object} options + * @return {Recognizer} + */ + set: function(options) { + assign(this.options, options); + + // also update the touchAction, in case something changed about the directions/enabled state + this.manager && this.manager.touchAction.update(); + return this; + }, + + /** + * recognize simultaneous with an other recognizer. + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + recognizeWith: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { + return this; + } + + var simultaneous = this.simultaneous; + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + if (!simultaneous[otherRecognizer.id]) { + simultaneous[otherRecognizer.id] = otherRecognizer; + otherRecognizer.recognizeWith(this); + } + return this; + }, + + /** + * drop the simultaneous link. it doesnt remove the link on the other recognizer. + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + dropRecognizeWith: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { + return this; + } + + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + delete this.simultaneous[otherRecognizer.id]; + return this; + }, + + /** + * recognizer can only run when an other is failing + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + requireFailure: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { + return this; + } + + var requireFail = this.requireFail; + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + if (inArray(requireFail, otherRecognizer) === -1) { + requireFail.push(otherRecognizer); + otherRecognizer.requireFailure(this); + } + return this; + }, + + /** + * drop the requireFailure link. it does not remove the link on the other recognizer. + * @param {Recognizer} otherRecognizer + * @returns {Recognizer} this + */ + dropRequireFailure: function(otherRecognizer) { + if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { + return this; + } + + otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); + var index = inArray(this.requireFail, otherRecognizer); + if (index > -1) { + this.requireFail.splice(index, 1); + } + return this; + }, + + /** + * has require failures boolean + * @returns {boolean} + */ + hasRequireFailures: function() { + return this.requireFail.length > 0; + }, + + /** + * if the recognizer can recognize simultaneous with an other recognizer + * @param {Recognizer} otherRecognizer + * @returns {Boolean} + */ + canRecognizeWith: function(otherRecognizer) { + return !!this.simultaneous[otherRecognizer.id]; + }, + + /** + * You should use `tryEmit` instead of `emit` directly to check + * that all the needed recognizers has failed before emitting. + * @param {Object} input + */ + emit: function(input) { + var self = this; + var state = this.state; + + function emit(event) { + self.manager.emit(event, input); + } + + // 'panstart' and 'panmove' + if (state < STATE_ENDED) { + emit(self.options.event + stateStr(state)); + } + + emit(self.options.event); // simple 'eventName' events + + if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...) + emit(input.additionalEvent); + } + + // panend and pancancel + if (state >= STATE_ENDED) { + emit(self.options.event + stateStr(state)); + } + }, + + /** + * Check that all the require failure recognizers has failed, + * if true, it emits a gesture event, + * otherwise, setup the state to FAILED. + * @param {Object} input + */ + tryEmit: function(input) { + if (this.canEmit()) { + return this.emit(input); + } + // it's failing anyway + this.state = STATE_FAILED; + }, + + /** + * can we emit? + * @returns {boolean} + */ + canEmit: function() { + var i = 0; + while (i < this.requireFail.length) { + if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { + return false; + } + i++; + } return true; - }; - return ScopeChecker; -}()); -exports.ScopeChecker = ScopeChecker; - -},{"./utils":20}],10:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var SymbolTree = /** @class */ (function () { - function SymbolTree(mapper) { - this.mapper = mapper; - this.tree = [undefined, {}]; - } - SymbolTree.prototype.set = function (path, element, max) { - var curr = this.tree; - var _max = max !== undefined ? max : path.length; - for (var i = 0; i < _max; i++) { - var n = this.mapper(path[i]); - var child = curr[1][n]; - if (!child) { - child = [undefined, {}]; - curr[1][n] = child; + }, + + /** + * update the recognizer + * @param {Object} inputData + */ + recognize: function(inputData) { + // make a new copy of the inputData + // so we can change the inputData without messing up the other recognizers + var inputDataClone = assign({}, inputData); + + // is is enabled and allow recognizing? + if (!boolOrFn(this.options.enable, [this, inputDataClone])) { + this.reset(); + this.state = STATE_FAILED; + return; + } + + // reset when we've reached the end + if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { + this.state = STATE_POSSIBLE; + } + + this.state = this.process(inputDataClone); + + // the recognizer has recognized a gesture + // so trigger an event + if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { + this.tryEmit(inputDataClone); + } + }, + + /** + * return the state of the recognizer + * the actual recognizing happens in this method + * @virtual + * @param {Object} inputData + * @returns {Const} STATE + */ + process: function(inputData) { }, // jshint ignore:line + + /** + * return the preferred touch-action + * @virtual + * @returns {Array} + */ + getTouchAction: function() { }, + + /** + * called when the gesture isn't allowed to recognize + * like when another is being recognized or it is disabled + * @virtual + */ + reset: function() { } +}; + +/** + * get a usable string, used as event postfix + * @param {Const} state + * @returns {String} state + */ +function stateStr(state) { + if (state & STATE_CANCELLED) { + return 'cancel'; + } else if (state & STATE_ENDED) { + return 'end'; + } else if (state & STATE_CHANGED) { + return 'move'; + } else if (state & STATE_BEGAN) { + return 'start'; + } + return ''; +} + +/** + * direction cons to string + * @param {Const} direction + * @returns {String} + */ +function directionStr(direction) { + if (direction == DIRECTION_DOWN) { + return 'down'; + } else if (direction == DIRECTION_UP) { + return 'up'; + } else if (direction == DIRECTION_LEFT) { + return 'left'; + } else if (direction == DIRECTION_RIGHT) { + return 'right'; + } + return ''; +} + +/** + * get a recognizer by name if it is bound to a manager + * @param {Recognizer|String} otherRecognizer + * @param {Recognizer} recognizer + * @returns {Recognizer} + */ +function getRecognizerByNameIfManager(otherRecognizer, recognizer) { + var manager = recognizer.manager; + if (manager) { + return manager.get(otherRecognizer); + } + return otherRecognizer; +} + +/** + * This recognizer is just used as a base for the simple attribute recognizers. + * @constructor + * @extends Recognizer + */ +function AttrRecognizer() { + Recognizer.apply(this, arguments); +} + +inherit(AttrRecognizer, Recognizer, { + /** + * @namespace + * @memberof AttrRecognizer + */ + defaults: { + /** + * @type {Number} + * @default 1 + */ + pointers: 1 + }, + + /** + * Used to check if it the recognizer receives valid input, like input.distance > 10. + * @memberof AttrRecognizer + * @param {Object} input + * @returns {Boolean} recognized + */ + attrTest: function(input) { + var optionPointers = this.options.pointers; + return optionPointers === 0 || input.pointers.length === optionPointers; + }, + + /** + * Process the input and return the state for the recognizer + * @memberof AttrRecognizer + * @param {Object} input + * @returns {*} State + */ + process: function(input) { + var state = this.state; + var eventType = input.eventType; + + var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); + var isValid = this.attrTest(input); + + // on cancel input and we've recognized before, return STATE_CANCELLED + if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { + return state | STATE_CANCELLED; + } else if (isRecognized || isValid) { + if (eventType & INPUT_END) { + return state | STATE_ENDED; + } else if (!(state & STATE_BEGAN)) { + return STATE_BEGAN; + } + return state | STATE_CHANGED; + } + return STATE_FAILED; + } +}); + +/** + * Pan + * Recognized when the pointer is down and moved in the allowed direction. + * @constructor + * @extends AttrRecognizer + */ +function PanRecognizer() { + AttrRecognizer.apply(this, arguments); + + this.pX = null; + this.pY = null; +} + +inherit(PanRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof PanRecognizer + */ + defaults: { + event: 'pan', + threshold: 10, + pointers: 1, + direction: DIRECTION_ALL + }, + + getTouchAction: function() { + var direction = this.options.direction; + var actions = []; + if (direction & DIRECTION_HORIZONTAL) { + actions.push(TOUCH_ACTION_PAN_Y); + } + if (direction & DIRECTION_VERTICAL) { + actions.push(TOUCH_ACTION_PAN_X); + } + return actions; + }, + + directionTest: function(input) { + var options = this.options; + var hasMoved = true; + var distance = input.distance; + var direction = input.direction; + var x = input.deltaX; + var y = input.deltaY; + + // lock to axis? + if (!(direction & options.direction)) { + if (options.direction & DIRECTION_HORIZONTAL) { + direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; + hasMoved = x != this.pX; + distance = Math.abs(input.deltaX); + } else { + direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; + hasMoved = y != this.pY; + distance = Math.abs(input.deltaY); + } + } + input.direction = direction; + return hasMoved && distance > options.threshold && direction & options.direction; + }, + + attrTest: function(input) { + return AttrRecognizer.prototype.attrTest.call(this, input) && + (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); + }, + + emit: function(input) { + + this.pX = input.deltaX; + this.pY = input.deltaY; + + var direction = directionStr(input.direction); + + if (direction) { + input.additionalEvent = this.options.event + direction; + } + this._super.emit.call(this, input); + } +}); + +/** + * Pinch + * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). + * @constructor + * @extends AttrRecognizer + */ +function PinchRecognizer() { + AttrRecognizer.apply(this, arguments); +} + +inherit(PinchRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof PinchRecognizer + */ + defaults: { + event: 'pinch', + threshold: 0, + pointers: 2 + }, + + getTouchAction: function() { + return [TOUCH_ACTION_NONE]; + }, + + attrTest: function(input) { + return this._super.attrTest.call(this, input) && + (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); + }, + + emit: function(input) { + if (input.scale !== 1) { + var inOut = input.scale < 1 ? 'in' : 'out'; + input.additionalEvent = this.options.event + inOut; + } + this._super.emit.call(this, input); + } +}); + +/** + * Press + * Recognized when the pointer is down for x ms without any movement. + * @constructor + * @extends Recognizer + */ +function PressRecognizer() { + Recognizer.apply(this, arguments); + + this._timer = null; + this._input = null; +} + +inherit(PressRecognizer, Recognizer, { + /** + * @namespace + * @memberof PressRecognizer + */ + defaults: { + event: 'press', + pointers: 1, + time: 251, // minimal time of the pointer to be pressed + threshold: 9 // a minimal movement is ok, but keep it low + }, + + getTouchAction: function() { + return [TOUCH_ACTION_AUTO]; + }, + + process: function(input) { + var options = this.options; + var validPointers = input.pointers.length === options.pointers; + var validMovement = input.distance < options.threshold; + var validTime = input.deltaTime > options.time; + + this._input = input; + + // we only allow little movement + // and we've reached an end event, so a tap is possible + if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { + this.reset(); + } else if (input.eventType & INPUT_START) { + this.reset(); + this._timer = setTimeoutContext(function() { + this.state = STATE_RECOGNIZED; + this.tryEmit(); + }, options.time, this); + } else if (input.eventType & INPUT_END) { + return STATE_RECOGNIZED; + } + return STATE_FAILED; + }, + + reset: function() { + clearTimeout(this._timer); + }, + + emit: function(input) { + if (this.state !== STATE_RECOGNIZED) { + return; + } + + if (input && (input.eventType & INPUT_END)) { + this.manager.emit(this.options.event + 'up', input); + } else { + this._input.timeStamp = now(); + this.manager.emit(this.options.event, this._input); + } + } +}); + +/** + * Rotate + * Recognized when two or more pointer are moving in a circular motion. + * @constructor + * @extends AttrRecognizer + */ +function RotateRecognizer() { + AttrRecognizer.apply(this, arguments); +} + +inherit(RotateRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof RotateRecognizer + */ + defaults: { + event: 'rotate', + threshold: 0, + pointers: 2 + }, + + getTouchAction: function() { + return [TOUCH_ACTION_NONE]; + }, + + attrTest: function(input) { + return this._super.attrTest.call(this, input) && + (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); + } +}); + +/** + * Swipe + * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. + * @constructor + * @extends AttrRecognizer + */ +function SwipeRecognizer() { + AttrRecognizer.apply(this, arguments); +} + +inherit(SwipeRecognizer, AttrRecognizer, { + /** + * @namespace + * @memberof SwipeRecognizer + */ + defaults: { + event: 'swipe', + threshold: 10, + velocity: 0.3, + direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, + pointers: 1 + }, + + getTouchAction: function() { + return PanRecognizer.prototype.getTouchAction.call(this); + }, + + attrTest: function(input) { + var direction = this.options.direction; + var velocity; + + if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { + velocity = input.overallVelocity; + } else if (direction & DIRECTION_HORIZONTAL) { + velocity = input.overallVelocityX; + } else if (direction & DIRECTION_VERTICAL) { + velocity = input.overallVelocityY; + } + + return this._super.attrTest.call(this, input) && + direction & input.offsetDirection && + input.distance > this.options.threshold && + input.maxPointers == this.options.pointers && + abs(velocity) > this.options.velocity && input.eventType & INPUT_END; + }, + + emit: function(input) { + var direction = directionStr(input.offsetDirection); + if (direction) { + this.manager.emit(this.options.event + direction, input); + } + + this.manager.emit(this.options.event, input); + } +}); + +/** + * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur + * between the given interval and position. The delay option can be used to recognize multi-taps without firing + * a single tap. + * + * The eventData from the emitted event contains the property `tapCount`, which contains the amount of + * multi-taps being recognized. + * @constructor + * @extends Recognizer + */ +function TapRecognizer() { + Recognizer.apply(this, arguments); + + // previous time and center, + // used for tap counting + this.pTime = false; + this.pCenter = false; + + this._timer = null; + this._input = null; + this.count = 0; +} + +inherit(TapRecognizer, Recognizer, { + /** + * @namespace + * @memberof PinchRecognizer + */ + defaults: { + event: 'tap', + pointers: 1, + taps: 1, + interval: 300, // max time between the multi-tap taps + time: 250, // max time of the pointer to be down (like finger on the screen) + threshold: 9, // a minimal movement is ok, but keep it low + posThreshold: 10 // a multi-tap can be a bit off the initial position + }, + + getTouchAction: function() { + return [TOUCH_ACTION_MANIPULATION]; + }, + + process: function(input) { + var options = this.options; + + var validPointers = input.pointers.length === options.pointers; + var validMovement = input.distance < options.threshold; + var validTouchTime = input.deltaTime < options.time; + + this.reset(); + + if ((input.eventType & INPUT_START) && (this.count === 0)) { + return this.failTimeout(); + } + + // we only allow little movement + // and we've reached an end event, so a tap is possible + if (validMovement && validTouchTime && validPointers) { + if (input.eventType != INPUT_END) { + return this.failTimeout(); + } + + var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; + var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; + + this.pTime = input.timeStamp; + this.pCenter = input.center; + + if (!validMultiTap || !validInterval) { + this.count = 1; + } else { + this.count += 1; + } + + this._input = input; + + // if tap count matches we have recognized it, + // else it has began recognizing... + var tapCount = this.count % options.taps; + if (tapCount === 0) { + // no failing requirements, immediately trigger the tap event + // or wait as long as the multitap interval to trigger + if (!this.hasRequireFailures()) { + return STATE_RECOGNIZED; + } else { + this._timer = setTimeoutContext(function() { + this.state = STATE_RECOGNIZED; + this.tryEmit(); + }, options.interval, this); + return STATE_BEGAN; + } + } + } + return STATE_FAILED; + }, + + failTimeout: function() { + this._timer = setTimeoutContext(function() { + this.state = STATE_FAILED; + }, this.options.interval, this); + return STATE_FAILED; + }, + + reset: function() { + clearTimeout(this._timer); + }, + + emit: function() { + if (this.state == STATE_RECOGNIZED) { + this._input.tapCount = this.count; + this.manager.emit(this.options.event, this._input); + } + } +}); + +/** + * Simple way to create a manager with a default set of recognizers. + * @param {HTMLElement} element + * @param {Object} [options] + * @constructor + */ +function Hammer(element, options) { + options = options || {}; + options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); + return new Manager(element, options); +} + +/** + * @const {string} + */ +Hammer.VERSION = '2.0.7'; + +/** + * default settings + * @namespace + */ +Hammer.defaults = { + /** + * set if DOM events are being triggered. + * But this is slower and unused by simple implementations, so disabled by default. + * @type {Boolean} + * @default false + */ + domEvents: false, + + /** + * The value for the touchAction property/fallback. + * When set to `compute` it will magically set the correct value based on the added recognizers. + * @type {String} + * @default compute + */ + touchAction: TOUCH_ACTION_COMPUTE, + + /** + * @type {Boolean} + * @default true + */ + enable: true, + + /** + * EXPERIMENTAL FEATURE -- can be removed/changed + * Change the parent input target element. + * If Null, then it is being set the to main element. + * @type {Null|EventTarget} + * @default null + */ + inputTarget: null, + + /** + * force an input class + * @type {Null|Function} + * @default null + */ + inputClass: null, + + /** + * Default recognizer setup when calling `Hammer()` + * When creating a new Manager these will be skipped. + * @type {Array} + */ + preset: [ + // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] + [RotateRecognizer, {enable: false}], + [PinchRecognizer, {enable: false}, ['rotate']], + [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}], + [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']], + [TapRecognizer], + [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']], + [PressRecognizer] + ], + + /** + * Some CSS properties can be used to improve the working of Hammer. + * Add them to this method and they will be set when creating a new Manager. + * @namespace + */ + cssProps: { + /** + * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. + * @type {String} + * @default 'none' + */ + userSelect: 'none', + + /** + * Disable the Windows Phone grippers when pressing an element. + * @type {String} + * @default 'none' + */ + touchSelect: 'none', + + /** + * Disables the default callout shown when you touch and hold a touch target. + * On iOS, when you touch and hold a touch target such as a link, Safari displays + * a callout containing information about the link. This property allows you to disable that callout. + * @type {String} + * @default 'none' + */ + touchCallout: 'none', + + /** + * Specifies whether zooming is enabled. Used by IE10> + * @type {String} + * @default 'none' + */ + contentZooming: 'none', + + /** + * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. + * @type {String} + * @default 'none' + */ + userDrag: 'none', + + /** + * Overrides the highlight color shown when the user taps a link or a JavaScript + * clickable element in iOS. This property obeys the alpha value, if specified. + * @type {String} + * @default 'rgba(0,0,0,0)' + */ + tapHighlightColor: 'rgba(0,0,0,0)' + } +}; + +var STOP = 1; +var FORCED_STOP = 2; + +/** + * Manager + * @param {HTMLElement} element + * @param {Object} [options] + * @constructor + */ +function Manager(element, options) { + this.options = assign({}, Hammer.defaults, options || {}); + + this.options.inputTarget = this.options.inputTarget || element; + + this.handlers = {}; + this.session = {}; + this.recognizers = []; + this.oldCssProps = {}; + + this.element = element; + this.input = createInputInstance(this); + this.touchAction = new TouchAction(this, this.options.touchAction); + + toggleCssProps(this, true); + + each(this.options.recognizers, function(item) { + var recognizer = this.add(new (item[0])(item[1])); + item[2] && recognizer.recognizeWith(item[2]); + item[3] && recognizer.requireFailure(item[3]); + }, this); +} + +Manager.prototype = { + /** + * set options + * @param {Object} options + * @returns {Manager} + */ + set: function(options) { + assign(this.options, options); + + // Options that need a little more setup + if (options.touchAction) { + this.touchAction.update(); + } + if (options.inputTarget) { + // Clean up existing event listeners and reinitialize + this.input.destroy(); + this.input.target = options.inputTarget; + this.input.init(); + } + return this; + }, + + /** + * stop recognizing for this session. + * This session will be discarded, when a new [input]start event is fired. + * When forced, the recognizer cycle is stopped immediately. + * @param {Boolean} [force] + */ + stop: function(force) { + this.session.stopped = force ? FORCED_STOP : STOP; + }, + + /** + * run the recognizers! + * called by the inputHandler function on every movement of the pointers (touches) + * it walks through all the recognizers and tries to detect the gesture that is being made + * @param {Object} inputData + */ + recognize: function(inputData) { + var session = this.session; + if (session.stopped) { + return; + } + + // run the touch-action polyfill + this.touchAction.preventDefaults(inputData); + + var recognizer; + var recognizers = this.recognizers; + + // this holds the recognizer that is being recognized. + // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED + // if no recognizer is detecting a thing, it is set to `null` + var curRecognizer = session.curRecognizer; + + // reset when the last recognizer is recognized + // or when we're in a new session + if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { + curRecognizer = session.curRecognizer = null; + } + + var i = 0; + while (i < recognizers.length) { + recognizer = recognizers[i]; + + // find out if we are allowed try to recognize the input for this one. + // 1. allow if the session is NOT forced stopped (see the .stop() method) + // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one + // that is being recognized. + // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. + // this can be setup with the `recognizeWith()` method on the recognizer. + if (session.stopped !== FORCED_STOP && ( // 1 + !curRecognizer || recognizer == curRecognizer || // 2 + recognizer.canRecognizeWith(curRecognizer))) { // 3 + recognizer.recognize(inputData); + } else { + recognizer.reset(); + } + + // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the + // current active recognizer. but only if we don't already have an active recognizer + if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { + curRecognizer = session.curRecognizer = recognizer; + } + i++; + } + }, + + /** + * get a recognizer by its event name. + * @param {Recognizer|String} recognizer + * @returns {Recognizer|Null} + */ + get: function(recognizer) { + if (recognizer instanceof Recognizer) { + return recognizer; + } + + var recognizers = this.recognizers; + for (var i = 0; i < recognizers.length; i++) { + if (recognizers[i].options.event == recognizer) { + return recognizers[i]; + } + } + return null; + }, + + /** + * add a recognizer to the manager + * existing recognizers with the same event name will be removed + * @param {Recognizer} recognizer + * @returns {Recognizer|Manager} + */ + add: function(recognizer) { + if (invokeArrayArg(recognizer, 'add', this)) { + return this; + } + + // remove existing + var existing = this.get(recognizer.options.event); + if (existing) { + this.remove(existing); + } + + this.recognizers.push(recognizer); + recognizer.manager = this; + + this.touchAction.update(); + return recognizer; + }, + + /** + * remove a recognizer by name or instance + * @param {Recognizer|String} recognizer + * @returns {Manager} + */ + remove: function(recognizer) { + if (invokeArrayArg(recognizer, 'remove', this)) { + return this; + } + + recognizer = this.get(recognizer); + + // let's make sure this recognizer exists + if (recognizer) { + var recognizers = this.recognizers; + var index = inArray(recognizers, recognizer); + + if (index !== -1) { + recognizers.splice(index, 1); + this.touchAction.update(); + } + } + + return this; + }, + + /** + * bind event + * @param {String} events + * @param {Function} handler + * @returns {EventEmitter} this + */ + on: function(events, handler) { + if (events === undefined) { + return; + } + if (handler === undefined) { + return; + } + + var handlers = this.handlers; + each(splitStr(events), function(event) { + handlers[event] = handlers[event] || []; + handlers[event].push(handler); + }); + return this; + }, + + /** + * unbind event, leave emit blank to remove all handlers + * @param {String} events + * @param {Function} [handler] + * @returns {EventEmitter} this + */ + off: function(events, handler) { + if (events === undefined) { + return; + } + + var handlers = this.handlers; + each(splitStr(events), function(event) { + if (!handler) { + delete handlers[event]; + } else { + handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1); } - curr = child; + }); + return this; + }, + + /** + * emit event to the listeners + * @param {String} event + * @param {Object} data + */ + emit: function(event, data) { + // we also want to trigger dom events + if (this.options.domEvents) { + triggerDomEvent(event, data); + } + + // no handlers, so skip it all + var handlers = this.handlers[event] && this.handlers[event].slice(); + if (!handlers || !handlers.length) { + return; + } + + data.type = event; + data.preventDefault = function() { + data.srcEvent.preventDefault(); + }; + + var i = 0; + while (i < handlers.length) { + handlers[i](data); + i++; + } + }, + + /** + * destroy the manager and unbinds all events + * it doesn't unbind dom events, that is the user own responsibility + */ + destroy: function() { + this.element && toggleCssProps(this, false); + + this.handlers = {}; + this.session = {}; + this.input.destroy(); + this.element = null; + } +}; + +/** + * add/remove the css properties as defined in manager.options.cssProps + * @param {Manager} manager + * @param {Boolean} add + */ +function toggleCssProps(manager, add) { + var element = manager.element; + if (!element.style) { + return; + } + var prop; + each(manager.options.cssProps, function(value, name) { + prop = prefixed(element.style, name); + if (add) { + manager.oldCssProps[prop] = element.style[prop]; + element.style[prop] = value; + } else { + element.style[prop] = manager.oldCssProps[prop] || ''; + } + }); + if (!add) { + manager.oldCssProps = {}; + } +} + +/** + * trigger dom event + * @param {String} event + * @param {Object} data + */ +function triggerDomEvent(event, data) { + var gestureEvent = document.createEvent('Event'); + gestureEvent.initEvent(event, true, true); + gestureEvent.gesture = data; + data.target.dispatchEvent(gestureEvent); +} + +assign(Hammer, { + INPUT_START: INPUT_START, + INPUT_MOVE: INPUT_MOVE, + INPUT_END: INPUT_END, + INPUT_CANCEL: INPUT_CANCEL, + + STATE_POSSIBLE: STATE_POSSIBLE, + STATE_BEGAN: STATE_BEGAN, + STATE_CHANGED: STATE_CHANGED, + STATE_ENDED: STATE_ENDED, + STATE_RECOGNIZED: STATE_RECOGNIZED, + STATE_CANCELLED: STATE_CANCELLED, + STATE_FAILED: STATE_FAILED, + + DIRECTION_NONE: DIRECTION_NONE, + DIRECTION_LEFT: DIRECTION_LEFT, + DIRECTION_RIGHT: DIRECTION_RIGHT, + DIRECTION_UP: DIRECTION_UP, + DIRECTION_DOWN: DIRECTION_DOWN, + DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, + DIRECTION_VERTICAL: DIRECTION_VERTICAL, + DIRECTION_ALL: DIRECTION_ALL, + + Manager: Manager, + Input: Input, + TouchAction: TouchAction, + + TouchInput: TouchInput, + MouseInput: MouseInput, + PointerEventInput: PointerEventInput, + TouchMouseInput: TouchMouseInput, + SingleTouchInput: SingleTouchInput, + + Recognizer: Recognizer, + AttrRecognizer: AttrRecognizer, + Tap: TapRecognizer, + Pan: PanRecognizer, + Swipe: SwipeRecognizer, + Pinch: PinchRecognizer, + Rotate: RotateRecognizer, + Press: PressRecognizer, + + on: addEventListeners, + off: removeEventListeners, + each: each, + merge: merge, + extend: extend, + assign: assign, + inherit: inherit, + bindFn: bindFn, + prefixed: prefixed +}); + +// this prevents errors when Hammer is loaded in the presence of an AMD +// style loader but by script tag, not by the loader. +var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line +freeGlobal.Hammer = Hammer; + +if (typeof define === 'function' && define.amd) { + define(function() { + return Hammer; + }); +} else if (typeof module != 'undefined' && module.exports) { + module.exports = Hammer; +} else { + window[exportName] = Hammer; +} + +})(window, document, 'Hammer'); + +},{}],85:[function(require,module,exports){ +(function (process,global,Buffer,__argument0,__argument1,__argument2,__argument3,setImmediate){ +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):(e=e||self,t(e.handTrack={}))})(this,function(exports){"use strict";/** + * @license + * Copyright 2018 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var _Mathpow=Math.pow,_Mathlog=Math.log,_NumberisInteger=Number.isInteger,_StringfromCharCode=String.fromCharCode,_NumberNEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,_Mathsin=Math.sin,_Mathcos=Math.cos,_MathPI=Math.PI,_Mathabs=Math.abs,_Mathceil=Math.ceil,_NumberMAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER,_NumberMIN_SAFE_INTEGER=Number.MIN_SAFE_INTEGER,_Mathround=Math.round,_Mathfloor=Math.floor,_Mathsqrt=Math.sqrt,_Mathexp=Math.exp,_Mathmax=Math.max,_Mathmin=Math.min;function __extends(a,e){function t(){this.constructor=a}extendStatics(a,e),a.prototype=null===e?Object.create(e):(t.prototype=e.prototype,new t)}function __awaiter(p,e,t,l){return new(t||(t=Promise))(function(n,r){function a(t){try{s(l.next(t))}catch(t){r(t)}}function o(t){try{s(l.throw(t))}catch(t){r(t)}}function s(r){r.done?n(r.value):new t(function(e){e(r.value)}).then(a,o)}s((l=l.apply(p,e||[])).next())})}function __generator(p,e){function t(t){return function(a){return function(t){if(l)throw new TypeError("Generator is already executing.");for(;s;)try{if(l=1,d&&(u=2&t[0]?d.return:t[0]?d.throw||((u=d.return)&&u.call(d),0):d.next)&&!(u=u.call(d,t[1])).done)return u;switch(d=0,u&&(t=[2&t[0],u.value]),t[0]){case 0:case 1:u=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,d=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(u=0<(u=s.trys).length&&u[u.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!u||t[1]>u[0]&&t[1]=n?r():setTimeout(l,a)}};l()})}function inferFromImplicitShape(s,e){for(var t=1,i=-1,p=0;ps[p])throw Error("Shapes can not be < 0. Found "+s[p]+" at dim "+p);if(-1==i){if(0i)&&1===s[i]&&(t.push(s[i]),r.push(i)),e[n]<=i&&n++}1!==s[i]&&(t.push(s[i]),r.push(i))}return{newShape:t,keptDims:r}}function getTypedArrayFromDType(a,e){var t=null;if(null==a||"float32"===a)t=new Float32Array(e);else if("int32"===a)t=new Int32Array(e);else{if("bool"!==a)throw new Error("Unknown data type "+a);t=new Uint8Array(e)}return t}function checkComputationForNaN(a,e,t){if("float32"===e)for(var r=0;re)return[];var t=Array(e-1);t[e-2]=a[e-1];for(var r=e-3;0<=r;--r)t[r]=t[r+1]*a[r+1];return t}function toTypedArray(a,n,t){return noConversionNeeded(a,n)?a:(Array.isArray(a)&&(a=flatten(a)),copyTypedArray(a,n,t))}function noConversionNeeded(a,e){return a instanceof Float32Array&&"float32"===e||a instanceof Int32Array&&"int32"===e||a instanceof Uint8Array&&"bool"===e}function makeOnesTypedArray(a,e){for(var t=makeZerosTypedArray(a,e),r=0;r20){for(var m=0,S;m<3;m++)S=(C=m*h)+h,f.push.apply(f,subTensorToString(l.subarray(C,S),I,t,d,n,!1));for(f.push("..."),m=i-3;m=2*e+1||1==n%2?a.push(n):l.push(n);p.push.apply(p,l),p.push(0),p.push.apply(p,a)}return p}function getReshapedPermuted(s,e,t,r){void 0===r&&(r=!0);var i=[];r?i.push(s[0]/t):i.push(s[0]*t);for(var o=1;o=-t&&aa?t+a:a})}function assertAxesAreInnerMostDims(a,e,t){assert(axesAreInnerMostDims(e,t),a+" supports only inner-most axes for now. Got axes "+e+" and rank-"+t+" input.")}function getAxesPermutation(a,e){if(axesAreInnerMostDims(a,e))return null;for(var t=[],r=0;rp.rank)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+p.rank+".");if(1>e.rank)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==e.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.shape[e.rank-1]>p.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+p.rank);if(0===p.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+p.shape+".");for(var t=e.shape,r=t[t.length-1],n=1,d=0;de.rank)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(1>a.rank)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+a.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(1>t.length)throw new Error("Output rank must be greater or equal to 1, but got shape: "+t);if(0===t.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===a.size)throw new Error("Updates specified for empty output. updates shape: "+a.shape)}validateUpdateShape(t,e,a)}function calculateShapes(p,e,t){for(var r=1r?1:r,s=e.size/c,u=computeStrides(t).concat([1]);return{sliceRank:r,numUpdates:s,sliceSize:o,strides:u.slice(u.length-r,u.length),outputSize:sizeFromShape(t)}}function segOpComputeOptimalWindowSize(a,e){var t=!1,o;for(a<=30?(o=a,t=!0):o=nearestDivisor(a,_Mathfloor(_Mathsqrt(a)));!t;){if(o>e||o===a){t=!0;break}o=nearestDivisor(a,o+1)}return o}function computeOutShape$1(s,e,t){for(var r=[],n=s.length,o=0;o=l[e]):!(n<=l[e]);n+=r[e])t+=1;return t}),[x,N,c]}function startForAxis(s,e,t,r,n){var o=e[n];s&1<o&&(o+=p),o=clamp(0,o,p-1)}function stopForAxis(s,e,t,r,n){var o=e[n];s&1<o&&(o+=p),o=0t||en}).sort(function(a,e){return e.score-a.score}),a=[],i=0;i=r){c=!0;break}if(!c&&(a.push(l),a.length>=t))break}return tensor1d(a,"int32")}function intersectionOverUnion(b,e,t){var r=b.subarray(4*e,4*e+4),n=b.subarray(4*t,4*t+4),o=_Mathmin(r[0],r[2]),a=_Mathmin(r[1],r[3]),i=_Mathmax(r[0],r[2]),s=_Mathmax(r[1],r[3]),u=_Mathmin(n[0],n[2]),l=_Mathmin(n[1],n[3]),c=_Mathmax(n[0],n[2]),p=_Mathmax(n[1],n[3]),d=(i-o)*(s-a),h=(c-u)*(p-l);if(0>=d||0>=h)return 0;var f=_Mathmax(o,u),m=_Mathmax(a,l),g=_Mathmin(i,c),N=_Mathmin(s,p),y=_Mathmax(g-f,0)*_Mathmax(N-m,0);return y/(d+h-y)}function split(s,e,i){var r=Array(s.rank).fill(0),n=s.shape.slice();return e.map(function(e){n[i]=e;var t=s.slice(r,n);return r[i]+=e,t})}function topkImpl(o,e,t,r){for(var n=e[e.length-1],a=[o.length/n,n],i=a[0],s=a[1],u=getTypedArrayFromDType(t,i*r),l=getTypedArrayFromDType("int32",i*r),c=0;co&&1<=l.length?"coords = 0;":l.map(function(t){return"coords["+(t+s)+"] = 0;"}).join("\n"))+"\n return get"+t+"("+(2>o&&0i||0=t)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error("GPU for rank "+t+" is not yet supported")}function squeezeInputInfo(a,e){var t=JSON.parse(JSON.stringify(a));return t.shapeInfo.logicalShape=e,t}function getSqueezedParams(a,e){return e.map(function(e){return a[e]}).join(", ")}function getCoords(a,e){if(1===a)return""+e;if(2===a)return e+".x, "+e+".y";if(3===a)return e+".x, "+e+".y, "+e+".z";if(4===a)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+a+" is not yet supported")}function getFinalCoord(a,e){if(1===a)return""+e;if(2===a)return e+".y";if(3===a)return e+".z";if(4===a)return e+".w";throw Error("Cumulative sum for rank "+a+" is not yet supported")}function getSourceCoords(s,e){var t=s.length;if(4= "+r);for(var n=0,i=0;i= "+r);for(var n=0,i=0;i=\n "+o);for(var a=1==r%2,i=1==t%2,s=_Mathfloor(r/2),u=_Mathfloor(t/2),l=_Mathceil(r/2),c=l*_Mathceil(t/2),p=nearestLargerEven(t)*nearestLargerEven(r),d=0;d= "+o);for(var a=1==r%2,i=_Mathfloor(r/2),u=_Mathfloor(t/2),l=_Mathceil(r/2),c=l*_Mathceil(t/2),p=nearestLargerEven(t)*nearestLargerEven(r),d=0;d=a||0>=e){var r="["+a+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(a>t||e>t)throw r="["+a+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+("["+t+"x"+t+"]."))}function createFramebuffer(t){return throwIfNull(t,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function bindVertexBufferToProgramAttribute(p,e,t,r,n,o,a){var i=p.getAttribLocation(e,t);return-1!==i&&(callAndCheck(p,function(){return p.bindBuffer(p.ARRAY_BUFFER,r)}),callAndCheck(p,function(){return p.vertexAttribPointer(i,n,p.FLOAT,!1,o,a)}),callAndCheck(p,function(){return p.enableVertexAttribArray(i)}),!0)}function bindTextureUnit(a,e,t){validateTextureUnit(a,t),callAndCheck(a,function(){return a.activeTexture(a.TEXTURE0+t)}),callAndCheck(a,function(){return a.bindTexture(a.TEXTURE_2D,e)})}function unbindTextureUnit(a,e){validateTextureUnit(a,e),callAndCheck(a,function(){return a.activeTexture(a.TEXTURE0+e)}),callAndCheck(a,function(){return a.bindTexture(a.TEXTURE_2D,null)})}function getProgramUniformLocationOrThrow(a,e,t){return throwIfNull(a,function(){return a.getUniformLocation(e,t)},"uniform \""+t+"\" not present in program.")}function getProgramUniformLocation(a,e,t){return a.getUniformLocation(e,t)}function bindTextureToProgramUniformSampler(a,e,t,r,n){callAndCheck(a,function(){return bindTextureUnit(a,t,n)}),callAndCheck(a,function(){return a.uniform1i(r,n)})}function bindCanvasToFramebuffer(t){callAndCheck(t,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),callAndCheck(t,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),callAndCheck(t,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})}function bindColorTextureToFramebuffer(a,e,t){callAndCheck(a,function(){return a.bindFramebuffer(a.FRAMEBUFFER,t)}),callAndCheck(a,function(){return a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,e,0)})}function unbindColorTextureFromFramebuffer(a,e){callAndCheck(a,function(){return a.bindFramebuffer(a.FRAMEBUFFER,e)}),callAndCheck(a,function(){return a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,null,0)})}function validateFramebuffer(a){var e=a.checkFramebufferStatus(a.FRAMEBUFFER);if(e!==a.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+getFramebufferErrorMessage(a,e))}function getFramebufferErrorMessage(a,e){return e===a.FRAMEBUFFER_INCOMPLETE_ATTACHMENT?"FRAMEBUFFER_INCOMPLETE_ATTACHMENT":e===a.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT?"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT":e===a.FRAMEBUFFER_INCOMPLETE_DIMENSIONS?"FRAMEBUFFER_INCOMPLETE_DIMENSIONS":e===a.FRAMEBUFFER_UNSUPPORTED?"FRAMEBUFFER_UNSUPPORTED":"unknown error "+e}function throwIfNull(a,e,t){var r=callAndCheck(a,function(){return e()});if(null==r)throw new Error(t);return r}function validateTextureUnit(a,e){var t=a.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+a.TEXTURE0;if(rt)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+t+"].")}function getTextureShapeFromLogicalShape(a,s){void 0===s&&(s=!1);var i=ENV.get("WEBGL_MAX_TEXTURE_SIZE");if(s&&(i*=2,a=a.map(function(e,t){return t>=a.length-2?nearestLargerEven(a[t]):a[t]})),2!==a.length){var p=squeezeShape(a);a=p.newShape}var n=sizeFromShape(a);return 1>=a.length&&n<=i?[n,1]:2===a.length&&a[0]<=i&&a[1]<=i?a:3===a.length&&a[0]*a[1]<=i&&a[2]<=i?[a[0]*a[1],a[2]]:3===a.length&&a[0]<=i&&a[1]*a[2]<=i?[a[0],a[1]*a[2]]:4===a.length&&a[0]*a[1]*a[2]<=i&&a[3]<=i?[a[0]*a[1]*a[2],a[3]]:4===a.length&&a[0]<=i&&a[1]*a[2]*a[3]<=i?[a[0],a[1]*a[2]*a[3]]:sizeToSquarishShape(n)}function isEven(t){return 0==t%2}function isReshapeFree(a,n){if(arraysEqual(a=a.slice(-2),n=n.slice(-2)))return!0;if(!a.length||!n.length)return!0;if(0===a[0]||0===a[1]||0===n[0]||0===n[1])return!0;if(a.length!==n.length){if(arraysEqual(squeezeShape(a).newShape,squeezeShape(n).newShape))return!0;}else if(isEven(a[0])&&isEven(n[0])){if(isEven(a[1])&&isEven(n[1]))return!0;if(a[1]===n[1])return!0}return!1}function createVertexShader$1(t){return createVertexShader(t,"\n precision highp float;\n attribute vec3 clipSpacePos;\n attribute vec2 uv;\n varying vec2 resultUV;\n\n void main() {\n gl_Position = vec4(clipSpacePos, 1);\n resultUV = uv;\n }")}function createVertexBuffer(t){return createStaticVertexBuffer(t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function createIndexBuffer(t){return createStaticIndexBuffer(t,new Uint16Array([0,1,2,2,1,3]))}function getTextureConfig(p,e){var t=p,l,d,c,m,h,g,f;return 2===ENV.get("WEBGL_VERSION")?(l=t.R32F,d=t.R16F,c=t.RGBA32F,m=t.RED,h=4,g=1,f=t.HALF_FLOAT):(l=p.RGBA,d=p.RGBA,c=t.RGBA,m=p.RGBA,h=4,g=4,f=null==e?null:e.HALF_FLOAT_OES),{internalFormatFloat:l,internalFormatHalfFloat:d,internalFormatPackedFloat:c,textureFormatFloat:m,downloadTextureFormat:p.RGBA,downloadUnpackNumChannels:h,defaultNumChannels:g,textureTypeHalfFloat:f}}function createAndConfigureTexture(p,e,t,r,n,o){validateTextureSize(e,t);var a=createTexture(p),i=p.TEXTURE_2D;return callAndCheck(p,function(){return p.bindTexture(i,a)}),callAndCheck(p,function(){return p.texParameteri(i,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE)}),callAndCheck(p,function(){return p.texParameteri(i,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE)}),callAndCheck(p,function(){return p.texParameteri(i,p.TEXTURE_MIN_FILTER,p.NEAREST)}),callAndCheck(p,function(){return p.texParameteri(i,p.TEXTURE_MAG_FILTER,p.NEAREST)}),callAndCheck(p,function(){return p.texImage2D(i,0,r,e,t,0,n,o,null)}),callAndCheck(p,function(){return p.bindTexture(p.TEXTURE_2D,null)}),a}function createFloat32MatrixTexture(a,e,t,r){var n=getUnpackedMatrixTextureShapeWidthHeight(e,t);return createAndConfigureTexture(a,n[0],n[1],r.internalFormatFloat,r.textureFormatFloat,a.FLOAT)}function createFloat16MatrixTexture(a,e,t,r){var n=getUnpackedMatrixTextureShapeWidthHeight(e,t);return createAndConfigureTexture(a,n[0],n[1],r.internalFormatFloat,r.textureFormatFloat,r.textureTypeHalfFloat)}function createUnsignedBytesMatrixTexture(a,e,t){var n=getUnpackedMatrixTextureShapeWidthHeight(e,t);return createAndConfigureTexture(a,n[0],n[1],a.RGBA,a.RGBA,a.UNSIGNED_BYTE)}function createPackedMatrixTexture(a,e,t,r){var n=getPackedMatrixTextureShapeWidthHeight(e,t);return createAndConfigureTexture(a,n[0],n[1],r.internalFormatPackedFloat,a.RGBA,a.FLOAT)}function createFloat16PackedMatrixTexture(a,e,t,r){var n=getPackedMatrixTextureShapeWidthHeight(e,t);return createAndConfigureTexture(a,n[0],n[1],r.internalFormatHalfFloat,a.RGBA,r.textureTypeHalfFloat)}function bindVertexProgramAttributeStreams(a,e,t){return callAndCheck(a,function(){return a.bindBuffer(a.ARRAY_BUFFER,t)}),bindVertexBufferToProgramAttribute(a,e,"clipSpacePos",t,3,20,0)&&bindVertexBufferToProgramAttribute(a,e,"uv",t,2,20,12)}function uploadPixelDataToTexture(a,e,t){callAndCheck(a,function(){return a.bindTexture(a.TEXTURE_2D,e)}),callAndCheck(a,function(){return a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,t)}),callAndCheck(a,function(){return a.bindTexture(a.TEXTURE_2D,null)})}function uploadDataToTexture(s,e,t,r,n,o){validateTextureSize(t,r),callAndCheck(s,function(){return s.bindTexture(s.TEXTURE_2D,e)}),callAndCheck(s,function(){return s.texSubImage2D(s.TEXTURE_2D,0,0,0,t,r,o,s.FLOAT,n)}),callAndCheck(s,function(){return s.bindTexture(s.TEXTURE_2D,null)})}function uploadMatrixToTexture(p,e,t,r,n,o,a){var i=getUnpackedMatrixTextureShapeWidthHeight(t,r),d=i[0],l=i[1],u;1===a.defaultNumChannels?u=n:encodeMatrixToUnpackedArray(n,u=new Float32Array(getUnpackedArraySizeFromMatrixSize(n.length,o)),o),uploadDataToTexture(p,e,d,l,u,a.textureFormatFloat)}function uploadMatrixToPackedTexture(i,e,t,r,n,o){var a=getPackedMatrixTextureShapeWidthHeight(r,n),s=a[0],p=a[1],l=new Float32Array(getPackedRGBAArraySizeFromMatrixShape(r,n));encodeMatrixToPackedRGBA(o,t,r,n,l),uploadDataToTexture(i,e,s,p,l,i.RGBA)}function maybeCreateBufferFromOutputTexture(p,e,t,r,n){var o=e;if(2===ENV.get("WEBGL_VERSION")){var l=p,i=l.createBuffer();callAndCheck(p,function(){return p.bindBuffer(l.PIXEL_PACK_BUFFER,i)});var s=4*getUnpackedArraySizeFromMatrixSize(t*r,n.downloadUnpackNumChannels);callAndCheck(p,function(){return p.bufferData(l.PIXEL_PACK_BUFFER,s,p.STATIC_DRAW)}),callAndCheck(p,function(){return l.readPixels(0,0,r,t,p.RGBA,p.FLOAT,0)}),callAndCheck(p,function(){return p.bindBuffer(l.PIXEL_PACK_BUFFER,null)}),o=i}return o}function downloadFloat32MatrixFromBuffer(p,e,t,r,n){var o=p,a=new Float32Array(getUnpackedArraySizeFromMatrixSize(t*r,n.downloadUnpackNumChannels));o.bindBuffer(p.ARRAY_BUFFER,e),o.getBufferSubData(p.ARRAY_BUFFER,0,a),o.bindBuffer(p.ARRAY_BUFFER,null);var i=new Float32Array(t*r);return decodeMatrixFromUnpackedArray(a,i,n.downloadUnpackNumChannels),i}function downloadFloat32MatrixFromOutputTexture(p,e,t,r){var n=getUnpackedMatrixTextureShapeWidthHeight(e,t),o=n[0],a=n[1],i=new Float32Array(getUnpackedArraySizeFromMatrixSize(e*t,r.downloadUnpackNumChannels));callAndCheck(p,function(){return p.readPixels(0,0,o,a,r.downloadTextureFormat,p.FLOAT,i)});var s=new Float32Array(e*t);return decodeMatrixFromUnpackedArray(i,s,r.downloadUnpackNumChannels),s}function downloadByteEncodedFloatMatrixFromOutputTexture(p,e,t,r){var n=getUnpackedMatrixTextureShapeWidthHeight(e,t),o=n[0],a=n[1],i=new Uint8Array(getUnpackedArraySizeFromMatrixSize(e*t,4));return callAndCheck(p,function(){return p.readPixels(0,0,o,a,r.downloadTextureFormat,p.UNSIGNED_BYTE,i)}),new Float32Array(i.buffer)}function downloadMatrixFromPackedOutputTexture(i,e,t,r,n,o){var a=getPackedMatrixTextureShapeWidthHeight(n,o),s=a[0],d=a[1],l=new Float32Array(getPackedRGBAArraySizeFromMatrixShape(n,o));callAndCheck(i,function(){return i.readPixels(0,0,s,d,i.RGBA,i.FLOAT,l)});var u=new Float32Array(sizeFromShape([e,t,r]));return decodeMatrixFromPackedRGBA(l,e,t,r,u)}function binSearchLastTrue(a){for(var e=0,s=a.length-1,i=-1,p;e<=s;)p=e+s>>1,a[p]()?(i=p,e=p+1):s=p-1;return i}function compileProgram(m,h,e,t){for(var n=h.userCode,r=e.map(function(t,e){var a={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked};return{name:h.variableNames[e],shapeInfo:a}}),a=r.map(function(t){return t.shapeInfo}),o={logicalShape:t.shape,texShape:t.texData.texShape,isUniform:!1,isPacked:t.texData.isPacked},s=makeShader(r,o,n,!0===h.supportsBroadcasting,h.usesPackedTextures),i=m.createProgram(s),l={},u=0,c;u=r;r++)for(var p=0;1>=p;p++){for(var l=(0==r?"r":"rp1")+", "+(0==p?"c":"cp1"),d=2;d "+e[0];for(var r="",s=a-2;s= "+e[s],s= "+e+";\n bool rEdge = rp1 >= "+t+";\n "}function getOutput(a,e){var t=a.length,r=getSourceCoordsArr(t,e);return 1===t?"getA(rc),\n rc + 1 >= "+a[0]+" ? 0. : getA(rc + 1),\n 0, 0":"getA("+r[0]+"),\n cEdge ? 0. : getA("+r[1]+"),\n rEdge ? 0. : getA("+r[2]+"),\n rEdge || cEdge ? 0. : getA("+r[3]+")"}function getFlatIndex(t){return"\n int getFlatIndex(ivec3 coords) {\n return round("+dotify(["coords.x","coords.y","coords.z"],computeStrides(t).map(function(t){return t.toString()}).concat(["1."]))+");\n }\n "}function getReshapedInputCoords(t){return"\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n "+getLogicalCoordinatesFromFlatIndex(["r","c","d"],t)+"\n return ivec3(r, c, d);\n }\n "}function getCoords$1(t){if(1===t)return"sourceLoc";if(2===t)return"sourceLoc.x, sourceLoc.y";if(3===t)return"sourceLoc.x, sourceLoc.y, sourceLoc.z";if(4===t)return"sourceLoc.x, sourceLoc.y, sourceLoc.z, sourceLoc.w";throw Error("Slicing for rank "+t+" is not yet supported")}function getPhysicalFromLogicalTextureType(a,e){if(e)return ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")?PhysicalTextureType.PACKED_2X2_FLOAT32:PhysicalTextureType.PACKED_2X2_FLOAT16;if(a===TextureUsage.DOWNLOAD||a===TextureUsage.PIXELS)return PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE;if(a===TextureUsage.UPLOAD)return PhysicalTextureType.UNPACKED_FLOAT32;if(a===TextureUsage.RENDER)return ENV.get("WEBGL_RENDER_FLOAT32_ENABLED")?PhysicalTextureType.UNPACKED_FLOAT32:PhysicalTextureType.UNPACKED_FLOAT16;throw new Error("Unknown logical texture type "+a)}function getKeyFromTextureShape(a,e,t){return a[0]+"_"+a[1]+"_"+e+"_"+t}function getSourceCoords$2(a){var e=a.length;if(5 0.0 ? 1.0 : float("+t+");\n "}function concat1d_(t){return concat(t,0)}function concat2d_(a,e){return concat(a,e)}function concat3d_(a,e){return concat(a,e)}function concat4d_(a,e){return concat(a,e)}function concat_(s,i){void 0===i&&(i=0),assert(1<=s.length,"Pass at least one tensor to concat");var p=convertToTensorArray(s,"tensors","concat");i=parseAxisParam(i,p[0].shape)[0];var e=computeOutShape(p.map(function(t){return t.shape}),i);if(0===sizeFromShape(e))return tensor([],e);if(1===(p=p.filter(function(t){return 0o)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+o+".");if(2s)throw new Error("Error in oneHot: depth must be >=2, but it is "+s);return ENV.engine.runKernel(function(a){return a.oneHot(p,s,t,i)},{$indices:p},function(){return{$indices:function(){return zerosLike(p)}}})}function fromPixels_(a,e){if(void 0===e&&(e=3),4D||255D||1=1+s.length,"input rank is "+r.rank+" but should be > than blockShape.length "+s.length),assert(t.length===s.length,"crops.length is "+t.length+" but should be equal to blockShape.length "+s.length),assert(0==r.shape[0]%e,"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+s.join(" * ")+" === "+e),ENV.engine.runKernel(function(a){return a.batchToSpaceND(r,s,t)},{$x:r},function(a){return{$x:function(){return a.spaceToBatchND(s,t)}}})}function spaceToBatchND_(a,s,t){var r=convertToTensor(a,"x","spaceToBatchND");return assert(r.rank>=1+s.length,"input rank "+r.rank+" should be > than [blockShape] "+s.length),assert(t.length===s.length,"paddings.shape[0] "+t.length+" must be equal to [blockShape] "+s.length),assert(r.shape.reduce(function(a,e,n){return 0e&&(assert(-(o.rank+1)<=e,"Axis must be in the interval ["+-(o.rank+1)+", "+o.rank+"]"),e=o.rank+e+1),r.splice(e,0,1),reshape(o,r)}function depthToSpace_(s,p,t){void 0===t&&(t="NHWC");var l=convertToTensor(s,"x","depthToSpace"),e="NHWC"===t?l.shape[1]:l.shape[2],n="NHWC"===t?l.shape[2]:l.shape[3],a="NHWC"===t?l.shape[3]:l.shape[1];return assert(0<=e*p,"Negative dimension size caused by overflow when multiplying\n "+e+" and "+p+" for depthToSpace with input shape\n "+l.shape),assert(0<=n*p,"Negative dimension size caused by overflow when multiplying\n "+n+" and "+p+" for depthToSpace with input shape\n "+l.shape),assert(0==a%(p*p),"Dimension size must be evenly divisible by "+p*p+" but is "+a+" for depthToSpace with input shape "+l.shape),ENV.engine.runKernel(function(a){return a.depthToSpace(l,p,t)},{$x:l})}function setdiff1dAsync_(m,e){return __awaiter(this,void 0,void 0,function(){var t,h,g,f,y,b,x,N,I,d;return __generator(this,function(a){switch(a.label){case 0:return t=convertToTensor(m,"x","setdiff1d"),h=convertToTensor(e,"y","setdiff1d"),assert(t.dtype===h.dtype,"x and y should have the same dtype, but got x ("+t.dtype+") and y ("+h.dtype+")."),assert(1===t.rank,"x should be 1D tensor, but got x ("+t.shape+")."),assert(1===h.rank,"y should be 1D tensor, but got y ("+h.shape+")."),[4,t.data()];case 1:return g=a.sent(),[4,h.data()];case 2:for(f=a.sent(),y=new Set(f),b=0,I=0;I=e?a:a+(a-1)*(e-1)}function getPadAndOutInfo(m,e,t,r,n,o,a,i){var s,y,b;if("number"==typeof m){s={top:m,bottom:m,left:m,right:m,type:0===m?"VALID":"NUMBER"};var x=computeOutputShape3D([e,t,1],o,1,r,m,i);y=x[0],b=x[1]}else if("same"===m){var p=((y=_Mathceil(e/r))-1)*r+o-e,d=((b=_Mathceil(t/n))-1)*n+a-t,h=_Mathfloor(p/2),f=_Mathfloor(d/2);s={top:h,bottom:p-h,left:f,right:d-f,type:"SAME"}}else{if("valid"!==m)throw Error("Unknown padding parameter: "+m);s={top:0,bottom:0,left:0,right:0,type:"VALID"},y=_Mathceil((e-o+1)/r),b=_Mathceil((t-a+1)/n)}return{padInfo:s,outHeight:y,outWidth:b}}function conditionalRound(a,e){if(!e)return a;switch(e){case"round":return _Mathround(a);case"ceil":return _Mathceil(a);case"floor":return _Mathfloor(a);default:throw new Error("Unknown roundingMode "+e);}}function tupleValuesAreOne(a){var e=parseTupleParam(a),t=e[0],r=e[1];return 1===t&&1===r}function eitherStridesOrDilationsAreOne(a,e){return tupleValuesAreOne(a)||tupleValuesAreOne(e)}function matMul_(y,e,t,b){void 0===t&&(t=!1),void 0===b&&(b=!1);var x=convertToTensor(y,"a","matMul"),o=convertToTensor(e,"b","matMul"),a=t?x.shape[x.rank-2]:x.shape[x.rank-1],i=b?o.shape[o.rank-1]:o.shape[o.rank-2],s=t?x.shape[x.rank-1]:x.shape[x.rank-2],u=b?o.shape[o.rank-2]:o.shape[o.rank-1],l=x.shape.slice(0,-2),c=o.shape.slice(0,-2),p=sizeFromShape(l),d=sizeFromShape(c);assert(2<=x.rank&&2<=o.rank&&x.rank===o.rank,"Error in matMul: inputs must have the same rank of at least 2, got ranks "+x.rank+" and "+o.rank+"."),assert(arraysEqual(l,c),"Error in matMul: outer dimensions ("+l+") and ("+c+") of Tensors with shapes "+x.shape+" and "+o.shape+" must match."),assert(a===i,"Error in matMul: inner shapes ("+a+") and ("+i+") of Tensors with shapes "+x.shape+" and "+o.shape+" and transposeA="+t+" and transposeB="+b+" must match.");var h=x.shape.slice(0,-2).concat([s,u]),f=t?x.as3D(p,a,s):x.as3D(p,s,a),m=b?o.as3D(d,u,i):o.as3D(d,i,u);return ENV.engine.runKernel(function(a){return a.batchMatMul(f,m,t,b)},{$a:f,$b:m},function(a){return t||b?!t&&b?{$a:function(){return a.matMul(m.toFloat(),!1,!1)},$b:function(){return a.matMul(f.toFloat(),!0,!1)}}:t&&!b?{$a:function(){return m.toFloat().matMul(a,!1,!0)},$b:function(){return f.toFloat().matMul(a,!1,!1)}}:{$a:function(){return m.toFloat().matMul(a,!0,!0)},$b:function(){return a.matMul(f.toFloat(),!0,!0)}}:{$a:function(){return a.matMul(m.toFloat(),!1,!0)},$b:function(){return f.toFloat().matMul(a,!0,!1)}}}).reshape(h)}function outerProduct_(a,e){var t=convertToTensor(a,"v1","outerProduct"),r=convertToTensor(e,"v2","outerProduct");return assert(1===t.rank&&1===r.rank,"Error in outerProduct: inputs must be rank 1, but got ranks "+t.rank+" and "+r.rank+"."),t.as2D(-1,1).matMul(r.as2D(1,-1))}function dot_(s,e){var t=convertToTensor(s,"t1","dot"),r=convertToTensor(e,"t2","dot");assert((1===t.rank||2===t.rank)&&(1===r.rank||2===r.rank),"Error in dot: inputs must all be rank 1 or 2, but got ranks "+t.rank+" and "+r.rank+".");var n=1===t.rank?t.size:t.shape[1],o=1===r.rank?r.size:r.shape[0];return assert(n===o,"Error in dot: inner dimensions of inputs must match, but got "+n+" and "+o+"."),1===t.rank&&1===r.rank?t.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===t.rank&&2===r.rank?t.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===t.rank&&1===r.rank?t.matMul(r.as2D(-1,1)).as1D():t.matMul(r.as2D(r.shape[0],r.shape[1]))}function conv1d_(m,e,t,r,n,g,f){void 0===n&&(n="NWC"),void 0===g&&(g=1);var i=convertToTensor(m,"x","conv1d"),s=convertToTensor(e,"filter","conv1d"),u=i,y=!1;2===i.rank&&(y=!0,u=i.as3D(1,i.shape[0],i.shape[1])),assert(3===u.rank,"Error in conv1d: input must be rank 3, but got rank "+u.rank+"."),assert(3===s.rank,"Error in conv1d: filter must be rank 3, but got rank "+s.rank+"."),null!=f&&assert(isInt(r),"Error in conv1d: pad must be an integer when using, dimRoundingMode "+f+" but got pad "+r+"."),assert(u.shape[2]===s.shape[1],"Error in conv1d: depth of input ("+u.shape[2]+") must match input depth for filter "+s.shape[1]+"."),assert(eitherStridesOrDilationsAreOne(t,g),"Error in conv1D: Either stride or dilation must be 1. Got stride "+t+" and dilation '"+g+"'"),assert("NWC"===n,"Error in conv1d: got dataFormat of "+n+" but only NWC is currently supported.");var b=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),p=u.as4D(u.shape[0],1,u.shape[1],u.shape[2]),d=conv2d(p,b,[1,t],r,"NHWC",[1,g],f);return y?d.as2D(d.shape[2],d.shape[3]):d.as3D(d.shape[0],d.shape[2],d.shape[3])}function conv2d_(m,e,t,r,n,g,y){void 0===n&&(n="NHWC"),void 0===g&&(g=[1,1]);var i=convertToTensor(m,"x","conv2d"),s=convertToTensor(e,"filter","conv2d"),u=i,b=!1;3===i.rank&&(b=!0,u=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),assert(4===u.rank,"Error in conv2d: input must be rank 4, but got rank "+u.rank+"."),assert(4===s.rank,"Error in conv2d: filter must be rank 4, but got rank "+s.rank+"."),null!=y&&assert(isInt(r),"Error in conv2d: pad must be an integer when using, dimRoundingMode "+y+" but got pad "+r+"."),assert(u.shape[3]===s.shape[2],"Error in conv2d: depth of input ("+u.shape[3]+") must match input depth for filter "+s.shape[2]+"."),assert(eitherStridesOrDilationsAreOne(t,g),"Error in conv2D: Either strides or dilations must be 1. Got strides "+t+" and dilations '"+g+"'"),assert("NHWC"===n,"Error in conv2d: got dataFormat of "+n+" but only NHWC is currently supported.");var x=computeConv2DInfo(u.shape,s.shape,t,g,r,y),d;if(1!==x.filterHeight||1!==x.filterWidth||1!==x.dilationHeight||1!==x.dilationWidth||1!==x.strideHeight||1!==x.strideWidth||"SAME"!==x.padInfo.type&&"VALID"!==x.padInfo.type)d=ENV.engine.runKernel(function(t){return t.conv2d(u,s,x)},{x:u,$filter:s},function(a){return assert(tupleValuesAreOne(g),"Error in gradient of conv2D: dilation rates greater than 1 are notyet supported in gradients. Got dilations '"+g+"'"),{x:function(){return conv2dDerInput_(u.shape,a,s,t,r)},$filter:function(){return conv2dDerFilter_(u,a,s.shape,t,r)}}});else{var N=u.reshape([-1,x.inChannels]),h=s.reshape([x.inChannels,x.outChannels]);d=matMul(N,h).reshape(x.outShape)}return b?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}function conv2dDerInput_(m,e,t,r,n,o){assert(m.length===e.rank,"Length of inShape ("+m.length+") and rank of dy ("+e.rank+") must match");var a=m,h=e,g=!1;3===e.rank&&(g=!0,h=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),a=[1,m[0],m[1],m[2]]);var f=a[3],l=h.shape[3];assert(4===a.length,"Error in conv2dDerInput: inShape must be length 4, but got length "+a.length+"."),assert(4===h.rank,"Error in conv2dDerInput: dy must be rank 4, but got rank "+h.rank),assert(4===t.rank,"Error in conv2dDerInput: filter must be rank 4, but got rank "+t.rank),assert(f===t.shape[2],"Error in conv2dDerInput: depth of input ("+f+") must match input depth for filter "+t.shape[2]+"."),assert(l===t.shape[3],"Error in conv2dDerInput: depth of output ("+l+") must match output depth for filter "+t.shape[3]+"."),null!=o&&assert(isInt(n),"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+".");var c=computeConv2DInfo(a,t.shape,r,1,n,o),p=ENV.engine.runKernel(function(a){return a.conv2dDerInput(h,t,c)},{dy4D:h,filter:t},function(a){return{dy4D:function(){return conv2d(a,t,r,n,"NHWC",1,o)},filter:function(){return conv2dDerFilter(a,h,t.shape,r,n,o)}}});return g?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function conv2dDerFilter_(p,e,t,r,n,o){var a=p;3===p.rank&&(a=p.as4D(1,p.shape[0],p.shape[1],p.shape[2]));var l=e;3===l.rank&&(l=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),assert(4===a.rank,"Error in conv2dDerFilter: input must be rank 4, but got shape "+a.shape+"."),assert(4===l.rank,"Error in conv2dDerFilter: dy must be rank 4, but got shape "+l.shape+"."),assert(4===t.length,"Error in conv2dDerFilter: filterShape must be length 4, but got "+t+"."),assert(a.shape[3]===t[2],"Error in conv2dDerFilter: depth of input "+a.shape[3]+") must match input depth in filter ("+t[2]+"."),assert(l.shape[3]===t[3],"Error in conv2dDerFilter: depth of dy ("+l.shape[3]+") must match output depth for filter ("+t[3]+")."),null!=o&&assert(isInt(n),"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+n+".");var d=computeConv2DInfo(a.shape,t,r,1,n,o);return ENV.engine.runKernel(function(t){return t.conv2dDerFilter(a,l,d)},{x4D:a,dy4D:l})}function conv2dTranspose_(s,e,t,r,n,o){return conv2dDerInput_(t,convertToTensor(s,"x","conv2dTranspose"),convertToTensor(e,"filter","conv2dTranspose"),r,n,o)}function depthwiseConv2d_(m,e,t,r,n,h,g){void 0===n&&(n="NHWC"),void 0===h&&(h=[1,1]);var i=convertToTensor(m,"x","depthwiseConv2d"),s=convertToTensor(e,"filter","depthwiseConv2d"),u=i,f=!1;3===i.rank&&(f=!0,u=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),assert(4===u.rank,"Error in depthwiseConv2d: input must be rank 4, but got rank "+u.rank+"."),assert(4===s.rank,"Error in depthwiseConv2d: filter must be rank 4, but got rank "+s.rank+"."),assert(u.shape[3]===s.shape[2],"Error in depthwiseConv2d: number of input channels ("+u.shape[3]+") must match the inChannels dimension in filter "+s.shape[2]+"."),null==h&&(h=[1,1]),assert(eitherStridesOrDilationsAreOne(t,h),"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+t+" and dilations '"+h+"'"),null!=g&&assert(isInt(r),"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+g+" but got pad "+r+".");var y=computeConv2DInfo(u.shape,s.shape,t,h,r,g,!0),p=ENV.engine.runKernel(function(t){return t.depthwiseConv2D(u,s,y)},{x:u,$filter:s},function(t){return assert(tupleValuesAreOne(h),"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+h+"'"),{x:function(){return depthwiseConv2dDerInput(u.shape,t,s,y)},$filter:function(){return depthwiseConv2dDerFilter(u,t,s.shape,y)}}});return f?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function separableConv2d_(g,e,t,r,n,o,y){void 0===o&&(o=[1,1]),void 0===y&&(y="NHWC");var b=convertToTensor(g,"x","separableConv2d"),s=convertToTensor(e,"depthwiseFilter","separableConv2d"),u=convertToTensor(t,"pointwiseFilter","separableConv2d"),l=b,x=!1;if(3===b.rank&&(x=!0,l=b.as4D(1,b.shape[0],b.shape[1],b.shape[2])),"NCHW"===y)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");assert(4===l.rank,"Error in separableConv2d: input must be rank 4, but got rank "+l.rank+"."),assert(4===s.rank,"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+s.rank+"."),assert(4===u.rank,"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+s.rank+"."),assert(1===u.shape[0],"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+u.shape[0]+"."),assert(1===u.shape[1],"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+u.shape[1]+".");var N=s.shape[2],d=s.shape[3];assert(u.shape[2]===N*d,"Error in separableConv2d: the third dimension of pointwise filter must be "+N*d+", but got "+u.shape[2]+".");var h=depthwiseConv2d(l,s,r,n,y,o),f=conv2d(h,u,1,"valid",y);return x?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}function depthwiseConv2dDerInput(s,e,t,r){var n=e,p=!1;3===e.rank&&(p=!0,n=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var l=ENV.engine.runKernel(function(a){return a.depthwiseConv2DDerInput(n,t,r)},{dy4D:n});return p?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}function depthwiseConv2dDerFilter(s,e,t,r){var n=s;3===s.rank&&(n=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]));var i=e;return 3===i.rank&&(i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),ENV.engine.runKernel(function(t){return t.depthwiseConv2DDerFilter(n,i,r)},{x4D:n,dy4D:i})}function reverse1d_(a){var e=convertToTensor(a,"x","reverse");return assert(1===e.rank,"Error in reverse1D: x must be rank 1 but got\n rank "+e.rank+"."),reverse(e,0)}function reverse2d_(a,e){var t=convertToTensor(a,"x","reverse");return assert(2===t.rank,"Error in reverse2D: x must be rank 2 but got\n rank "+t.rank+"."),reverse(t,e)}function reverse3d_(a,e){var t=convertToTensor(a,"x","reverse");return assert(3===t.rank,"Error in reverse3D: x must be rank 3 but got\n rank "+t.rank+"."),reverse(t,e)}function reverse4d_(a,e){var t=convertToTensor(a,"x","reverse");return assert(4===t.rank,"Error in reverse4D: x must be rank 4 but got\n rank "+t.rank+"."),reverse(t,e)}function reverse_(a,e){var t=convertToTensor(a,"x","reverse");if(0===t.rank)return t.clone();var r=parseAxisParam(e,t.shape);return ENV.engine.runKernel(function(a){return a.reverse(t,r)},{$x:t},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(t)}function maxPoolImpl_(p,d,t,r,m,e){var a=convertToTensor(p,"x","maxPool"),o=a,i=!1;3===a.rank&&(i=!0,o=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),null==r&&(r=[1,1]),assert(4===o.rank,"Error in maxPool: input must be rank 4 but got rank "+o.rank+"."),assert(eitherStridesOrDilationsAreOne(t,r),"Error in maxPool: Either strides or dilations must be 1. Got strides "+t+" and dilations '"+r+"'"),null!=e&&assert(isInt(m),"Error in maxPool: pad must be an integer when using, dimRoundingMode "+e+" but got pad "+m+".");var h=computePool2DInfo(o.shape,d,t,r,m,e),l=ENV.engine.runKernel(function(a,e){return e(a.maxPool(o,h))},{x:o},function(n,e){var a=e[0];return{x:function(){return maxPoolBackprop(n,o,a,d,t,r,m)}}});return i?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}function maxPool_(a,e,t,r,n){return maxPoolImpl_(a,e,t,1,r,n)}function avgPoolImpl_(p,d,t,r,m,e){var a=convertToTensor(p,"x","avgPool");assert("float32"===a.dtype,"The input dtype to avgPool must be float32"),null==r&&(r=[1,1]),assert(eitherStridesOrDilationsAreOne(t,r),"Error in avgPool: Either strides or dilations must be 1. Got strides "+t+" and dilations '"+r+"'");var o=a,i=!1;3===a.rank&&(i=!0,o=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),assert(4===o.rank,"Error in avgPool: x must be rank 4 but got rank "+o.rank+"."),null!=e&&assert(isInt(m),"Error in avgPool: pad must be an integer when using, dimRoundingMode "+e+" but got pad "+m+".");var h=computePool2DInfo(o.shape,d,t,r,m),l=ENV.engine.runKernel(function(t){return t.avgPool(o,h)},{x:o},function(a){return{x:function(){return avgPoolBackprop(a,o,d,t,r,m)}}});return l=l.cast(a.dtype),i?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}function avgPool_(a,e,t,r,n){return avgPoolImpl_(a,e,t,1,r,n)}function pool_(b,e,t,r,N,I){null==N&&(N=[1,1]),null==I&&(I=1),0===r&&(r="valid");var S=convertToTensor(b,"x","maxPool"),i=S,C=!1;3===S.rank&&(C=!0,i=S.as4D(1,S.shape[0],S.shape[1],S.shape[2])),assert(eitherStridesOrDilationsAreOne(I,N),"Error in pool: Either strides or dilations must be 1. Got strides "+I+" and dilations '"+N+"'");var k=computePool2DInfo(i.shape,e,I,N,r),c=[k.dilationHeight,k.dilationWidth],p;p="same"===r?withSpaceToBatchBasePaddings([k.filterHeight,k.filterWidth],c):[[0,0],[0,0]];var T=1===c[0]&&1===c[1],d=requiredSpaceToBatchPaddings([k.inHeight,k.inWidth],c,p),h=d[0],f=d[1],m=T?r:"valid",g=T?i:spaceToBatchND(i,c,h),v=("avg"===t?function(){return avgPoolImpl_(g,e,I,1,m)}:function(){return maxPoolImpl_(g,e,I,1,m)})(),y=T?v:batchToSpaceND(v,c,f);return C?y.as3D(y.shape[1],y.shape[2],y.shape[3]):y}function maxPoolBackprop(d,e,t,r,n,o,m,i){var s=convertToTensor(d,"dy","maxPoolBackprop"),u=convertToTensor(e,"input","maxPoolBackprop"),l=convertToTensor(t,"output","maxPoolBackprop");assert(u.rank===s.rank,"Rank of input ("+u.rank+") does not match rank of dy ("+s.rank+")"),null==o&&(o=[1,1]),assert(eitherStridesOrDilationsAreOne(n,o),"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"),assert(4===s.rank,"Error in maxPoolBackprop: dy must be rank 4 but got rank "+s.rank+"."),assert(4===u.rank,"Error in maxPoolBackprop: input must be rank 4 but got rank "+u.rank+"."),null!=i&&assert(isInt(m),"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+m+".");var c=computePool2DInfo(u.shape,r,n,o,m,i);return ENV.engine.runKernel(function(t){return t.maxPoolBackprop(s,u,l,c)},{$dy:s,$input:u})}function avgPoolBackprop(m,e,t,r,n,h){var a=convertToTensor(m,"dy","avgPoolBackprop"),i=convertToTensor(e,"input","avgPoolBackprop");assert(i.rank===a.rank,"Rank of input ("+i.rank+") does not match rank of dy ("+a.rank+")"),null==n&&(n=[1,1]),assert(eitherStridesOrDilationsAreOne(r,n),"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+n+"'");var s=i,g=a,f=!1;3===i.rank&&(f=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]),g=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),assert(4===g.rank,"Error in avgPoolBackprop: dy must be rank 4 but got rank "+g.rank+"."),assert(4===s.rank,"Error in avgPoolBackprop: input must be rank 4 but got rank "+s.rank+".");var y=computePool2DInfo(s.shape,t,r,n,h),p=ENV.engine.runKernel(function(t){return t.avgPoolBackprop(g,s,y)},{dy4D:g,input4D:s});return f?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p}function requiredSpaceToBatchPaddings(p,e,t){var r=t.map(function(t){return t[0]}),n=t.map(function(t){return t[1]}),o=p.concat(r,n),a=e.map(function(a,e){return(a-o[e]%a)%a}),i=n.map(function(n,e){return n+a[e]});return[e.map(function(a,e){return[r[e],i[e]]}),e.map(function(n,e){return[0,a[e]]})]}function withSpaceToBatchBasePaddings(a,s){var e=a.map(function(t,e){return t+(t-1)*(s[e]-1)}).map(function(t){return t-1}),r=e.map(function(t){return _Mathfloor(t/2)}),n=e.map(function(a,e){return a-r[e]});return e.map(function(a,e){return[r[e],n[e]]})}function slice1d_(a,e,t){var r=convertToTensor(a,"x","slice1d");return assert(1===r.rank,"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"),slice(r,[e],[t])}function slice2d_(a,e,t){var r=convertToTensor(a,"x","slice2d");return assert(2===r.rank,"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"),slice(r,e,t)}function slice3d_(a,e,t){var r=convertToTensor(a,"x","slice3d");return assert(3===r.rank,"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"),slice(r,e,t)}function slice4d_(a,e,t){var r=convertToTensor(a,"x","slice4d");return assert(4===r.rank,"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"),slice(r,e,t)}function slice_(s,e,t){var r=convertToTensor(s,"x","slice"),a,p;if(0===r.rank)throw new Error("Slicing scalar is not possible");a="number"==typeof e?[e].concat(Array(r.rank-1).fill(0)):e.length=o.rank)?o.clone():ENV.engine.runKernel(function(t){return t.transpose(o,n)},{$x:o},function(t){var e=getUndoAxesPermutation(n);return{$x:function(){return t.transpose(e)}}})}function localResponseNormalization_(p,l,d,c,m){void 0===l&&(l=5),void 0===d&&(d=1),void 0===c&&(c=1),void 0===m&&(m=.5);var e=convertToTensor(p,"x","localResponseNormalization");assert(4===e.rank||3===e.rank,"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+e.rank+"."),assert(isInt(l),"Error in localResponseNormalization: depthRadius must be an integer\n but got depthRadius "+l+".");var h=e,a=!1;3===e.rank&&(a=!0,h=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var g=ENV.engine.runKernel(function(t,e){return e(t.localResponseNormalization4D(h,l,d,c,m))},{x4D:h},function(t,e){var n=e[0];return{x4D:function(){return ENV.engine.runKernel(function(e){return e.LRNGrad(t,h,n,l,d,c,m)},{})}}});return a?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g}function norm_(s,p,l,d){void 0===p&&(p="euclidean"),void 0===l&&(l=null),void 0===d&&(d=!1);var u=normImpl(s=convertToTensor(s,"x","norm"),p,l),o=u.shape;if(d){var c=parseAxisParam(l,s.shape);o=expandShapeToKeepDim(u.shape,c)}return u.reshape(o)}function normImpl(a,e,t){if(void 0===t&&(t=null),0===a.rank)return a.abs();if(1!==a.rank&&null===t)return normImpl(a.reshape([-1]),e,t);if(1===a.rank||"number"==typeof t||t instanceof Array&&1===t.length){if(1===e)return a.abs().sum(t);if(e===1/0)return a.abs().max(t);if(e===-1/0)return a.abs().min(t);if("euclidean"===e||2===e)return a.abs().pow(scalar(2,"int32")).sum(t).sqrt();throw new Error("Error in norm: invalid ord value: "+e)}if(t instanceof Array&&2===t.length){if(1===e)return a.abs().sum(t[0]).max(t[1]-1);if(e===1/0)return a.abs().sum(t[1]).max(t[0]);if(e===-1/0)return a.abs().sum(t[1]).min(t[0]);if("fro"===e||"euclidean"===e)return a.square().sum(t).sqrt();throw new Error("Error in norm: invalid ord value: "+e)}throw new Error("Error in norm: invalid axis: "+t)}function unsortedSegmentSum_(a,e,t){var r=convertToTensor(a,"x","unsortedSegmentSum"),n=convertToTensor(e,"segmentIds","unsortedSegmentSum","int32");return assert("int32"===n.dtype,"segmentIds must be of dtype `int32`"),assert(isInt(t),"numSegments must be of dtype int"),ENV.engine.runKernel(function(a){return a.unsortedSegmentSum(r,n,t)},{$x:r},function(t){return{$x:function(){return gatherDropNegatives(t,n)}}})}function gather_(a,e,b){void 0===b&&(b=0);var x=convertToTensor(a,"x","gather"),n=convertToTensor(e,"indices","gather","int32");return assert("int32"===n.dtype,"Indices must be of dtype `int32`"),b=parseAxisParam(b,x.shape)[0],ENV.engine.runKernel(function(t){return t.gather(x,n,b)},{$x:x},function(r){return{$x:function(){if(0===b)return unsortedSegmentSum(r,n,x.shape[b]);var e=x.shape,t=n.size,a=e.slice(0,b),o=a.length,s=e.slice(b,e.length).slice(1),i=s.length,l=arrayRange(0,o),u=arrayRange(o+1,o+1+i),p=arrayConcat([a,[t],s]),d=r.reshape(p),c=n.reshape([t]),h=arrayConcat([[o],l,u]),m=d.transpose(h),g=unsortedSegmentSum(m,c,x.shape[b]),f=getUndoAxesPermutation(h);return g=g.transpose(f)}}})}function arrayRange(a,e){for(var t=[],r=a;re)throw new Error("'k' passed to topk() must be <= the last dimension ("+e+") but got "+i);var n=ENV.engine.runKernel(function(t){return t.topk(l,i,p)},{$x:l});return{values:n[0],indices:n[1]}}function scatterND_(a,e,t){var r=convertToTensor(a,"indices","scatterND","int32"),n=convertToTensor(e,"updates","scatterND");return validateInput(n,r,t),ENV.engine.runKernel(function(a){return a.scatterND(r,n,t)},{$indices:r,$updates:n})}function fft_(a){assert("complex64"===a.dtype,"The dtype for tf.spectral.fft() must be complex64 but got "+a.dtype+".");var e=a.shape[a.shape.length-1],t=a.size/e,r=a.as2D(t,e);return ENV.engine.runKernel(function(t){return t.fft(r)},{input:a}).reshape(a.shape)}function ifft_(a){assert("complex64"===a.dtype,"The dtype for tf.spectral.ifft() must be complex64 but got "+a.dtype+".");var e=a.shape[a.shape.length-1],t=a.size/e,r=a.as2D(t,e);return ENV.engine.runKernel(function(t){return t.ifft(r)},{input:a}).reshape(a.shape)}function rfft_(d){assert("float32"===d.dtype,"The dtype for rfft() must be real value but\n got "+d.dtype);var e=d.shape[d.shape.length-1],t=d.size/e,r=d.zerosLike(),n=complex(d,r).as2D(t,e),o=ENV.engine.runKernel(function(t){return t.fft(n)},{complexInput:n}),a=_Mathfloor(e/2)+1,i=real(o),s=imag(o),u=i.split([a,e-a],i.shape.length-1),l=s.split([a,e-a],s.shape.length-1),c=d.shape.slice();return c[d.shape.length-1]=a,complex(u[0],l[0]).reshape(c)}function validateInput$1(s,e,t,r){if("int32"!==s.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+s.dtype+".");if(2a.rank)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+a.rank);if(2===a.rank)return qr2d(a,s);var e=a.shape.slice(0,a.shape.length-2).reduce(function(a,e){return a*e}),p=[],n=[];return unstack(a.reshape([e,a.shape[a.shape.length-2],a.shape[a.shape.length-1]]),0).forEach(function(t){var e=qr2d(t,s),r=e[0],a=e[1];p.push(r),n.push(a)}),[stack(p,0).reshape(a.shape),stack(n,0).reshape(a.shape)]}function qr2d(p,e){return void 0===e&&(e=!1),ENV.engine.tidy(function(){if(2!==p.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+p.shape.length+"D Tensor.");for(var y=p.shape[0],r=p.shape[1],n=eye(y),b=p.clone(),x=tensor2d([[1]],[1,1]),i=x.clone(),t=y>=r?r:y,d=function(a){var e=b,o=i,s=n,p;p=ENV.engine.tidy(function(){var e=b.slice([a,a],[y-a,1]),t=e.norm(),o=b.slice([a,a],[1,1]),s=o.sign().neg(),l=o.sub(s.mul(t)),p=e.div(l);i=1===p.shape[0]?x.clone():x.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var d=s.matMul(l).div(t).neg(),u=b.slice([a,0],[y-a,r]),c=d.mul(i);b=0===a?u.sub(c.matMul(i.transpose().matMul(u))):b.slice([0,0],[a,r]).concat(u.sub(c.matMul(i.transpose().matMul(u))),0);var m=n.slice([0,a],[y,n.shape[1]-a]);return n=0===a?m.sub(m.matMul(i).matMul(c.transpose())):n.slice([0,0],[y,a]).concat(m.sub(m.matMul(i).matMul(c.transpose())),1),[i,b,n]}),i=p[0],b=p[1],n=p[2],dispose([e,o,s])},l=0;lr&&(n=n.slice([0,0],[y,r]),b=b.slice([0,0],[r,r])),[n,b]})}function resizeBilinear_(p,e,l){void 0===l&&(l=!1);var t=convertToTensor(p,"images","resizeBilinear");assert(3===t.rank||4===t.rank,"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+t.rank+"."),assert(2===e.length,"Error in resizeBilinear: new shape must 2D, but got shape "+e+".");var n=t,d=!1;3===t.rank&&(d=!0,n=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var c=e[0],i=e[1],s=ENV.engine.runKernel(function(t){return t.resizeBilinear(n,c,i,l)},{batchImages:n},function(a){return{batchImages:function(){return ENV.engine.runKernel(function(e){return e.resizeBilinearBackprop(a,n,l)},{})}}});return d?s.as3D(s.shape[1],s.shape[2],s.shape[3]):s}function resizeNearestNeighbor_(p,e,l){void 0===l&&(l=!1);var t=convertToTensor(p,"images","resizeNearestNeighbor");assert(3===t.rank||4===t.rank,"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+t.rank+"."),assert(2===e.length,"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."),assert("float32"===t.dtype||"int32"===t.dtype,"`images` must have `int32` or `float32` as dtype");var n=t,d=!1;3===t.rank&&(d=!0,n=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var c=e[0],i=e[1],s=ENV.engine.runKernel(function(t){return t.resizeNearestNeighbor(n,c,i,l)},{batchImages:n},function(a){return{batchImages:function(){return ENV.engine.runKernel(function(e){return e.resizeNearestNeighborBackprop(a,n,l)},{})}}});return d?s.as3D(s.shape[1],s.shape[2],s.shape[3]):s}function nonMaxSuppression_(p,e,t,l,d){void 0===l&&(l=.5),void 0===d&&(d=_NumberNEGATIVE_INFINITY);var u=convertToTensor(p,"boxes","nonMaxSuppression"),a=convertToTensor(e,"scores","nonMaxSuppression"),i=nonMaxSuppSanityCheck(u,a,t,l,d);return t=i.maxOutputSize,l=i.iouThreshold,d=i.scoreThreshold,ENV.engine.runKernel(function(n){return n.nonMaxSuppression(u,a,t,l,d)},{$boxes:u})}function nonMaxSuppressionAsync_(d,e,t,m,h){return void 0===m&&(m=.5),void 0===h&&(h=_NumberNEGATIVE_INFINITY),__awaiter(this,void 0,void 0,function(){var n,r,o,g,f,y;return __generator(this,function(a){switch(a.label){case 0:return n=convertToTensor(d,"boxes","nonMaxSuppressionAsync"),r=convertToTensor(e,"scores","nonMaxSuppressionAsync"),o=nonMaxSuppSanityCheck(n,r,t,m,h),t=o.maxOutputSize,m=o.iouThreshold,h=o.scoreThreshold,[4,n.data()];case 1:return g=a.sent(),[4,r.data()];case 2:return f=a.sent(),y=nonMaxSuppressionImpl(g,f,t,m,h),n!==d&&n.dispose(),r!==e&&r.dispose(),[2,y];}})})}function nonMaxSuppSanityCheck(s,e,t,i,p){null==i&&(i=.5),null==p&&(p=_NumberNEGATIVE_INFINITY);var l=s.shape[0];return t=_Mathmin(t,l),assert(0<=i&&1>=i,"iouThreshold must be in [0, 1], but was '"+i+"'"),assert(2===s.rank,"boxes must be a 2D tensor, but was of rank '"+s.rank+"'"),assert(4===s.shape[1],"boxes must have 4 columns, but 2nd dimension was "+s.shape[1]),assert(1===e.rank,"scores must be a 1D tensor"),assert(e.shape[0]===l,"scores has incompatible shape with boxes. Expected "+l+", but was "+e.shape[0]),{maxOutputSize:t,iouThreshold:i,scoreThreshold:p}}function cropAndResize_(p,e,t,r,n,d){var c=convertToTensor(p,"image","cropAndResize","float32"),i=convertToTensor(e,"boxes","cropAndResize","float32"),s=convertToTensor(t,"boxInd","cropAndResize","int32");n=n||"bilinear",d=d||0;var u=i.shape[0];return assert(4===c.rank,"Error in cropAndResize: image must be rank 4,but got rank "+c.rank+"."),assert(2===i.rank&&4===i.shape[1],"Error in cropAndResize: boxes must be have size ["+u+",4] but had shape "+i.shape+"."),assert(1===s.rank&&s.shape[0]===u,"Error in cropAndResize: boxInd must be have size ["+u+"] but had shape "+i.shape+"."),assert("int32"===s.dtype,"Error in cropAndResize: boxInd must be of dtype int32, but got dtype "+s.dtype+"."),assert(2===r.length,"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."),assert(1<=r[0]&&1<=r[1],"cropSize must be atleast [1,1], but was "+r),assert("bilinear"===n||"nearest"===n,"method must be bilinear or nearest, but was "+n),ENV.engine.runKernel(function(t){return t.cropAndResize(c,i,s,r,n,d)},{$image:c,$boxes:i})}function nextFrame(){return new Promise(function(t){return delayCallback(function(){return t()})})}function encodeWeights(a){return __awaiter(this,void 0,void 0,function(){var e,s,i,p;return __generator(this,function(t){switch(t.label){case 0:for(i in e=[],s=[],a){if("float32"!==(p=a[i]).dtype&&"int32"!==p.dtype&&"bool"!==p.dtype)throw new Error("Unsupported dtype in weight '"+i+"': "+p.dtype);e.push({name:i,shape:p.shape,dtype:p.dtype}),s.push(p.data())}return[4,Promise.all(s)];case 1:return[2,{data:concatenateTypedArrays(t.sent()),specs:e}];}})})}function decodeWeights(u,e){for(var m={},r=0,t=function(e){var t=e.name,n=e.dtype,a=e.shape,o=sizeFromShape(a),s;if(("quantization"in e)){var i=e.quantization;if("uint8"!==i.dtype&&"uint16"!==i.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+i.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var l=DTYPE_VALUE_SIZE_MAP[i.dtype],c=u.slice(r,r+o*l),g="uint8"===i.dtype?new Uint8Array(c):new Uint16Array(c);if("float32"===n)s=Float32Array.from(g,function(t){return t*i.scale+i.min});else{if("int32"!==n)throw new Error("Unsupported dtype in weight '"+t+"': "+n);s=Int32Array.from(g,function(t){return _Mathround(t*i.scale+i.min)})}r+=o*l}else{var d=DTYPE_VALUE_SIZE_MAP[n];if(c=u.slice(r,r+o*d),"float32"===n)s=new Float32Array(c);else if("int32"===n)s=new Int32Array(c);else{if("bool"!==n)throw new Error("Unsupported dtype in weight '"+t+"': "+n);s=new Uint8Array(c)}r+=o*d}var h;if("float32"===n)h=tensor(s,a,"float32");else if("int32"===n)h=tensor(s,a,"int32");else{if("bool"!==n)throw new Error("Unsupported dtype in weight '"+t+"': "+n);h=tensor(s,a,"bool")}m[t]=h},o=0,s=e;or.length,"Copying failed because more than one ("+r.length+") load handlers for source URL "+m+"."),h=r[0],assert(0<(g=IORouterRegistry.getSaveHandlers(e)).length,"Copying failed because no save handler is found for destination URL "+e+"."),assert(2>g.length,"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."),f=g[0],y=parseURL(m).scheme,b=parseURL(m).path,x=y===parseURL(m).scheme,[4,h.load()];case 1:return N=a.sent(),t&&x?[4,ModelStoreManagerRegistry.getManager(y).removeModel(b)]:[3,3];case 2:a.sent(),a.label=3;case 3:return[4,f.save(N)];case 4:return I=a.sent(),!t||x?[3,6]:[4,ModelStoreManagerRegistry.getManager(y).removeModel(b)];case 5:a.sent(),a.label=6;case 6:return[2,I.modelArtifactsInfo];}})})}function listModels(){return __awaiter(this,void 0,void 0,function(){var p,l,d,u,c,m,h;return __generator(this,function(e){switch(e.label){case 0:p=ModelStoreManagerRegistry.getSchemes(),l={},d=0,u=p,e.label=1;case 1:return de.length)throw new Error("Invalid key format: "+a);return e.slice(1,e.length-1).join("/")}function maybeStripScheme$1(t){return t.startsWith(BrowserLocalStorage.URL_SCHEME)?t.slice(BrowserLocalStorage.URL_SCHEME.length):t}function browserLocalStorage(t){return new BrowserLocalStorage(t)}function browserDownloads(t){return void 0===t&&(t="model"),new BrowserDownloads(t)}function browserFiles(t){return new BrowserFiles(t)}function loadWeightsAsArrayBuffer(a,n){return __awaiter(this,void 0,void 0,function(){var e,t;return __generator(this,function(n){switch(n.label){case 0:return e=a.map(function(t){return fetch(t,n)}),[4,Promise.all(e)];case 1:return t=n.sent(),[4,Promise.all(t.map(function(t){return t.arrayBuffer()}))];case 2:return[2,n.sent()];}})})}function loadWeights(m,a,g,e){return void 0===a&&(a=""),__awaiter(this,void 0,void 0,function(){var r,y,n,b,t,x,N,I,v,S;return __generator(this,function(o){switch(o.label){case 0:if(r=m.map(function(){return!1}),y={},n=null==g?[]:g.map(function(){return!1}),b=[],m.forEach(function(a,o){var t=0;a.weights.forEach(function(a){var e="quantization"in a?a.quantization.dtype:a.dtype,n=DTYPE_VALUE_SIZE_MAP[e]*sizeFromShape(a.shape),s=function(){r[o]=!0,null==y[o]&&(y[o]=[]),y[o].push({manifestEntry:a,groupOffset:t,sizeBytes:n})};null==g?s():g.forEach(function(e,t){e===a.name&&(s(),n[t]=!0)}),b.push(a.name),t+=n})}),!n.every(function(t){return t}))throw t=g.filter(function(a,e){return!n[e]}),new Error("Could not find weights in manifest with names: "+t.join(", ")+". \nManifest JSON has weights with names: "+b.join(", ")+".");return x=r.reduce(function(a,e,t){return e&&a.push(t),a},[]),N=[],x.forEach(function(e){m[e].paths.forEach(function(t){var e=a+(a.endsWith("/")?"":"/")+t;N.push(e)})}),[4,loadWeightsAsArrayBuffer(N,e)];case 1:return I=o.sent(),v={},S=0,x.forEach(function(e){for(var t=m[e].paths.length,a=0,r=0;re?a.substring(t):""]}function isHTTPScheme(t){return null!=t.match(BrowserHTTPRequest.URL_SCHEME_REGEX)}function browserHTTPRequest(a,e,t){return new BrowserHTTPRequest(a,e,t)}function fromMemory(a,e,t){return new PassthroughLoader(a,e,t)}function withSaveHandler(t){return new PassthroughSaver(t)}function confusionMatrix_(s,e,t){var r=convertToTensor(s,"label","confusionMatrix","int32"),n=convertToTensor(e,"label","confusionMatrix","int32");assert(null==t||0t)}function expectValuesInRange(a,e,t){var r=a instanceof Tensor?a.dataSync():a;for(var n=0;nt)throw new Error("Value out of range:"+r[n]+" low: "+e+", high: "+t)}function expectArrayBuffersEqual(a,e){expect(new Float32Array(a)).toEqual(new Float32Array(e))}function __extends$1(a,e){function t(){this.constructor=a}extendStatics$1(a,e),a.prototype=null===e?Object.create(e):(t.prototype=e.prototype,new t)}function __awaiter$1(p,e,t,d){return new(t||(t=Promise))(function(n,r){function a(t){try{s(d.next(t))}catch(t){r(t)}}function o(t){try{s(d.throw(t))}catch(t){r(t)}}function s(r){r.done?n(r.value):new t(function(e){e(r.value)}).then(a,o)}s((d=d.apply(p,e||[])).next())})}function __generator$1(p,e){function t(t){return function(a){return function(t){if(l)throw new TypeError("Generator is already executing.");for(;s;)try{if(l=1,d&&(u=2&t[0]?d.return:t[0]?d.throw||((u=d.return)&&u.call(d),0):d.next)&&!(u=u.call(d,t[1])).done)return u;switch(d=0,u&&(t=[2&t[0],u.value]),t[0]){case 0:case 1:u=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,d=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(u=0<(u=s.trys).length&&u[u.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!u||t[1]>u[0]&&t[1]=t.length?t:-1===t.indexOf("_")?t:t.replace(/[_]+(\w|$)/g,function(a,e){return e.toUpperCase()})}function serializeKerasObject(t){return null===t||void 0===t?null:{className:t.getClassName(),config:t.getConfig()}}function deserializeKerasObject(x,e,C,k){if(void 0===e&&(e={}),void 0===C&&(C={}),void 0===k&&(k="object"),"string"==typeof x){var T=x,i;if(T in C)i=C[T];else if(T in _GLOBAL_CUSTOM_OBJECTS)i=_GLOBAL_CUSTOM_OBJECTS[T];else if(null==(i=e[T]))throw new ValueError("Unknown "+k+": "+x+". This may be due to one of the following reasons:\n1. The "+k+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+k+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");return i}var E=x;if(null==E.className||null==E.config)throw new ValueError(k+": Improper config format: "+JSON.stringify(E)+".\n'className' and 'config' must set.");var o=E.className,s,R;if(o in C?(s=(z=C.get(o))[0],R=z[1]):o in _GLOBAL_CUSTOM_OBJECTS?(s=(B=_GLOBAL_CUSTOM_OBJECTS.className)[0],R=B[1]):o in e&&(s=(V=e[o])[0],R=V[1]),null==s)throw new ValueError("Unknown "+k+": "+o+". This may be due to one of the following reasons:\n1. The "+k+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+k+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");if(null!=R){for(var D={},c=0,P=Object.keys(_GLOBAL_CUSTOM_OBJECTS);ce?1:0}function reverseNumberCompare(a,e){return-1*numberCompare(a,e)}function stringToDType(t){switch(t){case"float32":return"float32";default:throw new ValueError("Invalid dtype: "+t);}}function unique(a){if(null==a)return a;for(var e=[],t=0,o=a,r;ta.indexOf(t))throw new ValueError(t+" is not a valid "+e+". Valid values are "+a+" or null/undefined.")}function checkArrayTypeAndLength(a,o,e,t){return void 0===e&&(e=0),void 0===t&&(t=1/0),assert$1(0<=e),assert$1(t>=e),Array.isArray(a)&&a.length>=e&&a.length<=t&&a.every(function(t){return typeof t===o})}function calcL2Norms(a,e){return tidy(function(){return sqrt(sum$1(mulStrict(a,a),e,!0))})}function serializeConstraint(t){return serializeKerasObject(t)}function deserializeConstraint(a,e){return void 0===e&&(e={}),deserializeKerasObject(a,serialization.SerializationMap.getMap().classNameMap,e,"constraint")}function getConstraint(t){return null==t?null:"string"==typeof t?deserializeConstraint({className:t in CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP?CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP[t]:t,config:{}}):t instanceof Constraint?t:deserializeConstraint(t)}function maxNorm(t){return new MaxNorm(t)}function unitNorm(t){return new UnitNorm(t)}function nonNeg(){return new NonNeg}function minMaxNorm(t){return new MinMaxNorm(t)}function checkDataFormat(t){checkStringTypeUnionValue(VALID_DATA_FORMAT_VALUES,"DataFormat",t)}function checkPaddingMode(t){checkStringTypeUnionValue(VALID_PADDING_MODE_VALUES,"PaddingMode",t)}function checkPoolMode(t){checkStringTypeUnionValue(VALID_POOL_MODE_VALUES,"PoolMode",t)}function nameScope(a,e){_nameScopeStack.push(a);try{var t=e();return _nameScopeStack.pop(),t}catch(t){throw _nameScopeStack.pop(),t}}function currentNameScopePrefix(){return 0===_nameScopeStack.length?"":_nameScopeStack.join("/")+"/"}function getScopedTensorName(t){if(!isValidTensorName(t))throw new Error("Not a valid tensor name: '"+t+"'");return currentNameScopePrefix()+t}function getUniqueTensorName(a){if(!isValidTensorName(a))throw new Error("Not a valid tensor name: '"+a+"'");nameMap.has(a)||nameMap.set(a,0);var e=nameMap.get(a);if(nameMap.set(a,nameMap.get(a)+1),0e&&(e=r.length+e+1),r.splice(e,0,1),a.reshape(r)}function repeat(a,e){return tidy(function(){if(2!==a.shape.length)throw new ValueError("repeat() expects a rank-2 tensor, but received a rank-"+a.shape.length+" tensor.");return tile$1(expandDims$1(a,1),[1,e,1])})}function flatten$1(a){var e=[arrayProd(a.shape)];return a.reshape(e)}function batchFlatten(a){if(1>=a.rank)throw new ValueError("batchFlatten requires a minimum rank of 2. Got rank: "+a.rank+".");var e=[a.shape[0],arrayProd(a.shape,1)];return a.reshape(e)}function sliceAlongFirstAxis(a,e,t){return tidy(function(){switch(a.rank){case 1:return slice1d(a,e,t);case 2:return slice2d(a,[e,0],[t,a.shape[1]]);case 3:return slice3d(a,[e,0,0],[t,a.shape[1],a.shape[2]]);case 4:return slice4d(a,[e,0,0,0],[t,a.shape[1],a.shape[2],a.shape[3]]);default:throw new ValueError("sliceAlongFirstAxis() received an unsupported tensor rank: "+a.rank);}})}function sliceAlongLastAxis(a,e,t){return tidy(function(){switch(a.rank){case 1:return slice1d(a,e,t);case 2:return slice2d(a,[0,e],[a.shape[0],t]);case 3:return slice3d(a,[0,0,e],[a.shape[0],a.shape[1],t]);case 4:return slice4d(a,[0,0,0,e],[a.shape[0],a.shape[1],a.shape[2],t]);default:throw new ValueError("sliceAlongLastAxis() received an unsupported tensor rank: "+a.rank);}})}function sliceAlongAxis(a,e,t,n){return tidy(function(){switch(a.rank){case 1:return slice1d(a,e,t);case 2:switch(n){case 1:return sliceAlongFirstAxis(a,e,t);case 2:return sliceAlongLastAxis(a,e,t);default:throw new ValueError("The axis is not within the rank of the tensor "+n);}case 3:switch(n){case 1:return sliceAlongFirstAxis(a,e,t);case 2:return slice3d(a,[0,e,0],[a.shape[0],t,a.shape[2]]);case 3:return sliceAlongLastAxis(a,e,t);default:throw new ValueError("The axis is not within the rank of the tensor "+n);}case 4:switch(n){case 1:return sliceAlongFirstAxis(a,e,t);case 2:return slice4d(a,[0,e,0,0],[a.shape[0],t,a.shape[2],a.shape[3]]);case 3:return slice4d(a,[0,0,e,0],[a.shape[0],a.shape[1],t,a.shape[3]]);case 4:return sliceAlongLastAxis(a,e,t);default:throw new ValueError("The axis is not within the rank of the tensor "+n);}default:throw new ValueError("sliceAlongLastAxis() received an unsupported tensor rank: "+a.rank);}})}function concatenate(a,e){var r;return void 0===e&&(e=-1),0>e&&(e=0===(r=a[0].rank)?0:r),e===a[0].rank&&(e=-1),concat(a,e)}function concatAlongFirstAxis(a,e){switch(a.rank){case 1:return concat1d([a,e]);case 2:return concat2d([a,e],0);case 3:return concat3d([a,e],0);case 4:return concat4d([a,e],0);default:throw new ValueError("concatAlongFirstAxis() received an unsupported tensor rank: "+a.rank);}}function tile$1(a,e){if(Array.isArray(e)||(e=[e]),a.rank!==e.length)throw new ValueError("The length of input n ("+e.length+") does not match the number of dimensions in input x ("+a.rank+")");return tile(a,e)}function randomNormal$1(a,e,o,s,r){return void 0===e&&(e=0),void 0===o&&(o=1),randomNormal(a,e,o,s,r)}function dot$1(p,d){if(2>p.rank||2>d.rank)throw new NotImplementedError("dot requires both inputs to be rank >= 2 but got x shape = "+p.shape+" and y shape = "+d.shape);if(3<=d.rank&&(n=p.shape.slice(-1)[0])!==(a=d.shape.slice(-2)[0]))throw new NotImplementedError("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+p.shape+" and y shape = "+d.shape);if(2===p.rank&&2===d.rank)return matMul(p,d);var c=p.shape.slice(),n=c.pop();p=p.reshape([-1,n]);var m=d.shape.slice(),i=m.pop(),a=m.pop(),h=m.concat([i]),s=Array.from({length:d.rank},function(t,e){return 0===e?d.rank-2:e<=d.rank-2?e-1:e});d=d.transpose(s).reshape([a,-1]);var l=c.concat(h);return matMul(p,d).reshape(l)}function gather$1(a,e,r){return tidy(function(){return e=Array.isArray(e)?tensor1d(e,"int32"):e.toInt(),gather(a,e,r)})}function square$1(t){return mulStrict(t,t)}function biasAdd(a,e,t){return tidy(function(){if(null==t&&(t=imageDataFormat()),checkDataFormat(t),1!==e.rank&&e.rank!==a.rank)throw new ValueError("Unexpected bias dimensions: "+e.rank+"; expected it to be 1 or "+a.rank);var n=e.shape,o;if(5===a.rank)"channelsFirst"===t?o=1===n.length?a.add(e.reshape([1,n[0],1,1,1])):a.add(e.reshape([1,n[3],n[0],n[1],n[2]])):"channelsLast"===t&&(o=1===n.length?a.add(e.reshape([1,1,1,1,n[0]])):a.add(e.reshape([1].concat(n))));else if(4===a.rank)"channelsFirst"===t?o=1===n.length?a.add(e.reshape([1,n[0],1,1])):a.add(e.reshape([1,n[2],n[0],n[1]])):"channelsLast"===t&&(o=1===n.length?a.add(e.reshape([1,1,1,n[0]])):a.add(e.reshape([1].concat(n))));else if(3===a.rank)"channelsFirst"===t?o=1===n.length?a.add(e.reshape([1,n[0],1])):a.add(e.reshape([1,n[1],n[0]])):"channelsLast"===t&&(o=1===n.length?a.add(e.reshape([1,1,n[0]])):a.add(e.reshape([1].concat(n))));else{if(!(3>a.rank))throw new ValueError("Unsupported input rank by biasAdd: "+a.rank);o=a.add(e)}return o})}function elu$1(a,e){if(void 0===e&&(e=1),1!==e)throw new NotImplementedError("Support for alpha values other than 1 ("+e+") is not implemented yet.");return elu(a)}function softsign(t){return tidy(function(){return div(t,add(getScalar(1),abs(t)))})}function dropout(a,e,t,n){return tidy(function(){if(null!=t&&!util.arraysEqual(a.shape,t))throw new NotImplementedError("Non-default noise shape is not implemented yet: "+JSON.stringify(t));if(null!=n)throw new NotImplementedError("seed is not implemented for dropout yet.");var r=step(add(neg(e),randomUniform(a.shape,0,1,"float32")));return r=mul(div(getScalar(1),sub(getScalar(1),e)),r),mul(a,r)})}function hardSigmoid(a){return tidy(function(){var e=add(getScalar(.5),mul(getScalar(.2),a));return clipByValue(e,0,1)})}function inTrainPhase(a,e,t){return void 0===t&&(t=!1),t?a():e()}function checkFanMode(t){checkStringTypeUnionValue(VALID_FAN_MODE_VALUES,"FanMode",t)}function checkDistribution(t){checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES,"Distribution",t)}function computeFans(o,e){var s,p;if(void 0===e&&(e="channelsLast"),checkDataFormat(e),2===o.length)s=o[0],p=o[1];else if(!(-1!==[3,4,5].indexOf(o.length))){var l=arrayProd(o);s=_Mathsqrt(l),p=_Mathsqrt(l)}else if("channelsFirst"===e){var a=arrayProd(o,2);s=o[1]*a,p=o[0]*a}else"channelsLast"===e&&(a=arrayProd(o,0,o.length-2),s=o[o.length-2]*a,p=o[o.length-1]*a);return[s,p]}function deserializeInitializer(a,e){return void 0===e&&(e={}),deserializeKerasObject(a,serialization.SerializationMap.getMap().classNameMap,e,"initializer")}function serializeInitializer(t){return serializeKerasObject(t)}function getInitializer(a){if("string"==typeof a){var e=a in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP?INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[a]:a;return"GlorotUniform"===e?new GlorotUniform:"GlorotNormal"===e?new GlorotNormal:"HeNormal"===e?new HeNormal:"LeCunNormal"===e?new LeCunNormal:deserializeInitializer({className:e,config:{}})}return a instanceof Initializer?a:deserializeInitializer(a)}function zeros$1(){return new Zeros}function ones$1$1(){return new Ones}function constant(t){return new Constant(t)}function randomUniform$1(t){return new RandomUniform(t)}function randomNormal$2(t){return new RandomNormal(t)}function truncatedNormal$1(t){return new TruncatedNormal(t)}function identity(t){return new Identity(t)}function varianceScaling(t){return new VarianceScaling(t)}function glorotUniform(t){return new GlorotUniform(t)}function glorotNormal(t){return new GlorotNormal(t)}function heNormal(t){return new HeNormal(t)}function leCunNormal(t){return new LeCunNormal(t)}function orthogonal(t){return new Orthogonal(t)}function isArrayOfShapes(t){return Array.isArray(t)&&Array.isArray(t[0])}function normalizeShapeList(t){return 0===t.length?[]:Array.isArray(t[0])?t:[t]}function getExactlyOneTensor(a){var e;if(Array.isArray(a)){if(1!==a.length)throw new ValueError("Expected Tensor length to be 1; got "+a.length);e=a[0]}else e=a;return e}function getExactlyOneShape(t){if(Array.isArray(t)&&Array.isArray(t[0])){if(1===t.length)return(t=t)[0];throw new ValueError("Expected exactly 1 Shape; got "+t.length)}return t}function countParamsInWeights(a){for(var e=0,o=0,s=a,r;o=e[e.length-1]&&(e=e.map(function(t){return _Mathfloor(m*t)})),!g)for(var f in a.push("Receives inputs"),o=[],d.nodesByDepth)o.push.apply(o,d.nodesByDepth[f]);h("_".repeat(m)),printRow(a,e,h),h("=".repeat(m));for(var s=d.layers,l=0;l=t.batchesPerEpoch:$.done)?T?(Q=void 0,isDatasetObject(t.validationData)?(J=toList,[4,x.evaluateDataset(t.validationData,{batches:t.validationBatches})]):[3,12]):[3,14]:[3,15];case 11:return Q=J.apply(void 0,[a.sent()]),[3,13];case 12:Q=toList(x.evaluate(R,D,{batchSize:null==t.validationBatchSize?32:t.validationBatchSize,verbose:0})),a.label=13;case 13:for(ee=0;ee=a&&(o=a),t.push([n,o]),n=o;return t}function fitLoop(x,e,t,n,r,C,k,T,s,l,u,E,p,R,d,f){return __awaiter$1(this,void 0,void 0,function(){var i,c,D,a,P,o,h,g;return __generator$1(this,function(m){switch(m.label){case 0:if(null==r&&(r=32),null==C&&(C=1),null==u&&(u=!0),null==p&&(p=0),i=!1,null!=s&&null!=l&&(i=!0),null!=d&&(i=!0,null==R))throw new ValueError("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(c=x.checkNumSamples(t,r,R,"steps_per_epoch"))&&(D=range$1(0,c)),null==k&&(k=1),a=configureCallbacks(T,f,k,C,p,c,R,r,i,E),P=a.callbackList,o=a.history,P.setModel(x),x.history=o,[4,P.onTrainBegin()];case 1:m.sent(),x.stopTraining_=!1,h=function(d){var a,m,N,y,b;return __generator$1(this,function(o){switch(o.label){case 0:return[4,P.onEpochBegin(d)];case 1:if(o.sent(),a={},null==R)return[3,2];throw new NotImplementedError("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===u)throw new NotImplementedError("batch shuffling is not implemneted yet");u&&util.shuffle(D),m=tensor1d(D),N=makeBatches(c,r),y=function(o){var p;return __generator$1(this,function(d){switch(d.label){case 0:return p={},[4,P.onBatchBegin(o,p)];case 1:return d.sent(),tidy(function(){var u=N[o][0],c=N[o][1],d=sliceAlongFirstAxis(m,u,c-u);p.batch=o,p.size=c-u;for(var h=sliceArraysByIndices(t,d),g=e(h),f=0;fn.validationSplit?(A=!0,O=_Mathfloor(r[0].shape[0]*(1-n.validationSplit)),L=r[0].shape[0],E=sliceArrays(r,O,L),r=sliceArrays(r,0,O),R=sliceArrays(C,O,L),C=sliceArrays(C,0,O),_=E.concat(R)):null!=n.validationSteps&&(A=!0);return M=r.concat(C),x.checkTrainableWeightsConsistency(),F=x.makeTrainFunction(),B=x.getDedupedMetricsNames(),V=void 0,U=void 0,A?(x.makeTestFunction(),V=x.testFunction,U=B.slice().concat(B.map(function(t){return"val_"+t}))):(V=null,_=[],U=B.slice()),W=standardizeCallbacks(n.callbacks),[4,fitLoop(x,F,M,B,D,n.epochs,n.verbose,W,V,_,n.shuffle,U,n.initialEpoch,null,null,n.yieldEvery)];case 2:return G=a.sent(),x.isTraining=!1,[2,G];case 3:return x.isTraining=!1,disposeNewTensors(r,e),disposeNewTensors(C,t),disposeNewTensors(E,k),disposeNewTensors(R,T),[7];case 4:return[2];}})})}function ensureTensorsRank2OrHigher(a){var o=[];a instanceof Tensor&&(a=[a]);for(var t=0,s;ta;)a+=n;return a}function batchDot(d,m,o){if(3= 2, but got "+d.shape.length),util.assert(2<=d.shape.length,"batchDot requires the rank of y to be >= 2, but got "+m.shape.length),"number"==typeof o&&(o=[o,o]),"complex64"===d.dtype||"complex64"===m.dtype)throw new NotImplementedError("batchDot is not implemented for complex64-type Tensors yet.");var g=d.shape.length,r=m.shape.length;null==o&&(o=[g-1,r-2]);var i=o;return tidy(function(){var e,t;if(g>r){e=g-r;for(var a=[],f=0;fg){for(e=r-g,a=[],f=0;fr?g+r-3:g-1;fN)throw new ValueError("Input should be at least 3D, but is "+N+"D.");var l=[1,0].concat(range$1(2,N)),p,I;if(e=transpose(e,l),null!=b)throw new NotImplementedError("The rnn() function of the deeplearn.js backend does not support masking yet.");if(null!=i)throw new NotImplementedError("The rnn() functoin of the deeplearn.js backend does not support constants yet.");a&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),n&&(e=reverse(e,0));for(var v=y,S=e.shape[0],d=function(t){var n=sliceAlongFirstAxis(e,t,1);n=n.reshape(n.shape.slice(1));var o=tidy(function(){return m(n,v)});if(I=o[0],x)if(0===t)p=I.expandDims(1);else{var s=concat([p,I.expandDims(1)],1);p.dispose(),p=s}v=o[1]},f=0;fu[0]&&t[1]e?1:0;if(r&&(e=-e),0===e)s(0<1/e?0:2147483648,i,a);else if(isNaN(e))s(2143289344,i,a);else if(34028234663852886e22>>0,i,a);else if(11754943508222875e-54>e)s((r<<31|_Mathround(e/1401298464324817e-60))>>>0,i,a);else{var n=_Mathfloor(_Mathlog(e)/l);s((r<<31|n+127<<23|8388607&_Mathround(8388608*(e*_Mathpow(2,-n))))>>>0,i,a)}}function t(i,e,t){var a=i(e,t),r=2*(a>>31)+1,n=255&a>>>23,o=8388607&a;return 255==n?o?NaN:r*(1/0):0==n?1401298464324817e-60*r*o:r*_Mathpow(2,n-150)*(o+8388608)}p.writeFloatLE=e.bind(null,writeUintLE),p.writeFloatBE=e.bind(null,writeUintBE),p.readFloatLE=t.bind(null,readUintLE),p.readFloatBE=t.bind(null,readUintBE)}():function(){function e(a,e,r){i[0]=a,e[r]=t[0],e[r+1]=t[1],e[r+2]=t[2],e[r+3]=t[3]}function n(a,e,r){i[0]=a,e[r]=t[3],e[r+1]=t[2],e[r+2]=t[1],e[r+3]=t[0]}function o(a,e){return t[0]=a[e],t[1]=a[e+1],t[2]=a[e+2],t[3]=a[e+3],i[0]}function s(a,e){return t[3]=a[e],t[2]=a[e+1],t[1]=a[e+2],t[0]=a[e+3],i[0]}var i=new Float32Array([-0]),t=new Uint8Array(i.buffer),a=128===t[3];p.writeFloatLE=a?e:n,p.writeFloatBE=a?n:e,p.readFloatLE=a?o:s,p.readFloatBE=a?s:o}(),"undefined"==typeof Float64Array?function(){function e(d,e,t,a,u,n){var o=0>a?1:0;if(o&&(a=-a),0===a)d(0,u,n+e),d(0<1/a?0:2147483648,u,n+t);else if(isNaN(a))d(0,u,n+e),d(2146959360,u,n+t);else if(17976931348623157e292>>0,u,n+t);else{var s;if(22250738585072014e-324>a)d((s=a/5e-324)>>>0,u,n+e),d((o<<31|s/4294967296)>>>0,u,n+t);else{var c=_Mathfloor(_Mathlog(a)/l);1024===c&&(c=1023),d(4503599627370496*(s=a*_Mathpow(2,-c))>>>0,u,n+e),d((o<<31|c+1023<<20|1048575&1048576*s)>>>0,u,n+t)}}}function t(l,e,t,a,r){var n=l(a,r+e),o=l(a,r+t),s=2*(o>>31)+1,i=2047&o>>>20,p=4294967296*(1048575&o)+n;return 2047==i?p?NaN:s*(1/0):0==i?5e-324*s*p:s*_Mathpow(2,i-1075)*(p+4503599627370496)}p.writeDoubleLE=e.bind(null,writeUintLE,0,4),p.writeDoubleBE=e.bind(null,writeUintBE,4,0),p.readDoubleLE=t.bind(null,readUintLE,0,4),p.readDoubleBE=t.bind(null,readUintBE,4,0)}():function(){function e(a,e,r){i[0]=a,e[r]=t[0],e[r+1]=t[1],e[r+2]=t[2],e[r+3]=t[3],e[r+4]=t[4],e[r+5]=t[5],e[r+6]=t[6],e[r+7]=t[7]}function n(a,e,r){i[0]=a,e[r]=t[7],e[r+1]=t[6],e[r+2]=t[5],e[r+3]=t[4],e[r+4]=t[3],e[r+5]=t[2],e[r+6]=t[1],e[r+7]=t[0]}function o(a,e){return t[0]=a[e],t[1]=a[e+1],t[2]=a[e+2],t[3]=a[e+3],t[4]=a[e+4],t[5]=a[e+5],t[6]=a[e+6],t[7]=a[e+7],i[0]}function s(a,e){return t[7]=a[e],t[6]=a[e+1],t[5]=a[e+2],t[4]=a[e+3],t[3]=a[e+4],t[2]=a[e+5],t[1]=a[e+6],t[0]=a[e+7],i[0]}var i=new Float64Array([-0]),t=new Uint8Array(i.buffer),a=128===t[7];p.writeDoubleLE=a?e:n,p.writeDoubleBE=a?n:e,p.readDoubleLE=a?o:s,p.readDoubleBE=a?s:o}(),p}function writeUintLE(n,e,t){e[t]=255&n,e[t+1]=255&n>>>8,e[t+2]=255&n>>>16,e[t+3]=n>>>24}function writeUintBE(n,e,t){e[t]=n>>>24,e[t+1]=255&n>>>16,e[t+2]=255&n>>>8,e[t+3]=255&n}function readUintLE(a,e){return(a[e]|a[e+1]<<8|a[e+2]<<16|a[e+3]<<24)>>>0}function readUintBE(a,e){return(a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3])>>>0}function inquire(moduleName){try{var mod$$1=eval("quire".replace(/^/,"re"))(moduleName);if(mod$$1&&(mod$$1.length||Object.keys(mod$$1).length))return mod$$1}catch(t){}return null}function pool$1(n,e,t){var p=t||8192,r=null,l=p;return function(t){if(1>t||t>p>>>1)return n(t);l+t>p&&(r=n(p),l=0);var a=e.call(r,l,l+=t);return 7&l&&(l=1+(7|l)),a}}function LongBits(a,e){this.lo=a>>>0,this.hi=e>>>0}function Op(n,e,t){this.fn=n,this.len=e,this.next=void 0,this.val=t}function noop(){}function State(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function Writer(){this.len=0,this.head=new Op(noop,0,0),this.tail=this.head,this.states=null}function writeByte(n,e,t){e[t]=255&n}function writeVarint32(n,r,t){for(;127>>=7;r[t]=n}function VarintOp(a,e){this.len=a,this.next=void 0,this.val=e}function writeVarint64(n,e,t){for(;n.hi;)e[t++]=128|127&n.lo,n.lo=(n.lo>>>7|n.hi<<25)>>>0,n.hi>>>=7;for(;127>>=7;e[t++]=n.lo}function writeFixed32(n,e,t){e[t]=255&n,e[t+1]=255&n>>>8,e[t+2]=255&n>>>16,e[t+3]=n>>>24}function BufferWriter$1(){writer.call(this)}function writeStringBuffer(n,e,t){40>n.length?minimal.utf8.write(n,e,t):e.utf8Write(n,t)}function indexOutOfRange(a,e){return RangeError("index out of range: "+a.pos+" + "+(e||1)+" > "+a.len)}function Reader(t){this.buf=t,this.pos=0,this.len=t.length}function readLongVarint(){var a=new LongBits$2(0,0),e=0;if(!(4e;++e){if(this.pos>=this.len)throw indexOutOfRange(this);if(a.lo=(a.lo|(127&this.buf[this.pos])<<7*e)>>>0,128>this.buf[this.pos++])return a}return a.lo=(a.lo|(127&this.buf[this.pos++])<<7*e)>>>0,a}for(;4>e;++e)if(a.lo=(a.lo|(127&this.buf[this.pos])<<7*e)>>>0,128>this.buf[this.pos++])return a;if(a.lo=(a.lo|(127&this.buf[this.pos])<<28)>>>0,a.hi=(a.hi|(127&this.buf[this.pos])>>4)>>>0,128>this.buf[this.pos++])return a;if(e=0,4e;++e)if(a.hi=(a.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,128>this.buf[this.pos++])return a;}else for(;5>e;++e){if(this.pos>=this.len)throw indexOutOfRange(this);if(a.hi=(a.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,128>this.buf[this.pos++])return a}throw Error("invalid varint encoding")}function readFixed32_end(a,e){return(a[e-4]|a[e-3]<<8|a[e-2]<<16|a[e-1]<<24)>>>0}function readFixed64(){if(this.pos+8>this.len)throw indexOutOfRange(this,8);return new LongBits$2(readFixed32_end(this.buf,this.pos+=4),readFixed32_end(this.buf,this.pos+=4))}function BufferReader$1(t){reader.call(this,t)}function Service(n,e,t){if("function"!=typeof n)throw TypeError("rpcImpl must be a function");minimal.EventEmitter.call(this),this.rpcImpl=n,this.requestDelimited=!!e,this.responseDelimited=!!t}function getParamValue(s,e,t,a){var r=e.params[s];if(r&&void 0!==r.inputIndex){if("tensor"===r.type)return getTensor(e.inputNames[r.inputIndex],t,a);if("tensors"===r.type)return(0===r.inputIndex?0===r.inputParamLength?e.inputNames:e.inputNames.slice(r.inputIndex,-r.inputParamLength):e.inputNames.splice(r.inputIndex)).map(function(n){return getTensor(n,t,a)});var n=Array.prototype.slice.call(getTensor(e.inputNames.slice(r.inputIndex)[0],t,a).dataSync());return"number"===r.type?n[0]:n}return r&&r.value}function getTensor(i,p,e){var t=parseNodeName(i),a=t[0],n=t[1],r=e.currentContextIds.find(function(t){return!!p[getNodeNameWithContextId(a,t)]});return void 0===r?void 0:p[getNodeNameWithContextId(a,r)][n]}function getTensorsForCurrentContenxt(n,e,t){return e[getNodeNameWithContextId(n,t.currentContextId)]}function getNodeNameAndIndex(o,e){var t=parseNodeName(o),a=t[0],r=t[1];return[getNodeNameWithContextId(a,e&&e.currentContextId),r]}function getNodeNameWithContextId(a,e){return e?a+"-"+e:a}function parseNodeName(a){var e=a.lastIndexOf(":");return-1===e?[a,0]:[a.substring(0,e),+a.substring(e+1)]}function split$1$1(n,e){for(var t=[],a=0;a{window.localStream=a,e.srcObject=a,e.onloadedmetadata=()=>{e.play(),t(!0)}}).catch(function(){t(!1)})})}async function stopVideo(){return!!window.localStream&&void window.localStream.getTracks().forEach(e=>(e.stop(),!0))}function getValidResolution(e,t,a){const n=t*e-1;return n-n%a+1}function getInputTensorDimensions(e){return e instanceof Tensor?[e.shape[0],e.shape[1]]:[e.height,e.width]}function calculateMaxScores(e,t,a){const n=[],r=[];for(let o=0;ot&&(t=e[o*a+n],s=n);n[o]=t,r[o]=s}// console.log([maxes, classes]) +return[n,r]}var extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,e){a.__proto__=e}||function(a,e){for(var t in e)e.hasOwnProperty(t)&&(a[t]=e[t])},__assign=Object.assign||function(a){for(var e=1,s=arguments.length,n;ethis.rank?this.rank.toString():"higher",trackerFn().registerTensor(this),null!=t&&trackerFn().write(this.dataId,t)}return a.make=function(e,t,r){return new a(e,r,t.values,t.dataId)},a.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},a.prototype.asScalar=function(){return this.throwIfDisposed(),assert(1===this.size,"The array must have only 1 element."),this.reshape([])},a.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},a.prototype.as2D=function(a,e){return this.throwIfDisposed(),this.reshape([a,e])},a.prototype.as3D=function(a,e,t){return this.throwIfDisposed(),this.reshape([a,e,t])},a.prototype.as4D=function(a,e,t,r){return this.throwIfDisposed(),this.reshape([a,e,t,r])},a.prototype.asType=function(t){return this.throwIfDisposed(),opHandler.cast(this,t)},Object.defineProperty(a.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),a.prototype.get=function(){for(var a=[],o=0;o=this.tensorInfo.get(t.dataId).refCount?(this.tensorInfo.get(t.dataId).backend.disposeData(t.dataId),this.numDataBuffers--,"complex64"!==t.dtype&&(this.numBytes-=sizeFromShape(t.shape)*bytesPerElement(t.dtype)),this.tensorInfo.delete(t.dataId)):this.tensorInfo.get(t.dataId).refCount--)},t.prototype.disposeVariables=function(){for(var a in this.registeredVariables){var e=this.registeredVariables[a];this.disposeTensor(e),delete this.registeredVariables[a]}},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.numTensors,t.numDataBuffers=this.numDataBuffers,t.numBytes=this.numBytes,t},t.prototype.profile=function(a){return __awaiter(this,void 0,void 0,function(){var e,n;return __generator(this,function(){return this.profiling=!0,e=this.numBytes,n=this.numTensors,this.activeProfile.kernels=[],this.activeProfile.result=a(),this.profiling=!1,this.activeProfile.peakBytes=_Mathmax.apply(Math,this.activeProfile.kernels.map(function(t){return t.totalBytesSnapshot})),this.activeProfile.newBytes=this.numBytes-e,this.activeProfile.newTensors=this.numTensors-n,[2,this.activeProfile]})})},t.prototype.shouldRecord=function(){return null!=this.activeTape&&0===this.customGradientDepth},t.prototype.addTapeNode=function(a,e,s){var r={};a.forEach(function(a,e){r[e]=a});var t={id:this.nextTapeNodeId++,name:this.activeScope.name,inputs:r,outputs:[e],gradient:function(a){var n={};return s(a).forEach(function(t,e){n[e]=function(){return t}}),n}};this.activeTape.push(t)},t.prototype.keep=function(t){if(1===this.scopeStack.length&&this.safeMode)throw new Error("Safe mode is ON. Enclose all tensor operations inside tf.tidy(): tf.tidy(() => {...}) to avoid memory leaks.");return this.keepTensors.add(t.id),t},t.prototype.startScope=function(a,e){void 0===e&&(e=!1),e&&0===this.gradientScopeCount&&(this.activeTape=[]),e&&this.gradientScopeCount++;var n={track:[],name:"unnamed scope"};a&&(n.name=a),this.scopeStack.push(n),this.activeScope=n},t.prototype.endScope=function(p,e){var l=this;void 0===e&&(e=!1),e&&(this.gradientScopeCount--,0===this.gradientScopeCount&&(this.activeTape=null));var r=new Set(this.keepTensors),n=getTensorsInContainer(p);n.forEach(function(t){return r.add(t.id)});for(var o=0,d;o {op();...}); to avoid memory leaks.");return this.activeScope.track.push(t),t},t.nextTensorId=0,t.nextVariableId=0,t}(),Type;!function(t){t[t.NUMBER=0]="NUMBER",t[t.BOOLEAN=1]="BOOLEAN",t[t.STRING=2]="STRING"}(Type||(Type={}));var URL_PROPERTIES=[{name:"DEBUG",type:Type.BOOLEAN},{name:"IS_BROWSER",type:Type.BOOLEAN},{name:"WEBGL_LAZILY_UNPACK",type:Type.BOOLEAN},{name:"WEBGL_CPU_FORWARD",type:Type.BOOLEAN},{name:"WEBGL_PACK_BATCHNORMALIZATION",type:Type.BOOLEAN},{name:"WEBGL_CONV_IM2COL",type:Type.BOOLEAN},{name:"WEBGL_MAX_TEXTURE_SIZE",type:Type.NUMBER},{name:"WEBGL_PAGING_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",type:Type.NUMBER},{name:"WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",type:Type.BOOLEAN},{name:"WEBGL_VERSION",type:Type.NUMBER},{name:"WEBGL_RENDER_FLOAT32_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_DOWNLOAD_FLOAT_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_FENCE_API_ENABLED",type:Type.BOOLEAN},{name:"WEBGL_SIZE_UPLOAD_UNIFORM",type:Type.NUMBER},{name:"BACKEND",type:Type.STRING},{name:"EPSILON",type:Type.NUMBER},{name:"PROD",type:Type.BOOLEAN},{name:"TENSORLIKE_CHECK_SHAPE_CONSISTENCY",type:Type.BOOLEAN}],TENSORFLOWJS_FLAGS_PREFIX="tfjsflags",EPSILON_FLOAT16=.001,TEST_EPSILON_FLOAT16=.1,EPSILON_FLOAT32=1e-7,TEST_EPSILON_FLOAT32=.001,Environment=function(){function t(t){this.features={},this.registry={},null!=t&&(this.features=t),this.get("DEBUG")&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}return t.setBackend=function(a,e){if(void 0===e&&(e=!1),!(a in ENV.registry))throw new Error("Backend name '"+a+"' not found in registry");ENV.engine.backend=ENV.findBackend(a),ENV.backendName=a},t.getBackend=function(){return ENV.initEngine(),ENV.backendName},t.disposeVariables=function(){ENV.engine.disposeVariables()},t.memory=function(){return ENV.engine.memory()},t.profile=function(t){return ENV.engine.profile(t)},t.tidy=function(a,e,t){return void 0===t&&(t=!1),ENV.engine.tidy(a,e,t)},t.dispose=function(t){getTensorsInContainer(t).forEach(function(t){return t.dispose()})},t.keep=function(t){return ENV.engine.keep(t)},t.time=function(t){return ENV.engine.time(t)},t.prototype.get=function(t){return t in this.features?this.features[t]:(this.features[t]=this.evaluateFeature(t),this.features[t])},t.prototype.getFeatures=function(){return this.features},t.prototype.set=function(a,e){this.features[a]=e},t.prototype.getBestBackendName=function(){var a=this;if(0===Object.keys(this.registry).length)throw new Error("No backend found in registry.");return Object.keys(this.registry).map(function(e){return{name:e,entry:a.registry[e]}}).sort(function(a,e){return e.entry.priority-a.entry.priority})[0].name},t.prototype.evaluateFeature=function(a){if("DEBUG"===a)return!1;if("IS_BROWSER"===a)return"undefined"!=typeof window;if("IS_NODE"===a)return"undefined"!=typeof process&&void 0!==process.versions.node;if("IS_CHROME"===a)return isChrome();if("WEBGL_CPU_FORWARD"===a)return!0;if("WEBGL_PACK_BATCHNORMALIZATION"===a)return!1;if("WEBGL_LAZILY_UNPACK"===a)return!1;if("WEBGL_CONV_IM2COL"===a)return!1;if("WEBGL_PAGING_ENABLED"===a)return this.get("IS_BROWSER")&&!this.get("PROD");if("WEBGL_MAX_TEXTURE_SIZE"===a)return getWebGLMaxTextureSize(this.get("WEBGL_VERSION"));if("IS_TEST"===a)return!1;if("BACKEND"===a)return this.getBestBackendName();if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"===a){var e=this.get("WEBGL_VERSION");return 0===e?0:getWebGLDisjointQueryTimerVersion(e)}if("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE"===a)return 0":"<",s=t?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+s+";\n float candidate = getA(batch, inIdx);\n if (candidate "+i+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "}}(),AvgPool2DBackpropProgram=function(){return function(p){this.variableNames=["dy"],this.outputShape=p.inShape;var e=p.filterHeight,t=p.filterWidth,r=p.strideHeight,n=p.strideWidth,o=p.dilationHeight,a=p.dilationWidth,i=p.effectiveFilterHeight,s=p.effectiveFilterWidth,d=i-1-p.padInfo.top,l=s-1-p.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+d+", "+l+");\n const float avgMultiplier = float("+1/(e*t)+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+i+";\n wR += "+o+") {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+p.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+s+";\n wC+= "+a+") {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+p.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "}}(),BatchNormProgram=function(){return function(p,e,t,r,n,o){this.outputShape=[],this.supportsBroadcasting=!0,this.variableNames=["x","mean","variance"],assertAndGetBroadcastShape(p,e),assertAndGetBroadcastShape(p,t);var a="0.0";null!=r&&(assertAndGetBroadcastShape(p,r),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var l="1.0";null!=n&&(assertAndGetBroadcastShape(p,n),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=p,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+a+";\n float scale = "+l+";\n float inv = scale * inversesqrt(variance + float("+o+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "}}(),BatchNormPackedProgram=function(){return function(p,e,t,r,n,o){this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],assertAndGetBroadcastShape(p,e),assertAndGetBroadcastShape(p,t);var a=broadcastSample("mean",e.length),i=broadcastSample("variance",t.length),s="vec4 offset = vec4(0.0)";null!=r&&(assertAndGetBroadcastShape(p,r),this.variableNames.push("offset"),s=broadcastSample("offset",r.length));var d="vec4 scale = vec4(1.0)";null!=n&&(assertAndGetBroadcastShape(p,n),this.variableNames.push("scale"),d=broadcastSample("scale",n.length)),this.outputShape=p,this.userCode="\n void main() {\n ivec4 rc = getOutputCoords();\n\n "+s+";\n "+d+";\n\n vec4 x = getX(rc.x, rc.y, rc.z, rc.w);\n "+a+";\n "+i+";\n\n vec4 inv = scale * inversesqrt(variance + vec4("+o+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "}}(),COMPLEX_MULTIPLY={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},BinaryOpComplexProgram=function(){return function(a,e,t){this.variableNames=["AReal","AImag","BReal","BImag"],this.supportsBroadcasting=!0,this.outputShape=assertAndGetBroadcastShape(e,t),this.userCode="\n float binaryOpComplex(\n float areal, float aimag, float breal, float bimag) {\n "+a+"\n }\n\n void main() {\n float areal = getARealAtOutCoords();\n float aimag = getAImagAtOutCoords();\n float breal = getBRealAtOutCoords();\n float bimag = getBImagAtOutCoords();\n setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n }\n "}}(),CHECK_NAN_SNIPPET="\n if (isNaN(a)) return a;\n if (isNaN(b)) return b;\n",ADD="return a + b;",SUB="return a - b;",MUL="return a * b;",DIV="if (a == b) return 1.0;\n return a / b;",INT_DIV="\n float resultSign = sign(a) * sign(b);\n int ia = round(a);\n int ib = round(b);\n int result = ia / ib;\n int amodb = ia - ib * result;\n\n if (resultSign < 0.0 && amodb != 0) {\n result -= 1;\n }\n return float(result);\n",POW="\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nreturn (round(mod(b, 2.0)) == 0 || round(mod(b, 2.0)) == 2) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",SQUARED_DIFFERENCE="return (a - b) * (a - b);",EQUAL="return float(a == b);",NOT_EQUAL="return float(a != b);",LESS="return float(a < b);",LESS_EQUAL="return float(a <= b);",GREATER="return float(a > b);",GREATER_EQUAL="return float(a >= b);",LOGICAL_AND="return float(a >= 1.0 && b >= 1.0);",LOGICAL_OR="return float(a >= 1.0 || b >= 1.0);",MAX=CHECK_NAN_SNIPPET+"\n return max(a, b);\n",MIN=CHECK_NAN_SNIPPET+"\n return min(a, b);\n",MOD="if (b == 0.0) return NAN;\n return mod(a, b);",ATAN2=CHECK_NAN_SNIPPET+"\n return atan(a, b);\n",ELU_DER="return (b >= 1.0) ? a : a * (b + 1.0);",BinaryOpProgram=function(){function t(a,e,t){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.outputShape=assertAndGetBroadcastShape(e,t),this.userCode="\n uniform float NAN;\n float binaryOperation(float a, float b) {\n "+a+"\n }\n\n void main() {\n float a = getAAtOutCoords();\n float b = getBAtOutCoords();\n setOutput(binaryOperation(a, b));\n }\n "}return t.prototype.getCustomSetupFunc=function(){var a=this;return function(e,t){null==a.startLoc&&(a.startLoc=e.getUniformLocationNoThrow(t,"NAN"),null==a.startLoc)||e.gl.uniform1f(a.startLoc,NaN)}},t}(),ClipProgram=function(){return function(a,e,t){this.variableNames=["A"],this.outputShape=a,this.userCode="\n void main() {\n float value = getAAtOutCoords();\n if (isNaN(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, float("+e+"), float("+t+")));\n }\n "}}(),ComplexAbsProgram=function(){return function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n void main() {\n float real = getRealAtOutCoords();\n float imag = getImagAtOutCoords();\n vec2 v = vec2(real, imag);\n\n setOutput(sqrt(dot(v, v)));\n }\n "}}(),ConcatProgram=function(){return function(a,e){this.variableNames=["A","B"],this.outputShape=[],this.outputShape=computeOutShape([a,e],1),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n float value = 0.0;\n if (yC < "+a[1]+") {\n value = getA(yR, yC);\n } else {\n yC -= "+a[1]+";\n value = getB(yR, yC);\n }\n\n setOutput(value);\n }\n "}}(),Conv2DDerFilterProgram=function(){return function(a){this.variableNames=["x","dy"],this.outputShape=a.filterShape;var e=a.strideHeight,t=a.strideWidth,r=a.padInfo.top,n=a.padInfo.left;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+a.batchSize+"; b++) {\n for (int yR = 0; yR < "+a.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+a.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+a.outWidth+"; yC++) {\n int xC = wC + yC * "+t+" - "+n+";\n\n if (xC < 0 || xC >= "+a.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "}}(),Conv2DDerInputProgram=function(){return function(s){this.variableNames=["dy","W"],this.outputShape=s.inShape;var e=s.filterHeight,t=s.filterWidth,r=s.strideHeight,n=s.strideWidth,o=e-1-s.padInfo.top,a=t-1-s.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+s.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+t+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+s.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+t+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+s.outChannels+"; d2++) {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "}}(),DepthwiseConv2DDerFilterProgram=function(){return function(s){this.variableNames=["x","dy"],this.outputShape=s.filterShape;var e=s.strideHeight,t=s.strideWidth,r=s.padInfo.top,n=s.padInfo.left,o=s.outChannels/s.inChannels;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int dm = coords.w;\n int d2 = d1 * "+o+" + dm;\n\n float dotProd = 0.0;\n\n // TODO: Vec4 over the batch size\n for (int b = 0; b < "+s.batchSize+"; b++) {\n for (int yR = 0; yR < "+s.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+s.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+s.outWidth+"; yC++) {\n int xC = wC + yC * "+t+" - "+n+";\n\n if (xC < 0 || xC >= "+s.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n setOutput(dotProd);\n }\n "}}(),DepthwiseConv2DDerInputProgram=function(){return function(p){this.variableNames=["dy","W"],this.outputShape=p.inShape;var e=p.filterHeight,t=p.filterWidth,r=p.strideHeight,n=p.strideWidth,o=e-1-p.padInfo.top,a=t-1-p.padInfo.left,i=p.outChannels/p.inChannels;this.userCode="\n const ivec2 pads = ivec2("+o+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+p.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+t+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+n+".0;\n\n if (dyC < 0.0 || dyC >= "+p.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+t+" - 1 - wC;\n\n // TODO: Vec4 over the channelMul\n for (int dm = 0; dm < "+i+"; dm++) {\n int d2 = d1 * "+i+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "}}(),Conv2DProgram=function(){return function(p){this.variableNames=["x","W"],this.outputShape=p.outShape;var e=p.padInfo.top,t=p.padInfo.left,r=p.strideHeight,n=p.strideWidth,o=p.dilationHeight,a=p.dilationWidth,i=p.filterHeight,s=p.filterWidth,d=4*_Mathfloor(p.inChannels/4),l=p.inChannels%4;this.userCode="\n const ivec2 strides = ivec2("+r+", "+n+");\n const ivec2 pads = ivec2("+e+", "+t+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+i+"; wR++) {\n int xR = xRCorner + wR * "+o+";\n\n if (xR < 0 || xR >= "+p.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+s+"; wC++) {\n int xC = xCCorner + wC * "+a+";\n\n if (xC < 0 || xC >= "+p.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+d+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1==l)+") {\n dotProd +=\n getX(batch, xR, xC, "+d+") *\n getW(wR, wC, "+d+", d2);\n } else if ("+(2==l)+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+d+"),\n getX(batch, xR, xC, "+d+" + 1)\n );\n vec2 wValues = vec2(\n getW(wR, wC, "+d+", d2),\n getW(wR, wC, "+d+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3==l)+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+d+"),\n getX(batch, xR, xC, "+d+" + 1),\n getX(batch, xR, xC, "+d+" + 2)\n );\n vec3 wValues = vec3(\n getW(wR, wC, "+d+", d2),\n getW(wR, wC, "+d+" + 1, d2),\n getW(wR, wC, "+d+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n setOutput(dotProd);\n }\n "}}(),DepthwiseConv2DProgram=function(){return function(d){this.variableNames=["x","W"],this.outputShape=d.outShape;var e=d.inHeight,t=d.inWidth,r=d.padInfo.top,n=d.padInfo.left,o=d.strideHeight,a=d.strideWidth,i=d.dilationHeight,s=d.dilationWidth,u=d.filterHeight,l=d.filterWidth,c=d.outChannels/d.inChannels;this.userCode="\n const ivec2 strides = ivec2("+o+", "+a+");\n const ivec2 pads = ivec2("+r+", "+n+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+c+";\n int q = d2 - d1 * "+c+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+u+"; wR++) {\n int xR = xRCorner + wR * "+i+";\n\n if (xR < 0 || xR >= "+e+") {\n continue;\n }\n\n for (int wC = 0; wC < "+l+"; wC++) {\n int xC = xCCorner + wC * "+s+";\n\n if (xC < 0 || xC >= "+t+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n setOutput(dotProd);\n }\n "}}(),CropAndResizeProgram=function(){return function(b,e,t,r,n){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var o=b[0],a=b[1],i=b[2],s=b[3],u=e[0],l=t[0],c=t[1];this.outputShape=[u,l,c,s];var p="bilinear"===r?1:0,d=[a-1+".0",i-1+".0"],h=d[0],f=d[1],m=1= "+o+") {\n return;\n }\n\n float height_scale = "+N+";\n float width_scale = "+v+";\n\n float in_y = "+y+";\n if( in_y < 0.0 || in_y > "+h+" ) {\n setOutput(float("+n+"));\n return;\n }\n float in_x = "+C+";\n if( in_x < 0.0 || in_x > "+f+" ) {\n setOutput(float("+n+"));\n return;\n }\n\n vec2 sourceFracIndexRC = vec2(in_y,in_x);\n if("+p+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(ceil(sourceFracIndexRC));\n\n float topLeft = getImage(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getImage(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getImage(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getImage(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(floor(\n sourceFracIndexRC + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestRC.x, sourceNearestRC.y, d);\n setOutput(newValue);\n }\n }\n "}}(),SAMPLE_1D_SNIPPET="\nvec2 UVfrom1D(int texNumR, int texNumC, int index) {\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_2D_SNIPPET="\nvec2 UVfrom2D(int texNumR, int texNumC, int numC, int row, int col) {\n int index = row * numC + col;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n int texNumC, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_3D_SNIPPET="\nvec2 UVfrom3D(int texNumR, int texNumC, int stride0,\n int stride1, int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_4D_SNIPPET="\nvec2 UVfrom4D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int row, int col, int depth,\n int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom4D(int texNumR, int texNumC, int texelsInBatch2,\n int texelsInBatch, int texelsInLogicalRow, int b2, int b,\n int row, int col) {\n int index = b2 * texelsInBatch2 + b * texelsInBatch +\n (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_5D_SNIPPET="\nvec2 UVfrom5D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int row, int col, int depth,\n int depth2, int depth3) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 +\n depth * stride2 + depth2 * stride3 + depth3;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",SAMPLE_6D_SNIPPET="\nvec2 UVfrom6D(int texNumR, int texNumC, int stride0,\n int stride1, int stride2, int stride3, int stride4,\n int row, int col, int depth, int depth2, int depth3, int depth4) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * stride0 + col * stride1 + depth * stride2 + depth2 *\n stride3 + depth3 * stride4 + depth4;\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",FLOAT_TEXTURE_SAMPLE_SNIPPET="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return texture2D(textureSampler, uv).r;\n }\n",FLOAT_TEXTURE_SET_R_SNIPPET="\n void setOutput(float val) {\n gl_FragColor = vec4(val, 0, 0, 0);\n }\n",FLOAT_TEXTURE_SET_RGBA_SNIPPET="\n void setOutput(vec4 val) {\n gl_FragColor = val;\n }\n",SHADER_PREFIX="\n precision highp float;\n precision highp int;\n varying vec2 resultUV;\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n bool hasNaN(vec4 values) {\n vec4 v1 = values * values;\n vec4 v2 = values * values;\n return any(notEqual(v1, v2));\n }\n\n float getNaN(vec4 values) {\n return dot(vec4(1), values);\n }\n\n int round(float value) {\n return int(floor(value + 0.5));\n }\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+SAMPLE_1D_SNIPPET+"\n "+SAMPLE_2D_SNIPPET+"\n "+SAMPLE_3D_SNIPPET+"\n "+SAMPLE_4D_SNIPPET+"\n "+SAMPLE_5D_SNIPPET+"\n "+SAMPLE_6D_SNIPPET+"\n",SHADER_PACKED_PREFIX="\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n float getChannel(vec4 frag, int dim) {\n float modCoord = mod(float(dim), 2.);\n return modCoord == 0. ? frag.r : frag.g;\n }\n",CumSumProgram=function(){return function(s,e,t){this.variableNames=["x"],this.outputShape=s;var r=s.length,n=s[s.length-1],o=t?"<":">";this.userCode="\n int getIndex(int i) {\n "+(t?"return "+n+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+getCoordsDataType(r)+" coords = getOutputCoords();\n int end = "+getFinalCoord(r,"coords")+";\n float val = 0.0;\n for (int i = "+n+" - 1; i >= 0; i -= 1) {\n int idx = getIndex(i);\n if (idx "+o+" end) {\n continue;\n }\n if (idx == end && "+e+") {\n continue;\n }\n "+getFinalCoord(r,"coords")+" = idx;\n val += getX("+getCoords(r,"coords")+");\n }\n setOutput(val);\n }\n "}}(),DepthToSpaceProgram=function(){function t(a,e,t){this.variableNames=["x"],this.outputShape=[],this.outputShape=a,this.blockSize=e,this.dataFormat=t,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int h = "+this.getHeightCoordString()+";\n int w = "+this.getWidthCoordString()+";\n int d = "+this.getDepthCoordString()+";\n\n int in_h = h / "+e+";\n int offset_h = imod(h, "+e+");\n int in_w = w / "+e+";\n int offset_w = imod(w, "+e+");\n int offset_d = (offset_h * "+e+" + offset_w) *\n "+this.getOutputDepthSize()+";\n int in_d = d + offset_d;\n\n float result = "+this.getInputSamplingString()+";\n setOutput(result);\n }\n "}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},t}(),EncodeFloatProgram=function(){return function(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n lowp vec4 encode_float(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float x = getAAtOutCoords();\n gl_FragColor = encode_float(x);\n }\n "}}(),COMPLEX_FFT={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"},FFTProgram=function(){return function(s,e,t){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var n=t?"2.0 * "+_MathPI:"-2.0 * "+_MathPI,o=t?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+n+";\n\n float unaryOpComplex(float real, float expR, float imag, float expI) {\n "+s+"\n }\n\n float mulMatDFT(int batch, int index) {\n float indexRatio = float(index) / float("+r+");\n float exponentMultiplierTimesIndexRatio =\n exponentMultiplier * indexRatio;\n\n float result = 0.0;\n\n for (int i = 0; i < "+r+"; i++) {\n // x = (-2|2 * PI / N) * index * i;\n float x = exponentMultiplierTimesIndexRatio * float(i);\n float expR = cos(x);\n float expI = sin(x);\n float real = getReal(batch, i);\n float imag = getImag(batch, i);\n\n result +=\n unaryOpComplex(real, expR, imag, expI) / "+o+";\n }\n\n return result;\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n setOutput(mulMatDFT(coords[0], coords[1]));\n }\n "}}(),FromPixelsProgram=function(){return function(a){this.variableNames=["A"];var e=a[0],t=a[1];this.outputShape=a,this.userCode="\n void main() {\n ivec3 coords = getOutputCoords();\n int texR = coords[0];\n int texC = coords[1];\n int depth = coords[2];\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+t+".0, "+e+".0);\n\n vec4 values = texture2D(A, uv);\n float value;\n if (depth == 0) {\n value = values.r;\n } else if (depth == 1) {\n value = values.g;\n } else if (depth == 2) {\n value = values.b;\n } else if (depth == 3) {\n value = values.a;\n }\n\n setOutput(floor(value * 255.0 + 0.5));\n }\n "}}(),GatherProgram=function(){return function(s,e,t){this.variableNames=["A","indices"];var r=s.slice();r[t]=e,this.outputShape=r,this.rank=r.length;var n=getCoordsDataType(this.rank),o=getSourceCoords(s,t);this.userCode="\n void main() {\n "+n+" resRC = getOutputCoords();\n setOutput(getA("+o+"));\n }\n "}}(),GatherNDProgram=function(){return function(s,e,t){this.sliceDim=s,this.strides=e,this.variableNames=["x","indices"],this.outputShape=t;var r=getCoordsDataType(e.length),n=getCoordsDataType(t.length),o=1= "+m[1]+" || pos >= "+m[0]+") continue;\n\n int offsetY = int(blockIndex / ("+s+")) * "+a+" - "+p+";\n int d0 = offsetY + "+l+" * (pos / "+d+");\n\n if(d0 >= "+e[0]+" || d0 < 0) continue;\n\n int offsetX = int(mod(float(blockIndex), "+s+".) * "+o+". - "+c+".);\n int d1 = offsetX + "+u+" * (int(mod(float(pos), "+d+".) / "+n+".));\n\n if(d1 >= "+e[1]+" || d1 < 0) continue;\n\n result[row * 2 + col] = getA(d0, d1, int(mod(float(pos), "+n+".)));\n }\n }\n\n gl_FragColor = result;\n }\n "}}(),LRNProgram=function(){return function(p,e,t,r,n){this.variableNames=["x"],this.outputShape=[];var o=e,i=p[3]-1,s;this.outputShape=p;var l="float("+t+") + float("+r+") * sum";s=.5===n?"inversesqrt("+l+")":1===n?"1.0/("+l+")":"exp(log("+l+") * float(-"+n+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+o+"; j <= "+o+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+i+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+s+";\n setOutput(val);\n }\n "}}(),LRNGradProgram=function(){return function(a,e,t,r,n){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=a,this.depth=a[3],this.depthRadius=e,this.bias=t,this.alpha=r,this.beta=n,this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n\n float result = 0.0;\n for (int d = 0; d < "+this.depth+"; ++d) {\n int depthBegin = int(max(0.0, float(d - "+e+")));\n int depthEnd = int(min(float("+this.depth+"),\n float(d + "+e+" + 1)));\n\n const int MIN_DEPTH_BEGIN = 0;\n const int MAX_DEPTH_END = "+this.depth+";\n\n float norm = 0.0;\n for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd) {\n norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n }\n else {\n break;\n }\n }\n\n norm = float("+r+") * norm + float("+t+");\n\n for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n if (k < depthBegin){\n continue;\n }\n else if (k >= depthBegin && k < depthEnd){\n float dyi = -2.0 * float("+r+")\n * float("+n+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+n+");\n }\n if (k == coords[3]) {\n dyi *= getDy(b, r, c, d);\n result += dyi;\n }\n }\n else {\n break;\n }\n }\n }\n setOutput(result);\n }\n "}}(),MaxPool2DBackpropProgram=function(){return function(p){this.variableNames=["dy","maxPos"],this.outputShape=p.inShape;var e=p.strideHeight,t=p.strideWidth,r=p.dilationHeight,n=p.effectiveFilterHeight,o=p.effectiveFilterWidth,a=n-1-p.padInfo.top,i=o-1-p.padInfo.left;this.userCode="\n const ivec2 pads = ivec2("+a+", "+i+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+n+";\n wR += "+r+") {\n float dyR = float(dyRCorner + wR) / "+e+".0;\n\n if (dyR < 0.0 || dyR >= "+p.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+o+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+t+".0;\n\n if (dyC < 0.0 || dyC >= "+p.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(b, idyR, idyC, d);\n int maxPosValue = "+(n*o-1)+" - int(getMaxPos(b, idyR, idyC, d));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue = wR * "+o+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n setOutput(dotProd);\n }\n "}}(),MatMulProgram=function(){return function(d,e,m,h){void 0===m&&(m=!1),void 0===h&&(h=!1),this.variableNames=["matrixA","matrixB"];var t=d[0],o=m?d[2]:d[1],a=h?e[1]:e[2],i=m?d[1]:d[2];this.outputShape=[t,o,a];var s=function(a,e){return m?"batch, "+e+" + "+a+", aRow":"batch, aRow, "+e+" + "+a},u=function(a,e){return h?"batch, bCol, "+e+" + "+a:"batch, "+e+" + "+a+", bCol"},l=4*_Mathfloor(i/4),c=i%4;this.userCode=" float dotARowBCol(int batch, int aRow, int bCol) {\n float result = 0.0;\n for (int i = 0; i < "+l+"; i += 4) {\n vec4 a = vec4(\n getMatrixA("+s(0,"i")+"),\n getMatrixA("+s(1,"i")+"),\n getMatrixA("+s(2,"i")+"),\n getMatrixA("+s(3,"i")+")\n );\n vec4 b = vec4(\n getMatrixB("+u(0,"i")+"),\n getMatrixB("+u(1,"i")+"),\n getMatrixB("+u(2,"i")+"),\n getMatrixB("+u(3,"i")+")\n );\n\n result += dot(a, b);\n }\n\n if ("+(1==c)+") {\n result += getMatrixA("+s(0,l)+") *\n getMatrixB("+u(0,l)+");\n } else if ("+(2==c)+") {\n vec2 a = vec2(\n getMatrixA("+s(0,l)+"),\n getMatrixA("+s(1,l)+")\n );\n vec2 b = vec2(\n getMatrixB("+u(0,l)+"),\n getMatrixB("+u(1,l)+")\n );\n result += dot(a, b);\n } else if ("+(3==c)+") {\n vec3 a = vec3(\n getMatrixA("+s(0,l)+"),\n getMatrixA("+s(1,l)+"),\n getMatrixA("+s(2,l)+")\n );\n vec3 b = vec3(\n getMatrixB("+u(0,l)+"),\n getMatrixB("+u(1,l)+"),\n getMatrixB("+u(2,l)+")\n );\n result += dot(a, b);\n }\n\n return result;\n }\n\n void main() {\n ivec3 resBRC = getOutputCoords();\n setOutput(dotARowBCol(resBRC.x, resBRC.y, resBRC.z));\n }\n "}}(),MatMulPackedProgram=function(){return function(p,e,t,r,d){void 0===r&&(r=!1),void 0===d&&(d=!1),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=t;var m=r?p[0]:p[1],a=_Mathceil(m/2),i=r?"i * 2, rc.x":"rc.x, i * 2",s=d?"rc.y, i * 2":"i * 2, rc.y",u=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],l=d?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];this.userCode="\n const float sharedDimension = "+a+".0;\n\n vec4 dot2x2ARowBCol(ivec2 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+a+"; i++) {\n vec4 a = getMatrixA("+i+");\n vec4 b = getMatrixB("+s+");\n\n result += ("+u[0]+" * "+l[0]+") + ("+u[1]+" * "+l[1]+");\n }\n return result;\n }\n\n void main() {\n ivec2 rc = getOutputCoords();\n setOutput(dot2x2ARowBCol(rc));\n }\n "}}(),MultinomialProgram=function(){function t(a,e,t){this.variableNames=["probs"],this.outputShape=[a,t],this.userCode="\n uniform float seed;\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n\n float r = random(seed);\n float cdf = 0.0;\n\n for (int i = 0; i < "+(e-1)+"; i++) {\n cdf += getProbs(batch, i);\n\n if (r < cdf) {\n setOutput(float(i));\n return;\n }\n }\n\n // If no other event happened, last event happened.\n setOutput(float("+(e-1)+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(a){var e=this;return function(t,r){null==e.seedLoc&&(e.seedLoc=t.getUniformLocation(r,"seed")),t.gl.uniform1f(e.seedLoc,a)}},t}(),OneHotProgram=function(){return function(a,e,t,r){this.variableNames=["indices"],this.outputShape=[a,e],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int index = round(getIndices(coords.x));\n setOutput(mix(float("+r+"), float("+t+"),\n float(index == coords.y)));\n }\n "}}(),PackProgram=function(){return function(s){this.variableNames=["A"],this.outputShape=s;var e=s.length,t=getChannels("rc",e),r=getCoordsDataType(e),n=getOutOfBoundsCondition(e,s,t),o=getSetup(e,s[s.length-1],s[s.length-2],t),a=getOutput(s,t);this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n\n if("+n+") {\n gl_FragColor = vec4(0);\n } else {\n "+o+"\n\n setOutput(vec4("+a+"));\n }\n }\n "}}(),PadProgram=function(){return function(p,e,t){this.variableNames=["x"],this.outputShape=e.map(function(e,t){return e[0]+p[t]+e[1]});var r=p.length,n=getCoordsDataType(r),o=e.map(function(t){return t[0]}).join(","),a=e.map(function(e,t){return e[0]+p[t]}).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1===r?"\n int start = "+o+";\n int end = "+a+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+t+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n ":"\n "+n+" start = "+n+"("+o+");\n "+n+" end = "+n+"("+a+");\n\n void main() {\n "+n+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+t+"));\n } else {\n "+n+" coords = outC - start;\n setOutput(getX("+i+"));\n }\n }\n "}}(),Pool2DProgram=function(){return function(y,e,t){if(this.variableNames=["x"],"avg"===e&&t)throw new Error("Cannot compute positions for average pool.");var r=y.filterWidth,n=y.strideHeight,o=y.strideWidth,a=y.dilationHeight,i=y.dilationWidth,s=y.effectiveFilterHeight,u=y.effectiveFilterWidth,l=y.padInfo.top,c=y.padInfo.left;this.outputShape=y.outShape;var p="avg"===e,d="0.0";if(p||(d="-1.0 / 0.0"),t)this.userCode="\n const ivec2 strides = ivec2("+n+", "+o+");\n const ivec2 pads = ivec2("+l+", "+c+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < "+s+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+y.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+u+";\n wC += "+i+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+y.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xR, xC, d);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition = wR * "+u+" + wC;\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var b=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(b="avgValue / count");var x=4*_Mathfloor(r/4),m=r%4,g="\n if ("+p+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+n+", "+o+");\n const ivec2 pads = ivec2("+l+", "+c+");\n const float initializationValue = "+d+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xR, int xC, int d) {\n if (xC < 0 || xC >= "+y.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xR, xC, d);\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n vec4 minMaxValue = vec4("+d+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wR = 0; wR < "+s+";\n wR += "+a+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+y.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+x+"; wC += 4) {\n int xC = xCCorner + wC * "+i+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+i+", d),\n getValue(batch, xR, xC + 2 * "+i+", d),\n getValue(batch, xR, xC + 3 * "+i+", d)\n );\n\n "+g+"\n }\n\n int xC = xCCorner + "+x+";\n if ("+(1==m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(2==m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+i+", d),\n initializationValue,\n initializationValue\n );\n\n "+g+"\n } else if ("+(3==m)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+i+", d),\n getValue(batch, xR, xC + 2 * "+i+", d),\n initializationValue\n );\n\n "+g+"\n }\n }\n setOutput("+b+");\n }\n "}}}(),ReduceProgram=function(){return function(m,e){this.variableNames=["x"];var t=m.windowSize,r=m.batchSize,n=m.inSize,o=_Mathceil(n/t);this.outputShape=[r,o];var a="0.0",g="";"prod"===e?a="1.0":"min"===e?(a="1.0 / 0.0",g="min"):"max"==e&&(a="-1.0 / 0.0",g="max");var f=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?f="sumValue":"prod"===e?f="prodValue":"all"===e?f="allValue":"any"==e&&(f="anyValue");var y=4*_Mathfloor(t/4),l=t%4,c="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+g+"(values, minMaxValue);\n }\n ",b="vec4";"all"===e?(a="1.0",c="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",b="bvec4"):"any"==e&&(a="0.0",c="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",b="bvec4");var x="";0= "+n+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+a+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+x+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+t+";\n\n vec4 minMaxValue = vec4("+a+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+y+"; i += 4) {\n int inIdx = inOffset + i;\n "+b+" values = "+b+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+c+"\n }\n\n int inIdx = inOffset + "+y+";\n if ("+(1==l)+") {\n "+b+" values = "+b+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+c+"\n } else if ("+(2==l)+") {\n "+b+" values = "+b+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+c+"\n } else if ("+(3==l)+") {\n "+b+" values = "+b+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+c+"\n }\n setOutput("+f+");\n }\n "}}(),ReshapePackedProgram=function(){return function(a,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=a;for(var t="",s=0,i;4>s;s++)i="thisRC = rc;",1==s%2&&(i+="thisRC.z += 1;"),1= "+i+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+s+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(n-1)+".0));\n float dxRLerp = dxR - float(topDxRIndex);\n float inverseDxRLerp = 1.0 - dxRLerp;\n\n float dxC = float(dyC) * widthScale;\n int leftDxCIndex = int(floor(dxC));\n int rightDxCIndex = int(min(ceil(dxC), "+(o-1)+".0));\n float dxCLerp = dxC - float(leftDxCIndex);\n float inverseDxCLerp = 1.0 - dxCLerp;\n\n if (r == topDxRIndex && c == leftDxCIndex) {\n // topLeft\n accumulator +=\n getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n }\n\n if (r == topDxRIndex && c == rightDxCIndex) {\n // topRight\n accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n }\n\n if (r == bottomDxRIndex && c == leftDxCIndex) {\n // bottomLeft\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n }\n\n if (r == bottomDxRIndex && c == rightDxCIndex) {\n // bottomRight\n accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "}}(),ResizeBilinearProgram=function(){return function(p,e,t,r){this.variableNames=["A"],this.outputShape=[];var n=p[0],o=p[1],a=p[2],i=p[3];this.outputShape=[n,e,t,i];var s=[r&&1= "+i+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+s+") {\n continue;\n }\n\n float sourceFracRow =\n float("+u[0]+") *\n (float(dyR) / float("+l[0]+"));\n\n float sourceFracCol =\n float("+u[1]+") *\n (float(dyC) / float("+l[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+n+") - 1),\n "+t+" ? float(round(sourceFracRow)) :\n float(floor(sourceFracRow))));\n\n int sourceNearestCol = int(min(\n float(int("+o+") - 1),\n "+t+" ? float(round(sourceFracCol)) :\n float(floor(sourceFracCol))));\n\n if (r == sourceNearestRow && c == sourceNearestCol) {\n accumulator += getDy(b, dyR, dyC, d);\n }\n }\n }\n // End loop over dy\n\n setOutput(accumulator);\n }\n "}}(),ResizeNearestNeighborProgram=function(){return function(p,e,t,r){this.variableNames=["A"],this.outputShape=[];var n=p[0],o=p[1],a=p[2],i=p[3];this.outputShape=[n,e,t,i];var s=[r&&1= "+n+") {\n return initializationValue;\n }\n ");var d="";0= "+n+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+l+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+d+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+o+")) * float("+e+"));\n int currentSeg = int(mod(float(outIdx), float("+o+")));\n\n float sumValue = 0.0;\n\n for (int i = 0; i < "+i+"; i += 4) {\n int inIdx = inOffset + i;\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n );\n\n "+"\n sumValue += dot(values, filter);\n "+"\n }\n\n int inIdx = inOffset + "+i+";\n if ("+(1==s)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n 0,\n 0,\n 0\n );\n\n "+"\n sumValue += dot(values, filter);\n "+"\n } else if ("+(2==s)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n 0,\n 0\n );\n\n "+"\n sumValue += dot(values, filter);\n "+"\n } else if ("+(3==s)+") {\n vec4 values = vec4(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n vec4 filter = vec4(\n int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n 0\n );\n\n "+"\n sumValue += dot(values, filter);\n "+"\n }\n setOutput(sumValue);\n }\n "}}(),SelectProgram=function(){return function(p,e,t){var r,d;if(this.variableNames=["c","a","b"],this.outputShape=e,4= 1.0) {\n setOutput(getA("+d+"));\n } else {\n setOutput(getB("+d+"));\n }\n }\n "}}(),SliceProgram=function(){function t(a){this.variableNames=["source"],this.outputShape=a,this.rank=a.length;var e=getCoordsDataType(this.rank),t=getCoords$1(this.rank);this.userCode="\n uniform "+e+" start;\n\n void main() {\n "+e+" sourceLoc = start + getOutputCoords();\n setOutput(getSource("+t+"));\n }\n "}return t.prototype.getCustomSetupFunc=function(a){var e=this;if(a.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+a.length+")");return function(t,r){if(null!=e.startLoc||(e.startLoc=t.getUniformLocationNoThrow(r,"start"),null!=e.startLoc))if(1===e.rank)t.gl.uniform1i(e.startLoc,a[0]);else if(2===e.rank)t.gl.uniform2i(e.startLoc,a[0],a[1]);else if(3===e.rank)t.gl.uniform3i(e.startLoc,a[0],a[1],a[2]);else{if(4!==e.rank)throw Error("Slicing for rank "+e.rank+" is not yet supported");t.gl.uniform4i(e.startLoc,a[0],a[1],a[2],a[3])}}},t}(),StridedSliceProgram=function(){return function(p,e,t,r){this.variableNames=["x"];var n=t.filter(function(a,e){return-1===r.indexOf(e)});this.outputShape=n;var o=t.length,a=getCoordsDataType(t.length),i=getCoordsDataType(n.length),s="";if(1===o)s="coords * strides + begin";else{var d=0;s=t.map(function(a,e){return-1===r.indexOf(e)?(d++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(d-1)+"] * strides["+e+"] + begin["+e+"]"):"begin["+e+"]"}).join(",")}this.userCode="\n "+a+" begin = "+a+"("+p+");\n "+a+" strides = "+a+"("+e+");\n\n void main() {\n "+i+" coords = getOutputCoords();\n setOutput(getX("+s+"));\n }\n "}}(),TextureManager=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(s,e,t){var r=getPhysicalFromLogicalTextureType(e,t),o=getKeyFromTextureShape(s,r,t),a;if(o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]),0a)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(a,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var a=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){a.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){a.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}(),TileProgram=function(){return function(s,e){this.variableNames=["A"];for(var t=Array(s.length),r=0;r= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n",NEG="return -x;",CEIL="return ceil(x);",FLOOR="return floor(x);",SIGN="\n if (isNaN(x)) { return 0.0; }\n return sign(x);\n",ROUND="\n // OpenGL ES does not support round function.\n // The algorithm is based on banker's rounding.\n float base = floor(x);\n if ((x - base) < 0.5) {\n return floor(x);\n } else if ((x - base) > 0.5) {\n return ceil(x);\n } else {\n if (mod(base, 2.0) == 0.0) {\n return base;\n } else {\n return base + 1.0;\n }\n }\n",EXP="return exp(x);",EXPM1="return exp(x) - 1.0;",LOG="if (x < 0.0) return NAN;\n return log(x);",LOG1P="return log(1.0 + x);",SQRT="return sqrt(x);",RSQRT="return inversesqrt(x);",SIGMOID="return 1.0 / (1.0 + exp(-1.0 * x));",SOFTPLUS="\n float epsilon = 1.1920928955078125e-7;\n float threshold = log(epsilon) + 2.0;\n\n bool too_large = x > -threshold;\n bool too_small = x < threshold;\n\n float result;\n float exp_x = exp(x);\n\n if (too_large){\n result = x;\n }\n else if (too_small){\n result = exp_x;\n }\n else{\n result = log(exp_x + 1.0);\n }\n return result;\n",SIN=CHECK_NAN_SNIPPET$1+"\n return sin(x);\n",COS=CHECK_NAN_SNIPPET$1+"\n return cos(x);\n",TAN="return tan(x);",ASIN="return asin(x);",ACOS="return acos(x);",ATAN=CHECK_NAN_SNIPPET$1+"\n return atan(x);\n",SINH="\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n",COSH="\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n",TANH="\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n",ASINH="return log(x + sqrt(x * x + 1.0));",ACOSH=CHECK_NAN_SNIPPET$1+"\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));",ATANH=CHECK_NAN_SNIPPET$1+"\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;",ERF="\n // Error function is calculated approximately with elementary function.\n // See \"Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables\", Abramowitz and Stegun.\n float p = "+ERF_P+";\n float a1 = "+ERF_A1+";\n float a2 = "+ERF_A2+";\n float a3 = "+ERF_A3+";\n float a4 = "+ERF_A4+";\n float a5 = "+ERF_A5+";\n\n float t = 1.0 / (1.0 + p * x);\n return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n",SQUARE="return x * x;",RECIPROCAL="return 1.0 / x;",LOGICAL_NOT="return float(!(x >= 1.0));",TO_INT="return float(int(x));",UnpackProgram=function(){return function(s){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=s;var e=s.length,t=getChannels("rc",e),r=getCoordsDataType(e),n=getSourceCoords$1(e,t),o=t.slice(-2),a=1===e?"rc":"vec2("+o.join(",")+")";this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n vec4 packedInput = getA("+n+");\n\n setOutput(getChannel(packedInput, "+a+"));\n }\n "}}(),concat=op({concat_:concat_}),concat1d=op({concat1d_:concat1d_}),concat2d=op({concat2d_:concat2d_}),concat3d=op({concat3d_:concat3d_}),concat4d=op({concat4d_:concat4d_}),split$1=op({split_:split_}),alea=createCommonjsModule(function(t){!function(a,e,t){function s(a,e){return e.c=a.c,e.s0=a.s0,e.s1=a.s1,e.s2=a.s2,e}function n(n,e){var t=new function(a){var o=this,e=(s=4022871197,function(t){t=t.toString();for(var a=0,o;a>>0,s=(o*=s)>>>0,s+=4294967296*(o-=s);return 23283064365386963e-26*(s>>>0)}),s;o.next=function(){var t=2091639*o.s0+23283064365386963e-26*o.c;return o.s0=o.s1,o.s1=o.s2,o.s2=t-(o.c=0|t)},o.c=1,o.s0=e(" "),o.s1=e(" "),o.s2=e(" "),o.s0-=e(a),0>o.s0&&(o.s0+=1),o.s1-=e(a),0>o.s1&&(o.s1+=1),o.s2-=e(a),0>o.s2&&(o.s2+=1),e=null}(n),r=e&&e.state,o=t.next;return o.int32=function(){return 0|4294967296*t.next()},o.double=function(){return o()+11102230246251565e-32*(0|2097152*o())},o.quick=o,r&&("object"==typeof r&&s(r,t),o.state=function(){return s(t,{})}),o}e&&e.exports?e.exports=n:t&&t.amd?t(function(){return n}):this.alea=n}(0,t,!1)}),xor128=createCommonjsModule(function(t){!function(a,e,t){function s(a,e){return e.x=a.x,e.y=a.y,e.z=a.z,e.w=a.w,e}function n(n,e){var t=new function(a){var o=this,e="";o.x=0,o.y=0,o.z=0,o.w=0,o.next=function(){var t=o.x^o.x<<11;return o.x=o.y,o.y=o.z,o.z=o.w,o.w^=o.w>>>19^t^t>>>8},a===(0|a)?o.x=a:e+=a;for(var t=0;t>>0)/4294967296};return o.double=function(){do var a=((t.next()>>>11)+(t.next()>>>0)/4294967296)/2097152;while(0===a);return a},o.int32=t.next,o.quick=o,r&&("object"==typeof r&&s(r,t),o.state=function(){return s(t,{})}),o}e&&e.exports?e.exports=n:t&&t.amd?t(function(){return n}):this.xor128=n}(0,t,!1)}),xorwow=createCommonjsModule(function(t){!function(a,e,t){function s(a,e){return e.x=a.x,e.y=a.y,e.z=a.z,e.w=a.w,e.v=a.v,e.d=a.d,e}function n(n,e){var t=new function(a){var o=this,e="";o.next=function(){var t=o.x^o.x>>>2;return o.x=o.y,o.y=o.z,o.z=o.w,o.w=o.v,0|(o.d=0|o.d+362437)+(o.v=o.v^o.v<<4^t^t<<1)},o.x=0,o.y=0,o.z=0,o.w=0,o.v=0,a===(0|a)?o.x=a:e+=a;for(var t=0;t>>4),o.next()}(n),r=e&&e.state,o=function(){return(t.next()>>>0)/4294967296};return o.double=function(){do var a=((t.next()>>>11)+(t.next()>>>0)/4294967296)/2097152;while(0===a);return a},o.int32=t.next,o.quick=o,r&&("object"==typeof r&&s(r,t),o.state=function(){return s(t,{})}),o}e&&e.exports?e.exports=n:t&&t.amd?t(function(){return n}):this.xorwow=n}(0,t,!1)}),xorshift7=createCommonjsModule(function(t){!function(a,e,t){function s(a,e){return e.x=a.x.slice(),e.i=a.i,e}function n(n,i){null==n&&(n=+new Date);var t=new function(a){var s=this;s.next=function(){var t=s.x,a=s.i,n,o;return n=t[a],o=(n^=n>>>7)^n<<24,o^=(n=t[7&a+1])^n>>>10,o^=(n=t[7&a+3])^n>>>3,o^=(n=t[7&a+4])^n<<7,n=t[7&a+7],o^=(n^=n<<13)^n<<9,t[a]=o,s.i=7&a+1,o},function(a,e){var o=[],n;if(e===(0|e))o[0]=e;else for(e=""+e,n=0;no.length;)o.push(0);for(n=0;8>n&&0===o[n];++n);for(8==n?o[7]=-1:o[n],a.x=o,a.i=0,n=256;0>>0)/4294967296};return o.double=function(){do var a=((t.next()>>>11)+(t.next()>>>0)/4294967296)/2097152;while(0===a);return a},o.int32=t.next,o.quick=o,r&&(r.x&&s(r,t),o.state=function(){return s(t,{})}),o}e&&e.exports?e.exports=n:t&&t.amd?t(function(){return n}):this.xorshift7=n}(0,t,!1)}),xor4096=createCommonjsModule(function(t){!function(a,e,t){function s(a,e){return e.i=a.i,e.w=a.w,e.X=a.X.slice(),e}function n(n,i){null==n&&(n=+new Date);var t=new function(a){var s=this;s.next=function(){var t=s.w,i=s.X,o=s.i,p,l;return s.w=t=0|t+1640531527,l=i[127&o+34],p=i[o=127&o+1],l^=l<<13,p^=p<<17,l^=l>>>15,p^=p>>>12,l=i[o]=l^p,s.i=o,0|l+(t^t>>>16)},function(p,e){var l=[],s=128,d,c,m,h,g;for(e===(0|e)?(c=e,e=null):(e+="\0",c=0,s=_Mathmax(s,e.length)),m=0,h=-32;h>>15,c^=c<<4,c^=c>>>13,0<=h&&(g=0|g+1640531527,m=0==(d=l[127&h]^=c+g)?m+1:0);for(128<=m&&(l[127&(e&&e.length||0)]=-1),m=127,h=512;0>>15,d^=d>>>12,l[m]=c^d;p.w=g,p.X=l,p.i=m}(s,a)}(n),r=i&&i.state,o=function(){return(t.next()>>>0)/4294967296};return o.double=function(){do var a=((t.next()>>>11)+(t.next()>>>0)/4294967296)/2097152;while(0===a);return a},o.int32=t.next,o.quick=o,r&&(r.X&&s(r,t),o.state=function(){return s(t,{})}),o}e&&e.exports?e.exports=n:t&&t.amd?t(function(){return n}):this.xor4096=n}(0,t,!1)}),tychei=createCommonjsModule(function(t){!function(a,e,t){function s(a,e){return e.a=a.a,e.b=a.b,e.c=a.c,e.d=a.d,e}function n(n,e){var t=new function(a){var s=this,e="";s.next=function(){var t=s.b,a=s.c,i=s.d,p=s.a;return t=t<<25^t>>>7^a,a=0|a-i,i=i<<24^i>>>8^p,p=0|p-t,s.b=t=t<<20^t>>>12^a,s.c=a=0|a-i,s.d=i<<16^a>>>16^p,s.a=0|p-t},s.a=0,s.b=0,s.c=-1640531527,s.d=1367130551,a===_Mathfloor(a)?(s.a=0|a/4294967296,s.b=0|a):e+=a;for(var t=0;t>>0)/4294967296};return o.double=function(){do var a=((t.next()>>>11)+(t.next()>>>0)/4294967296)/2097152;while(0===a);return a},o.int32=t.next,o.quick=o,r&&("object"==typeof r&&s(r,t),o.state=function(){return s(t,{})}),o}e&&e.exports?e.exports=n:t&&t.amd?t(function(){return n}):this.tychei=n}(0,t,!1)}),seedrandom=createCommonjsModule(function(a){!function(s,i){function e(a,e,n){var m=[],h=t(function s(e,t){var r=[],o=typeof e,a;if(t&&"object"==o)for(a in e)try{r.push(s(e[a],t-1))}catch(t){}return r.length?r:"string"==o?e:e+"\0"}((e=1==e?{entropy:!0}:e||{}).entropy?[a,p(s)]:null==a?function(){try{var t;return c&&(t=c.randomBytes)?t=t(256):(t=new Uint8Array(256),(d.crypto||d.msCrypto).getRandomValues(t)),p(t)}catch(t){var a=d.navigator,n=a&&a.plugins;return[+new Date,d,n,d.screen,p(s)]}}():a,3),m),g=new function(a){var p=a.length,l=this,n=0,d=l.i=l.j=0,u=l.S=[],s;for(p||(a=[p++]);n<256;)u[n]=n++;for(n=0;n<256;n++)u[n]=u[d=255&d+a[n%p]+(s=u[n])],u[d]=s;(l.g=function(a){for(var n=0,p=l.i,d=l.j,u=l.S,s;a--;)s=u[p=255&p+1],n=n*256+u[255&(u[p]=u[d=255&d+s])+(u[d]=s)];return l.i=p,l.j=d,n})(256)}(m),f=function(){for(var a=g.g(6),n=o,s=0;a=l;)a/=2,n/=2,s>>>=1;return(a+s)/n};return f.int32=function(){return 0|g.g(4)},f.quick=function(){return g.g(4)/4294967296},f.double=f,t(p(g.S),s),(e.pass||n||function(a,e,t,n){return n&&(n.S&&r(n,g),a.state=function(){return r(g,{})}),t?(i.random=a,e):a})(f,h,"global"in e?e.global:this==i,e.state)}function r(a,e){return e.i=a.i,e.j=a.j,e.S=a.S.slice(),e}function t(a,e){for(var t=a+"",n=0,s;n=this.lower},t}(),batchToSpaceND=op({batchToSpaceND_:batchToSpaceND_}),cast=op({cast_:cast_}),clone=op({clone_:clone_}),cumsum=op({cumsum_:cumsum_}),depthToSpace=op({depthToSpace_:depthToSpace_}),expandDims=op({expandDims_:expandDims_}),eye=op({eye_:eye_}),fromPixels=op({fromPixels_:fromPixels_}),multinomial=op({multinomial_:multinomial_}),oneHot=op({oneHot_:oneHot_}),pad=op({pad_:pad_}),pad1d=op({pad1d_:pad1d_}),pad2d=op({pad2d_:pad2d_}),pad3d=op({pad3d_:pad3d_}),pad4d=op({pad4d_:pad4d_}),rand=op({rand_:rand_}),randomNormal=op({randomNormal_:randomNormal_}),randomUniform=op({randomUniform_:randomUniform_}),reshape=op({reshape_:reshape_}),spaceToBatchND=op({spaceToBatchND_:spaceToBatchND_}),squeeze=op({squeeze_:squeeze_}),stack=op({stack_:stack_}),tile=op({tile_:tile_}),truncatedNormal=op({truncatedNormal_:truncatedNormal_}),unstack=op({unstack_:unstack_}),setdiff1dAsync=setdiff1dAsync_,CPU_HANDOFF_SIZE_THRESHOLD=10,BEFORE_PAGING_CONSTANT=300,MATMUL_SHARED_DIM_THRESHOLD=1e3,MathBackendWebGL=function(){function t(a,e){if(void 0===e&&(e=!0),this.gpgpu=a,this.delayedStorage=e,this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.lruDataGPU=[],this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.binaryCache={},this.disposed=!1,1>ENV.get("WEBGL_VERSION"))throw new Error("WebGL is not supported on this device");if(null==a){var n=getWebGLContext(ENV.get("WEBGL_VERSION"));this.gpgpu=new GPGPUContext(n),this.canvas=n.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpuCreatedLocally=!1,this.canvas=a.gl.canvas;ENV.get("WEBGL_PAGING_ENABLED")&&(this.NUM_BYTES_BEFORE_PAGING=window.screen.height*window.screen.width*window.devicePixelRatio*BEFORE_PAGING_CONSTANT),this.textureManager=new TextureManager(this.gpgpu)}return t.prototype.register=function(a,e,t){if(this.texData.has(a))throw new Error("Data buffer is already registered");this.texData.set(a,{shape:e,dtype:t,values:null,texture:null,complexTensors:null,texShape:null,usage:TextureUsage.RENDER,isPacked:!1})},t.prototype.setDataMover=function(t){this.texData=new DataStorage(t)},t.prototype.fromPixels=function(s,p){if(null==s)throw new Error("pixels passed to tf.fromPixels() can not be null");var t=[s.height,s.width],r=[s.height,s.width,p];if(!(s instanceof HTMLVideoElement||s instanceof HTMLImageElement||s instanceof HTMLCanvasElement||s instanceof ImageData))throw new Error("pixels passed to tf.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement or ImageData, but was "+s.constructor.name);if(s instanceof HTMLVideoElement){if(null==this.fromPixels2DContext){if(!ENV.get("IS_BROWSER"))throw new Error("Can't read pixels from HTMLImageElement outside the browser.");if("complete"!==document.readyState)throw new Error("The DOM is not ready yet. Please call tf.fromPixels() once the DOM is ready. One way to do that is to add an event listener for `DOMContentLoaded` on the document object");this.fromPixels2DContext=document.createElement("canvas").getContext("2d")}this.fromPixels2DContext.canvas.width=s.width,this.fromPixels2DContext.canvas.height=s.height,this.fromPixels2DContext.drawImage(s,0,0,s.width,s.height),s=this.fromPixels2DContext.canvas}var n=this.makeTensorHandle(t,"int32");this.texData.get(n.dataId).usage=TextureUsage.PIXELS,this.gpgpu.uploadPixelDataToTexture(this.getTexture(n.dataId),s);var o=new FromPixelsProgram(r),a=this.compileAndRun(o,[n]);return this.disposeData(n.dataId),a},t.prototype.makeTensorHandle=function(a,e){var t={};return this.register(t,a,e),{dataId:t,shape:a,dtype:e}},t.prototype.write=function(p,e){if(null==e)throw new Error("MathBackendWebGL.write(): values can not be null");var t=this.texData.get(p),r=t.texture,n=t.texShape,o=t.usage,a=t.dtype,i=t.isPacked;if("complex64"===a)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");null!=r&&(this.releaseTexture(p,r,n,o,i),t.texture=null,t.texShape=null),t.usage=TextureUsage.UPLOAD,t.values=e,this.delayedStorage||this.uploadToGPU(p)},t.prototype.readSync=function(p){var e=this.texData.get(p),t=e.values,r=e.dtype,n=e.complexTensors;if(null!=t)return this.convertAndCacheOnCPU(p);var o=null!=this.activeTimers,s,l;return l=(o&&(s=performance.now()),"complex64"===r)?mergeRealAndImagArrays(n.real.dataSync(),n.imag.dataSync()):this.getValuesFromTexture(p),o&&(this.downloadWaitMs+=performance.now()-s),this.convertAndCacheOnCPU(p,l)},t.prototype.read=function(p){return __awaiter(this,void 0,void 0,function(){var d,e,m,h,g,f,y,b,x;return __generator(this,function(t){switch(t.label){case 0:if(this.pendingRead.has(p))return d=this.pendingRead.get(p),[2,new Promise(function(t){return d.push(t)})];if(e=this.texData.get(p),m=e.texture,h=e.values,g=e.texShape,null!=h)return[2,this.convertAndCacheOnCPU(p)];if(this.pendingRead.set(p,[]),!ENV.get("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===ENV.get("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return f=this.gpgpu.maybeCreateBufferFromTexture(m,g[0],g[1]),[4,this.gpgpu.createAndWaitForFence()];case 1:return t.sent(),y=f instanceof WebGLTexture?this.getValuesFromTexture(p):this.gpgpu.downloadFloat32MatrixFromBuffer(f,g[0],g[1]),b=this.convertAndCacheOnCPU(p,y),x=this.pendingRead.get(p),this.pendingRead.delete(p),x.forEach(function(t){return t(b)}),this.pendingDisposal.has(p)&&(this.pendingDisposal.delete(p),this.disposeData(p)),[2,b];}})})},t.prototype.getValuesFromTexture=function(m){var e=this.texData.get(m),t=e.shape,r=e.dtype,n=e.texture,o=e.texShape;if(ENV.get("WEBGL_DOWNLOAD_FLOAT_ENABLED")){if(this.texData.get(m).isPacked){var a=sizeFromShape(t.slice(0,t.length-2)),i=1MATMUL_SHARED_DIM_THRESHOLD){y&&(m=m.transpose([0,2,1])),r&&(g=g.transpose([0,2,1]));var s=1===o?m:m.as3D(i,a,1),u=1===o?2:1,l=1===o?g.as3D(i,1,a):g;return this.multiply(s,l).sum(u,!0)}if(1===i){var c=m.as2D(m.shape[1],m.shape[2]),p=g.as2D(g.shape[1],g.shape[2]),d=new MatMulPackedProgram(c.shape,p.shape,[n,o],y,r),h=this.compileAndRun(d,[c,p],this.makePackedTensor(d.outputShape));return!1===ENV.get("WEBGL_LAZILY_UNPACK")&&(h=this.unpackTensor(h)),h.reshape([1,h.shape[0],h.shape[1]])}return this.compileAndRun(new MatMulProgram(m.shape,g.shape,y,r),[m,g])},t.prototype.multiply=function(d,e){if("complex64"===d.dtype){var t=this.texData.get(d.dataId),r=this.texData.get(e.dataId),n=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.REAL,d.shape,e.shape),o=new BinaryOpComplexProgram(COMPLEX_MULTIPLY.IMAG,d.shape,e.shape),a=[this.makeComplexComponentTensorHandle(d,t.complexTensors.real),this.makeComplexComponentTensorHandle(d,t.complexTensors.imag),this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag)],i=this.compileAndRun(n,a),s=this.compileAndRun(o,a),u=this.complex(i,s);return i.dispose(),s.dispose(),u}if(this.shouldExecuteOnCPU([d,e]))return this.cpuBackend.multiply(d,e);var l=new BinaryOpProgram(MUL,d.shape,e.shape),c=this.makeOutputArray(l.outputShape,d.dtype);return this.compileAndRun(l,[d,e],c)},t.prototype.batchNormalization=function(d,e,t,r,n,o){var a=[d,e,t],i=null;null!=o&&(i=o.shape,a.push(o));var m=null;null!=n&&(m=n.shape,a.push(n));var h=null,g=BatchNormProgram;ENV.get("WEBGL_PACK_BATCHNORMALIZATION")&&(h=this.makePackedTensor(d.shape),g=BatchNormPackedProgram);var f=new g(d.shape,e.shape,t.shape,i,m,r);return this.compileAndRun(f,a,h)},t.prototype.localResponseNormalization4D=function(s,e,t,r,n){var o=new LRNProgram(s.shape,e,t,r,n);return this.compileAndRun(o,[s])},t.prototype.LRNGrad=function(p,e,t,r,n,o,a){var i=new LRNGradProgram(e.shape,r,n,o,a);return this.compileAndRun(i,[e,t,p])},t.prototype.tile=function(a,e){var t=new TileProgram(a.shape,e);return this.compileAndRun(t,[a])},t.prototype.pad=function(a,e,t){var r=new PadProgram(a.shape,e,t);return this.compileAndRun(r,[a])},t.prototype.transpose=function(a,e){var t=new TransposeProgram(a.shape,e);return this.compileAndRun(t,[a])},t.prototype.gather=function(a,e,t){var r=new GatherProgram(a.shape,e.size,t);return this.compileAndRun(r,[a,e])},t.prototype.batchToSpaceND=function(p,e,t){assert(4>=p.rank,"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");var r=e.reduce(function(a,e){return a*e}),n=getReshaped(p.shape,e,r),o=getPermuted(n.length,e.length),a=getReshapedPermuted(p.shape,e,r),i=getSliceBeginCoords(t,e.length),s=getSliceSize(a,t,e.length);return p.reshape(n).transpose(o).reshape(a).slice(i,s)},t.prototype.spaceToBatchND=function(p,e,t){assert(4>=p.rank,"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");var r=e.reduce(function(a,e){return a*e}),n=[[0,0]];n.push.apply(n,t);for(var o=1+e.length;o 1 for depthToSpace, but was: "+e);var r=p.shape[0],n=("NHWC"===t?p.shape[1]:p.shape[2])*e,o=("NHWC"===t?p.shape[2]:p.shape[3])*e,a=("NHWC"===t?p.shape[3]:p.shape[1])/(e*e),i=new DepthToSpaceProgram("NHWC"===t?[r,n,o,a]:[r,a,n,o],e,t);return this.compileAndRun(i,[p])},t.prototype.split=function(a,e,t){return split(a,e,t)},t.prototype.scatterND=function(l,e,t){var r=calculateShapes(e,l,t),n=r.sliceRank,o=r.numUpdates,a=r.sliceSize,i=r.strides,s=r.outputSize,u=l.reshape([o,n]),c=e.reshape([o,a]);if(0===s)return reshapeTensor(tensor([]),t);var p=scalar(0),d=new ScatterProgram(o,n,u.rank,c.rank,i,[s/a,a]);return this.compileAndRun(d,[c,u,p]).reshape(t)},t.prototype.sparseToDense=function(p,e,t,r){var n=calculateShapes(e,p,t),o=n.sliceRank,a=n.numUpdates,i=n.strides,s=n.outputSize,d=new ScatterProgram(a,o,p.rank,e.rank,i,[s,1],!1);return this.compileAndRun(d,[e,p,r]).reshape(t)},t.prototype.fft=function(t){return this.fftImpl(t,!1)},t.prototype.ifft=function(t){return this.fftImpl(t,!0)},t.prototype.fftImpl=function(p,e){var t=this.texData.get(p.dataId),r=new FFTProgram(COMPLEX_FFT.REAL,p.shape,e),n=new FFTProgram(COMPLEX_FFT.IMAG,p.shape,e),o=[this.makeComplexComponentTensorHandle(p,t.complexTensors.real),this.makeComplexComponentTensorHandle(p,t.complexTensors.imag)],a=this.compileAndRun(r,o),i=this.compileAndRun(n,o),s=this.complex(a,i).as2D(p.shape[0],p.shape[1]);return a.dispose(),i.dispose(),s},t.prototype.gatherND=function(d,e){var t=e.shape,r=t[t.length-1],n=prepareAndValidate(d,e),o=n[0],a=n[1],i=n[2],s=n[3],u=e.reshape([a,r]),l=d.reshape([d.size/i,i]),c=new GatherNDProgram(r,s,[a,i]);return this.compileAndRun(c,[l,u]).reshape(o)},t.prototype.makeOutputArray=function(a,e){return Tensor.make(a,{},e)},t.prototype.makePackedTensor=function(a){var e=Tensor.make(a,{});return this.texData.get(e.dataId).isPacked=!0,e},t.prototype.unpackTensor=function(a){var e=new UnpackProgram(a.shape);return this.compileAndRun(e,[a])},t.prototype.getBatchDim=function(a,e){return void 0===e&&(e=2),sizeFromShape(a.slice(0,a.length-e))},t.prototype.getRowsCols=function(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[1this.NUM_BYTES_BEFORE_PAGING)for(var N=this.numBytesInGPU-this.NUM_BYTES_BEFORE_PAGING;0p&&(p=N,b=x);s[l]=b}return a},t.prototype.cumsum=function(m,e,t,r){if(this.assertNotComplex(m,"cumsum"),e!==m.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(m.rank-1)+" but got axis="+e);for(var n=upcastType(m.dtype,"int32"),o=zeros(m.shape,n),a=o.dataSync(),i=m.dataSync(),s=m.shape[m.rank-1],u=r?function(a,e){return a+s-e-1}:function(a,e){return a+e},l=0;le?1:0})},t.prototype.greaterEqual=function(a,e){return this.assertNotComplex([a,e],"greaterEqual"),this.broadcastedBinaryOp(a,e,"bool",function(a,e){return a>=e?1:0})},t.prototype.logicalNot=function(a){this.assertNotComplex(a,"logicalNot");for(var e=a.dataSync(),t=new Int32Array(e.length),r=0;ra&&0>e||0<=a&&0<=e?t:(t+e)%e})},t.prototype.max=function(m,e){this.assertNotComplex(m,"max"),assertAxesAreInnerMostDims("max",e,m.rank);for(var t=computeOutAndReduceShapes(m.shape,e),r=t[0],n=t[1],o=zeros(r,m.dtype),a=sizeFromShape(n),i=o.dataSync(),s=m.dataSync(),u=0;uc&&(c=y);i[u]=c}return o},t.prototype.maximum=function(a,e){return this.assertNotComplex([a,e],"maximum"),this.broadcastedBinaryOp(a,e,a.dtype,function(a,e){return _Mathmax(a,e)})},t.prototype.all=function(m,e){this.assertNotComplex(m,"all"),assertAxesAreInnerMostDims("all",e,m.rank);for(var t=computeOutAndReduceShapes(m.shape,e),r=t[0],n=t[1],o=zeros(r,m.dtype),a=sizeFromShape(n),i=o.dataSync(),s=m.dataSync(),u=0;ue[r]?-1:0e[r]-s?_Mathfloor(e[r]):.5t?t:p-e,a=r[n]z||z>=t.inHeight))for(var F=y*e.strides[0],E=O+z*P.strides[1],w=0;wV||V>=t.inWidth))for(var U=F+C*e.strides[1],N=E+V*t.inChannels,R=U,W=0;WB||B>=t.inHeight))for(var V=x*e.strides[0],w=z+B*L.strides[1],S=0;SW||W>=t.inWidth))for(var G=V+_*e.strides[1],R=w+W*t.inChannels,I=U,q=G,H=0;HI?I=$:"avg"==t&&(G+=$,q++);if(isNaN(I))break}h[C+_*g+T]="avg"===t?G/q:I}return d.toTensor()},t.prototype.maxPool=function(a,e){return this.pool(a,e,"max")},t.prototype.maxPoolPositions=function(N,e){for(var t=buffer(e.outShape,"int32"),r=e.strideHeight,n=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,i=e.effectiveFilterHeight,s=e.effectiveFilterWidth,u=e.padInfo.top,l=e.padInfo.left,c=0;cf;)f+=o;for(var D=_Mathmin(e.inHeight,i+R),g=0;gy;)y+=a;for(var O=_Mathmin(e.inWidth,s+P),T=_NumberNEGATIVE_INFINITY,L=-1,z=f;zT&&(T=_,L=M*s+F)}t.set(L,c,k,g,I)}}return t.toTensor()},t.prototype.maxPoolBackprop=function(N,e,t,r){this.assertNotComplex([e,t],"maxPoolBackprop");for(var n=this.maxPoolPositions(e,r),o=r.strideHeight,a=r.strideWidth,i=r.dilationHeight,s=r.dilationWidth,u=r.effectiveFilterHeight,l=r.effectiveFilterWidth,c=l-1-r.padInfo.left,p=u-1-r.padInfo.top,d=buffer(e.shape,"float32"),h=0;hA||A>=r.outHeight||_Mathfloor(A)!==A))for(var _=0,O;_O||O>=r.outWidth||_Mathfloor(O)!==O)){var L=u*l-1-n.get(h,A,O,I)===P*l+_?1:0;0!=L&&(x+=N.get(h,A,O,I)*L)}d.set(x,h,k,R,I)}return d.toTensor()},t.prototype.avgPoolBackprop=function(f,e,t){this.assertNotComplex([f,e],"avgPoolBackprop");for(var r=t.strideHeight,n=t.strideWidth,o=t.filterHeight,a=t.filterWidth,i=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=l-1-t.padInfo.left,p=u-1-t.padInfo.top,d=buffer(e.shape,"float32"),h=0;hP||P>=t.outHeight||_Mathfloor(P)!==P))for(var A=0,_;A_||_>=t.outWidth||_Mathfloor(_)!==_||(T+=f.get(h,P,_,N));d.set(T*(1/(o*a)),h,I,k,N)}return d.toTensor()},t.prototype.cast=function(a,e){return castTensor(a,e,this)},t.prototype.reshape=function(a,e){return reshapeTensor(a,e)},t.prototype.avgPool=function(a,e){return this.assertNotComplex(a,"avgPool"),this.pool(a,e,"avg").toFloat()},t.prototype.resizeBilinear=function(T,e,t,r){this.assertNotComplex(T,"resizeBilinear");for(var n=T.shape,o=n[0],a=n[1],i=n[2],s=n[3],u=T.dataSync(),l=new Float32Array(sizeFromShape([o,e,t,s])),c=[r&&1$||$>=u)){var K=W+$*V.strides[1],P=$*f;if(w===_Mathmin(o-1,t?_Mathround(P):_Mathfloor(P)))for(var F=0,X;FX||X>=l)){var Y=K+X*V.strides[2],U=X*m;_===_Mathmin(a-1,t?_Mathround(U):_Mathfloor(U))&&(H+=p[Y+I])}}c[q+I]=H}return tensor4d(c,e.shape,e.dtype)},t.prototype.batchNormalization=function(b,e,t,r,n,o){this.assertNotComplex([b,e,t,n,o],"batchNormalization");for(var a=b.dataSync(),i=e.dataSync(),s=t.dataSync(),u=n?n.dataSync():new Float32Array([1]),l=o?o.dataSync():new Float32Array([0]),c=new Float32Array(a.length),p=l.length,d=u.length,h=s.length,f=i.length,m=0,N=0,I=0,S=0,C=0;C=p&&(m=0),N>=f&&(N=0),I>=d&&(I=0),S>=h&&(S=0);return tensor4d(c,b.shape)},t.prototype.localResponseNormalization4D=function(m,g,e,t,n){function r(t){for(var e=t%c,r=t-e+_Mathmax(0,e-g),s=t-e+_Mathmin(e+g,a),o=0,p;r<=s;r++)p=i[r],o+=p*p;return o}this.assertNotComplex(m,"localResponseNormalization4D");for(var c=m.shape[3],a=c-1,i=m.dataSync(),o=sizeFromShape(m.shape),s=new Float32Array(o),l=0;l 1 for depthToSpace, but was: "+e);for(var r=b.shape[0],n=b.shape[1],o=b.shape[2],a=b.shape[3],i=n*e,s=o*e,u=a/(e*e),l=b.dataSync(),c=new Float32Array(r*i*s*u),p=0,N=0;N=i))for(var _=1Q||Q>s-1)for(var J=0;J(W=1u-1)for(ee=0;ee(W=1u-1)for(ee=0;eeh||h>=y.size/i)throw new Error("Invalid indices: does not index into "+y.shape);for(var I=0;Im||m>=r/n)throw new Error("Invalid indices: does not index into "+t);for(var S=0;St.length)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t}return t.prototype.load=function(){return __awaiter(this,void 0,void 0,function(){var a=this,r,m;return __generator(this,function(){return r=this.files[0],m=this.files.slice(1),[2,new Promise(function(h,t){var e=new FileReader;e.onload=function(e){var n=JSON.parse(e.target.result),i=n.modelTopology;if(null!=i){0===m.length&&h({modelTopology:i});var o=n.weightsManifest;if(null!=o){var s;try{s=a.checkManifestAndWeightFiles(o,m)}catch(a){return void t(a)}var u=[],c=[],p=[];o.forEach(function(t){t.paths.forEach(function(t){c.push(t),p.push(null)}),u.push.apply(u,t.weights)}),o.forEach(function(a){a.paths.forEach(function(a){var e=new FileReader;e.onload=function(e){var t=e.target.result,n=c.indexOf(a);p[n]=t,-1===p.indexOf(null)&&h({modelTopology:i,weightSpecs:u,weightData:concatenateArrayBuffers(p)})},e.onerror=function(){t("Failed to weights data from file of path '"+a+"'.")},e.readAsArrayBuffer(s[a])})})}else t(new Error("weightManifest field is missing from file "+r.name))}else t(new Error("modelTopology field is missing from file "+r.name))},e.onerror=function(){t("Failed to read model topology and weights manifest JSON from file '"+r.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},e.readAsText(r)})]})})},t.prototype.checkManifestAndWeightFiles=function(s,p){for(var t=[],r=p.map(function(t){return basename(t.name)}),n={},e=0,o=s;ee.scale)throw new ValueError("scale must be a positive float. Got: "+e.scale);return t.scale=null==e.scale?1:e.scale,t.mode=e.mode,checkFanMode(t.mode),t.distribution=e.distribution,checkDistribution(t.distribution),t.seed=e.seed,t}return __extends$1(e,a),e.prototype.apply=function(p,e){var l=computeFans(p),n=l[0],r=l[1],i=this.scale;if(i/="fanIn"===this.mode?_Mathmax(1,n):"fanOut"===this.mode?_Mathmax(1,r):_Mathmax(1,(n+r)/2),"normal"===this.distribution){var d=_Mathsqrt(i);if("float32"!==(e=e||"float32")&&"int32"!==e)throw new NotImplementedError(this.getClassName()+" does not support dType "+e+".");return truncatedNormal(p,0,d,e,this.seed)}var o=_Mathsqrt(3*i);return randomUniform(p,-o,o,e)},e.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},e.className="VarianceScaling",e}(Initializer);serialization.registerClass(VarianceScaling);var GlorotUniform=function(a){function e(e){return a.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})||this}return __extends$1(e,a),e.prototype.getClassName=function(){return VarianceScaling.className},e.className="GlorotUniform",e}(VarianceScaling);serialization.registerClass(GlorotUniform);var GlorotNormal=function(a){function e(e){return a.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})||this}return __extends$1(e,a),e.prototype.getClassName=function(){return VarianceScaling.className},e.className="GlorotNormal",e}(VarianceScaling);serialization.registerClass(GlorotNormal);var HeNormal=function(a){function e(e){return a.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return __extends$1(e,a),e.prototype.getClassName=function(){return VarianceScaling.className},e.className="HeNormal",e}(VarianceScaling);serialization.registerClass(HeNormal);var LeCunNormal=function(a){function e(e){return a.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return __extends$1(e,a),e.prototype.getClassName=function(){return VarianceScaling.className},e.className="LeCunNormal",e}(VarianceScaling);serialization.registerClass(LeCunNormal);var Orthogonal=function(a){function e(e){var t=a.call(this)||this;if(t.DEFAULT_GAIN=1,t.gain=null==e.gain?t.DEFAULT_GAIN:e.gain,t.seed=e.seed,null!=t.seed)throw new NotImplementedError("Random seed is not implemented for Orthogonal Initializer yet.");return t}return __extends$1(e,a),e.prototype.apply=function(a){var e=this;return tidy(function(){if(2!==a.length)throw new NotImplementedError("The Orthogonal Initializer does not support non-2D shapes yet.");2e3a[1]?[a[1],a[0]]:a,0,1,"float32"),t=linalg_ops.gramSchmidt(n);return a[0]>a[1]&&(t=t.transpose()),mul(getScalar(e.gain),t)})},e.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},e.className="Orthogonal",e}(Initializer);serialization.registerClass(Orthogonal);var INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",identity:"Identity",leCunNormal:"LeCunNormal",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"},exports_initializers=Object.freeze({zeros:zeros$1,ones:ones$1$1,constant:constant,randomUniform:randomUniform$1,randomNormal:randomNormal$2,truncatedNormal:truncatedNormal$1,identity:identity,varianceScaling:varianceScaling,glorotUniform:glorotUniform,glorotNormal:glorotNormal,heNormal:heNormal,leCunNormal:leCunNormal,orthogonal:orthogonal}),DEFAULT_VARIABLE_NAME_PREFIX="Variable",LayerVariable=function(){function t(a,e,o,s,p){void 0===e&&(e="float32"),void 0===o&&(o=DEFAULT_VARIABLE_NAME_PREFIX),void 0===s&&(s=!0),void 0===p&&(p=null),this.dtype=null==e?"float32":e,this.shape=a.shape,this.id=getNextUniqueTensorId(),o=null==o?DEFAULT_VARIABLE_NAME_PREFIX:o,this.originalName=getScopedTensorName(o),this.name=getUniqueTensorName(this.originalName),this.trainable=s,this.constraint=p,this.val=variable(a,this.trainable,this.name,this.dtype)}return t.prototype.read=function(){return this.assertNotDisposed(),this.val},t.prototype.write=function(t){return this.assertNotDisposed(),checkShapesMatch(this.val,t),this.val.id!==t.id&&(this.val.assign(t),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this},t.prototype.dispose=function(){this.assertNotDisposed(),this.val.dispose()},t.prototype.assertNotDisposed=function(){if(this.val.isDisposed)throw new Error("LayersVariable "+this.name+" is already disposed.")},t}(),InputSpec=function(){return function(t){this.dtype=t.dtype,this.shape=t.shape,this.ndim=null==t.shape?t.ndim:t.shape.length,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}}}(),SymbolicTensor=function(){return function(s,e,t,n,r,i,a){this.dtype=s,this.shape=e,this.sourceLayer=t,this.inputs=n,this.callArgs=r,this.outputTensorIndex=a,this.id=getNextUniqueTensorId(),null!=i&&(this.originalName=getScopedTensorName(i),this.name=getUniqueTensorName(this.originalName)),this.rank=e.length}}(),_nextNodeID=0,Node=function(){function t(a,e){this.callArgs=e,this.id=_nextNodeID++,this.outboundLayer=a.outboundLayer,this.inboundLayers=a.inboundLayers,this.nodeIndices=a.nodeIndices,this.tensorIndices=a.tensorIndices,this.inputTensors=a.inputTensors,this.outputTensors=a.outputTensors,this.inputMasks=a.inputMasks,this.outputMasks=a.outputMasks,this.inputShapes=a.inputShapes,this.outputShapes=a.outputShapes;for(var t=0,o=a.inboundLayers,r;ta.SKIP_FIRST_BATCHES&&(this.batchDurationsMillis.push(t-this.batchStartMillis),this.batchDurationsMillis.length>=a.DECISION_BATCH_COUNT&&(o=this.batchDurationsMillis.reduce(function(a,e){return a+e})/this.batchDurationsMillis.length,this.autoYieldEveryBatches=_Mathround(a.THRESHOLD_MILLIS/o),1>this.autoYieldEveryBatches&&(this.autoYieldEveryBatches=1))),this.batchStartMillis=util.now(),this.lastYieldBatchCount=this.batchCount,[3,6];case 3:return this.batchCount-this.lastYieldBatchCount>=this.autoYieldEveryBatches?[4,nextFrame()]:[3,6];case 4:return n.sent(),[4,this.resolveOneTensorInLogs(e)];case 5:n.sent(),this.lastYieldBatchCount=this.batchCount,n.label=6;case 6:return[3,9];case 7:return"batch"===this.yieldEvery?[4,nextFrame()]:[3,9];case 8:n.sent(),n.label=9;case 9:return[2];}})})},a.prototype.maybeYieldOnEpoch=function(){return __awaiter$1(this,void 0,void 0,function(){return __generator$1(this,function(t){switch(t.label){case 0:return"epoch"===this.yieldEvery?[4,nextFrame()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2];}})})},a.SKIP_FIRST_BATCHES=1,a.DECISION_BATCH_COUNT=2,a.THRESHOLD_MILLIS=16,a}(),BaseLogger=function(a){function e(e){var t=a.call(this)||this;return t.yieldEvery=e||"auto",t}return __extends$1(e,a),e.prototype.onTrainBegin=function(){return __awaiter$1(this,void 0,void 0,function(){return __generator$1(this,function(){return this.autoYielder=new ModelTrainingYielder(this.yieldEvery),[2]})})},e.prototype.onEpochBegin=function(){return __awaiter$1(this,void 0,void 0,function(){return __generator$1(this,function(){return this.seen=0,this.totals={},[2]})})},e.prototype.onBatchEnd=function(a,s){return __awaiter$1(this,void 0,void 0,function(){var t=this,a,p,l,d;return __generator$1(this,function(e){switch(e.label){case 0:return[4,this.autoYielder.maybeYieldOnBatch(s)];case 1:for(d in e.sent(),null==s&&(s={}),a=null==s.size?0:s.size,this.seen+=a,p=function(e){var n=s[e];if("number"==typeof n)l.totals.hasOwnProperty(e)||(l.totals[e]=0),l.totals[e]+=n*a;else{var r;e in l.totals?r=l.totals[e]:l.totals[e]=getScalar(0),l.totals[e]=tidy(function(){return add(t.totals[e],mul(n,getScalar(a)))}),null!=r&&r.dispose()}},l=this,s)p(d);return[2];}})})},e.prototype.onEpochEnd=function(a,p){return __awaiter$1(this,void 0,void 0,function(){var t=this,o,s,l,d,u;return __generator$1(this,function(e){switch(e.label){case 0:return[4,this.autoYielder.maybeYieldOnEpoch()];case 1:if(e.sent(),null!=p)for(o=function(a){return null==s.totals[a]?"continue":void("number"==typeof s.totals[a]?p[a]=s.totals[a]/s.seen:tidy(function(){p[a]=mul(div(getScalar(1),getScalar(t.seen)),t.totals[a]),t.totals[a].dispose(),keep(p[a])}))},s=this,l=0,d=this.params.metrics;l= 0, but got "+e),a.checkForDuplicate(t),null==a.constructors[e]&&(a.constructors[e]=[]),a.constructors[e].push(t)},a.checkForDuplicate=function(r){for(var e in a.constructors)a.constructors[+e].forEach(function(t){if(t===r)throw new ValueError("Duplicate callback constructor.")})},a.clear=function(){a.constructors={}},a.createCallbacks=function(e){var t=[];for(var n in a.constructors){var r=+n;e>=r&&t.push.apply(t,a.constructors[r])}return t.map(function(t){return new t})},a.constructors={},a}(),mse$1=meanSquaredError$1,MSE$1=meanSquaredError$1,mae$1=meanAbsoluteError,MAE$1=meanAbsoluteError,mape$1=meanAbsolutePercentageError,MAPE$1=meanAbsolutePercentageError,categoricalCrossentropy$1=categoricalCrossentropy,cosine$1=cosineProximity,sparseCategoricalCrossentropy$1=sparseCategoricalCrossentropy,version$1="0.8.5",Container=function(ae){function x(e){var t=ae.call(this,{})||this;if(t.containerNodes=new Set,t.name=e.name,null==t.name){var n=t.getClassName().toLowerCase();t.name=getUid(n)}if(t.supportsMasking=!1,t.trainable=!0,t.updatable=!0,t.inputs=Array.isArray(e.inputs)?e.inputs.slice():[e.inputs],t.outputs=Array.isArray(e.outputs)?e.outputs.slice():[e.outputs],unique(t.inputs).length!==t.inputs.length)throw new ValueError("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+t.inputs.map(function(t){return t.name}));unique(t.outputs).length!==t.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+t.outputs.map(function(t){return t.name})),t.inputLayers=[],t.inputLayersNodeIndices=[],t.inputLayersTensorIndices=[],t.outputLayers=[],t.outputLayersNodeIndices=[],t.outputLayersTensorIndices=[],t.layers=[];for(var r=0,i=t.outputs;r1 nodes"),assert$1(0===se,"input layer has >1 tensors"),t.inputLayers.push(o),t.inputLayersNodeIndices.push(oe),t.inputLayersTensorIndices.push(se);t.inputNames=[],t.outputNames=[],t.feedInputShapes=[],t.feedInputNames=[],t.feedOutputNames=[];for(var p=0;pn?1:0});for(var xe=0,Ne=B;xet}))throw new ValueError("Negative dimension size caused by adding layer "+t.name+" with input shape ["+t.inboundNodes[0].inputTensors[0].shape+"]")},p.prototype.add=function(t){var e=t instanceof p||t instanceof Model,r;if(e){if(1!==(r=t).outputs.length)throw new ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==r.inputs.length)throw new ValueError("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===t.inboundNodes.length){if(null==t.batchInputShape)throw new ValueError("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");var o=Input({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(o)}if(e)this.outputs=r.outputs,this.inputs=r.inputs;else{if(1!==t.inboundNodes.length)throw new ValueError("A layer added to a Sequential model must not already be connected somewhere else. Model received layer "+t.name+" which has "+t.inboundNodes.length+" pre-existing inbound connections.");if(1!==t.inboundNodes[0].outputTensors.length)throw new ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=getSourceInputs(this.outputs[0])}this.inboundNodes=[],new Node({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:pyListRepeat(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(function(t){return t.shape}),outputShapes:this.outputs[0].shape})}else{var s=t.apply(this.outputs[0]);if(Array.isArray(s))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),this.built=!1},p.prototype.pop=function(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{var t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}},p.prototype.call=function(a,e){return null==this.model&&this.build(),this.model.call(a,e)},p.prototype.build=function(t){if(getExactlyOneShape(t),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Model({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.model.updatable=this.updatable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0},p.prototype.countParams=function(){return this.built||this.build(),o.prototype.countParams.call(this)},p.prototype.summary=function(e,t,a){void 0===a&&(a=console.log),this.built||this.build(),o.prototype.summary.call(this,e,t,a)},p.prototype.setWeights=function(t){null==this.model&&this.build(),this.model.setWeights(t)},Object.defineProperty(p.prototype,"updatable",{get:function(){return this._updatable},set:function(t){this.built&&(this.model.updatable=t),this._updatable=t},enumerable:!0,configurable:!0}),p.prototype.evaluate=function(a,e,t){if(void 0===t&&(t={}),!this.built)throw new RuntimeError("The model needs to be compiled before being used.");return this.model.evaluate(a,e,t)},p.prototype.evaluateDataset=function(a,e){return __awaiter$1(this,void 0,void 0,function(){return __generator$1(this,function(){if(!this.built)throw new RuntimeError("The model needs to be compiled before being used.");return[2,this.model.evaluateDataset(a,e)]})})},p.prototype.predict=function(a,e){return void 0===e&&(e={}),null==this.model&&this.build(),this.model.predict(a,e)},p.prototype.predictOnBatch=function(t){return null==this.model&&this.build(),this.model.predictOnBatch(t)},p.prototype.compile=function(t){this.build(),this.model.compile(t),this.optimizer=this.model.optimizer,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames},p.prototype.fit=function(a,e,t){return void 0===t&&(t={}),__awaiter$1(this,void 0,void 0,function(){return __generator$1(this,function(){if(!this.built)throw new RuntimeError("The model needs to be compiled before being used.");return[2,this.model.fit(a,e,t)]})})},p.prototype.fitDataset=function(a,e){return __awaiter$1(this,void 0,void 0,function(){return __generator$1(this,function(){if(!this.built)throw new RuntimeError("The model needs to be compiled before being used.");return[2,this.model.fitDataset(a,e)]})})},p.fromConfig=function(t,e){var n={},d;if(e instanceof Array){if(null==e[0].className||"Merge"===e[0].className)throw new ValueError("Legacy serialization format not supported yet.");d=e}else util.assert(null!=e.layers,"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),d=e.layers,delete e.layers,n=e;var u=new t(n);if(!(u instanceof p))throw new NotImplementedError("Sequential.fromConfig called on non-Sequential input: "+u);for(var a=0,c=d,s;at.filters)throw new ValueError("Convolution layer expected config.filters to be a 'number' > 0 but got "+JSON.stringify(t.filters))},e}(BaseConv),Conv2D=function(a){function e(t){var n=a.call(this,2,t)||this;return e.verifyConfig(t),n}return __extends$1(e,a),e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this);return delete e.rank,e},e.verifyConfig=function(t){if("number"!=typeof t.kernelSize&&!checkArrayTypeAndLength(t.kernelSize,"number",1,2))throw new ValueError("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv2D",e}(Conv);serialization.registerClass(Conv2D);var Conv2DTranspose=function(a){function e(e){var t=a.call(this,e)||this;if(t.inputSpec=[new InputSpec({ndim:4})],"same"!==t.padding&&"valid"!==t.padding)throw new ValueError("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+t.padding);return t}return __extends$1(e,a),e.prototype.build=function(a){if(4!==(a=getExactlyOneShape(a)).length)throw new ValueError("Input should have rank 4; Received input shape: "+JSON.stringify(a));var o="channelsFirst"===this.dataFormat?1:a.length-1;if(null==a[o])throw new ValueError("The channel dimension of the inputs should be defined. Found `None`.");var t=a[o],r=this.kernelSize.concat([this.filters,t]),s;this.kernel=this.addWeight("kernel",r,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new InputSpec({ndim:4,axes:(s={},s[o]=t,s)})],this.built=!0},e.prototype.call=function(m){var e=this;return tidy(function(){var n=getExactlyOneTensor(m);if(4!==n.shape.length)throw new ValueError("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+n.shape.length);var g=n.shape,a=g[0],o,y;"channelsFirst"===e.dataFormat?(o=2,y=3):(o=1,y=2);var b=g[o],s=g[y],l=e.kernelSize[0],u=e.kernelSize[1],c=e.strides[0],p=e.strides[1],h=[a,deconvLength(b,c,l,e.padding),deconvLength(s,p,u,e.padding),e.filters];"channelsLast"!==e.dataFormat&&(n=transpose(n,[0,2,3,1]));var d=conv2dTranspose(n,e.kernel.read(),h,e.strides,e.padding);return"channelsLast"!==e.dataFormat&&(d=transpose(d,[0,3,1,2])),null!=e.bias&&(d=biasAdd(d,e.bias.read(),e.dataFormat)),null!=e.activation&&(d=e.activation.apply(d)),d})},e.prototype.computeOutputShape=function(p){var d=(p=getExactlyOneShape(p)).slice(),i,u,c;"channelsFirst"===this.dataFormat?(i=1,u=2,c=3):(i=3,u=1,c=2);var m=this.kernelSize[0],a=this.kernelSize[1],o=this.strides[0],s=this.strides[1];return d[i]=this.filters,d[u]=deconvLength(d[u],o,m,this.padding),d[c]=deconvLength(d[c],s,a,this.padding),d},e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this);return delete e.dilationRate,e},e.className="Conv2DTranspose",e}(Conv2D);serialization.registerClass(Conv2DTranspose);var SeparableConv=function(a){function e(e,t){var n=a.call(this,e,t)||this;if(n.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",n.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",n.depthwiseKernel=null,n.pointwiseKernel=null,null==t.filters)throw new ValueError("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new ValueError("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new ValueError("SeparableConv"+n.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(t.padding));return n.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,n.depthwiseInitializer=getInitializer(t.depthwiseInitializer||n.DEFAULT_DEPTHWISE_INITIALIZER),n.depthwiseRegularizer=getRegularizer(t.depthwiseRegularizer),n.depthwiseConstraint=getConstraint(t.depthwiseConstraint),n.pointwiseInitializer=getInitializer(t.depthwiseInitializer||n.DEFAULT_POINTWISE_INITIALIZER),n.pointwiseRegularizer=getRegularizer(t.pointwiseRegularizer),n.pointwiseConstraint=getConstraint(t.pointwiseConstraint),n}return __extends$1(e,a),e.prototype.build=function(s){if((s=getExactlyOneShape(s)).lengths[p])throw new ValueError("The channel dimension of the inputs should be defined, but found "+JSON.stringify(s[p]));for(var t=s[p],n=this.kernelSize.concat([t,this.depthMultiplier]),r=[],i=0;i(a=getExactlyOneShape(a)).length)throw new ValueError("Inputs to DepthwiseConv2D should have rank 4. Received input shape: "+JSON.stringify(a)+".");var o="channelsFirst"===this.dataFormat?1:3;if(null==a[o]||0>a[o])throw new ValueError("The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not ("+a[o]+").");var t=a[o],n=[this.kernelSize[0],this.kernelSize[1],t,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",n,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.bias=this.useBias?this.addWeight("bias",[t*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):null,this.built=!0},e.prototype.call=function(a){var r=this;return tidy(function(){var e=depthwiseConv2d$1(a=getExactlyOneTensor(a),r.depthwiseKernel.read(),r.strides,r.padding,r.dataFormat,null);return r.useBias&&(e=biasAdd(e,r.bias.read(),r.dataFormat)),null!=r.activation&&(e=r.activation.apply(e)),e})},e.prototype.computeOutputShape=function(o){o=getExactlyOneShape(o);var s="channelsFirst"===this.dataFormat?o[2]:o[1],t="channelsFirst"===this.dataFormat?o[3]:o[2],n="channelsFirst"===this.dataFormat?o[1]*this.depthMultiplier:o[3]*this.depthMultiplier,r=convOutputLength(s,this.kernelSize[0],this.padding,this.strides[0]),i=convOutputLength(t,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[o[0],n,r,i]:[o[0],r,i,n]},e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this);return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=serializeInitializer(this.depthwiseInitializer),e.depthwiseRegularizer=serializeRegularizer(this.depthwiseRegularizer),e.depthwiseConstraint=serializeConstraint(this.depthwiseRegularizer),e},e.className="DepthwiseConv2D",e}(BaseConv);serialization.registerClass(DepthwiseConv2D);var Dropout=function(a){function e(e){var t=a.call(this,e)||this;if(t.rate=_Mathmax(_Mathmin(e.rate,1),0),t.rateScalar=getScalar(t.rate),t.noiseShape=e.noiseShape,t.seed=e.seed,null!=t.seed)throw new NotImplementedError("Non-default seed is not implemented in Dropout layer yet: "+t.seed);return t.supportsMasking=!0,t}return __extends$1(e,a),e.prototype.getNoiseShape=function(a){if(null==this.noiseShape)return this.noiseShape;for(var e=a.shape,t=[],n=0;nt.rate){var r=null!=e.training&&e.training,s=t.getNoiseShape(n);return inTrainPhase(function(){return dropout(n,t.rateScalar,s,t.seed)},function(){return n},r)}return o})},e.prototype.getConfig=function(){var e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Dropout",e}(Layer);serialization.registerClass(Dropout);var Dense=function(a){function e(e){var t=a.call(this,e)||this;if(t.activation=null,t.useBias=!0,t.kernel=null,t.bias=null,t.DEFAULT_KERNEL_INITIALIZER="glorotNormal",t.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){var n=null;null!=e.batchSize&&(n=e.batchSize),t.batchInputShape=[n,e.inputDim]}return t.units=e.units,t.activation=getActivation(e.activation),null!=e.useBias&&(t.useBias=e.useBias),t.kernelInitializer=getInitializer(e.kernelInitializer||t.DEFAULT_KERNEL_INITIALIZER),t.biasInitializer=getInitializer(e.biasInitializer||t.DEFAULT_BIAS_INITIALIZER),t.kernelConstraint=getConstraint(e.kernelConstraint),t.biasConstraint=getConstraint(e.biasConstraint),t.kernelRegularizer=getRegularizer(e.kernelRegularizer),t.biasRegularizer=getRegularizer(e.biasRegularizer),t.activityRegularizer=getRegularizer(e.activityRegularizer),t.inputSpec=[{minNDim:2}],t}return __extends$1(e,a),e.prototype.build=function(a){var r=(a=getExactlyOneShape(a))[a.length-1],n;null==this.kernel&&(this.kernel=this.addWeight("kernel",[r,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:(n={},n[-1]=r,n)}],this.built=!0},e.prototype.computeOutputShape=function(a){var n=(a=getExactlyOneShape(a)).slice();return n[n.length-1]=this.units,n},e.prototype.call=function(a,e){var t=this;return tidy(function(){t.invokeCallHook(a,e);var n=dot$1(getExactlyOneTensor(a),t.kernel.read());return null!=t.bias&&(n=biasAdd(n,t.bias.read())),null!=t.activation&&(n=t.activation.apply(n)),n})},e.prototype.getConfig=function(){var e={units:this.units,activation:serializeActivation(this.activation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),biasConstraint:serializeConstraint(this.biasConstraint)},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Dense",e}(Layer);serialization.registerClass(Dense);var Flatten=function(a){function e(e){var t=a.call(this,e||{})||this;return t.inputSpec=[{minNDim:3}],t}return __extends$1(e,a),e.prototype.computeOutputShape=function(a){for(var r=0,o=(a=getExactlyOneShape(a)).slice(1);rt||null==t},e.prototype.fixUnknownDimension=function(p,e){for(var t="Total size of new array must be unchanged.",n=e.slice(),r=1,d=null,u=0,c;us||0>i)t.push(null);else if(1===s)t.push(i);else if(1===i)t.push(s);else{if(s!==i)throw new ValueError("Operands could not be broadcast together with shapes "+JSON.stringify(o)+" "+JSON.stringify(e));t.push(s)}}return t},e.prototype.build=function(p){if(Array.isArray(p)&&!Array.isArray(p[0])&&(p=[getExactlyOneShape(p)]),2>(p=p).length)throw new ValueError("A merge layer should be called on an Array of at least 2 inputs. Got "+p.length+" input(s).");for(var l=[],d=0,u=p;dthis.axis?t.length+this.axis:this.axis,r=0,p=e.slice(1),a;rt.dropout&&null==t.dropoutMask&&(t.dropoutMask=generateDropoutMask(function(){return onesLike(p)},t.dropout,n)),0t.recurrentDropout&&null==t.recurrentDropoutMask&&(t.recurrentDropoutMask=generateDropoutMask(function(){return onesLike(e)},t.recurrentDropout,n));var u=t.dropoutMask,o=t.recurrentDropoutMask;a=dot$1(null==u?p:mul(p,u),t.kernel.read()),null!=t.bias&&(a=biasAdd(a,t.bias.read())),null!=o&&(e=mul(e,o));var s=add(a,dot$1(e,t.recurrentKernel.read()));return null!=t.activation&&(s=t.activation.apply(s)),[s,s]})},e.prototype.getConfig=function(){var e={units:this.units,activation:serializeActivation(this.activation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="SimpleRNNCell",e}(RNNCell);serialization.registerClass(SimpleRNNCell);var SimpleRNN=function(s){function e(e){return e.cell=new SimpleRNNCell(e),s.call(this,e)||this}return __extends$1(e,s),e.prototype.call=function(e,t){var n=this;return tidy(function(){null!=n.cell.dropoutMask&&(dispose(n.cell.dropoutMask),n.cell.dropoutMask=null),null!=n.cell.recurrentDropoutMask&&(dispose(n.cell.recurrentDropoutMask),n.cell.recurrentDropoutMask=null);var r=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return s.prototype.call.call(n,e,{mask:r,training:i,initialState:a})})},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:serializeActivation(this.activation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},t=s.prototype.getConfig.call(this);return delete t.cell,Object.assign(e,t),e},e.className="SimpleRNN",e}(RNN);serialization.registerClass(SimpleRNN);var GRUCell=function(a){function e(e){var t=a.call(this,e)||this;return t.DEFAULT_ACTIVATION="tanh",t.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",t.DEFAULT_KERNEL_INITIALIZER="glorotNormal",t.DEFAULT_RECURRENT_INITIALIZER="orthogonal",t.DEFAULT_BIAS_INITIALIZER="zeros",t.units=e.units,t.activation=getActivation(void 0===e.activation?t.DEFAULT_ACTIVATION:e.activation),t.recurrentActivation=getActivation(void 0===e.recurrentActivation?t.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),t.useBias=null==e.useBias||e.useBias,t.kernelInitializer=getInitializer(e.kernelInitializer||t.DEFAULT_KERNEL_INITIALIZER),t.recurrentInitializer=getInitializer(e.recurrentInitializer||t.DEFAULT_RECURRENT_INITIALIZER),t.biasInitializer=getInitializer(e.biasInitializer||t.DEFAULT_BIAS_INITIALIZER),t.kernelRegularizer=getRegularizer(e.kernelRegularizer),t.recurrentRegularizer=getRegularizer(e.recurrentRegularizer),t.biasRegularizer=getRegularizer(e.biasRegularizer),t.kernelConstraint=getConstraint(e.kernelConstraint),t.recurrentConstraint=getConstraint(e.recurrentConstraint),t.biasConstraint=getConstraint(e.biasConstraint),t.dropout=min$1([1,max$1([0,null==e.dropout?0:e.dropout])]),t.recurrentDropout=min$1([1,max$1([0,null==e.recurrentDropout?0:e.recurrentDropout])]),t.implementation=e.implementation,t.stateSize=t.units,t.dropoutMask=null,t.recurrentDropoutMask=null,t}return __extends$1(e,a),e.prototype.build=function(a){var n=(a=getExactlyOneShape(a))[a.length-1];this.kernel=this.addWeight("kernel",[n,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.bias=this.useBias?this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):null,this.built=!0},e.prototype.call=function(x,C){var t=this;return tidy(function(){if(2!==(x=x).length)throw new ValueError("GRUCell expects 2 input Tensors (inputs, h, c), got "+x.length+".");var e=null!=C.training&&C.training,n=x[1];x=x[0],0t.dropout&&null==t.dropoutMask&&(t.dropoutMask=generateDropoutMask(function(){return onesLike(x)},t.dropout,e,3)),0t.recurrentDropout&&null==t.recurrentDropoutMask&&(t.recurrentDropoutMask=generateDropoutMask(function(){return onesLike(n)},t.recurrentDropout,e,3));var r=t.dropoutMask,l=t.recurrentDropoutMask,u,k,T;0t.dropout&&(x=mul(x,r[0]));var E=dot$1(x,t.kernel.read());t.useBias&&(E=biasAdd(E,t.bias.read())),0t.recurrentDropout&&(n=mul(n,l[0]));var R=t.recurrentKernel.read(),p=split$1(R,[2*t.units,t.units],R.rank-1),h=p[0],d=p[1],f=dot$1(n,h),g=split$1(E,3,E.rank-1),m=g[0],y=g[1],v=g[2],b=split$1(f,2,f.rank-1),D=b[0],w=b[1];u=t.recurrentActivation.apply(add(m,D)),k=t.recurrentActivation.apply(add(y,w));var S=dot$1(mul(k,n),d);T=t.activation.apply(add(v,S));var I=add(mul(u,n),mul(add(getScalar(1),neg(u)),T));return[I,I]})},e.prototype.getConfig=function(){var e={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="GRUCell",e}(RNNCell);serialization.registerClass(GRUCell);var GRU=function(s){function e(e){return 0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new GRUCell(e),s.call(this,e)||this}return __extends$1(e,s),e.prototype.call=function(e,t){var n=this;return tidy(function(){null!=n.cell.dropoutMask&&(dispose(n.cell.dropoutMask),n.cell.dropoutMask=null),null!=n.cell.recurrentDropoutMask&&(dispose(n.cell.recurrentDropoutMask),n.cell.recurrentDropoutMask=null);var r=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return s.prototype.call.call(n,e,{mask:r,training:i,initialState:a})})},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=s.prototype.getConfig.call(this);return delete t.cell,Object.assign(e,t),e},e.fromConfig=function(a,e){return 0===e.implmentation&&(e.implementation=1),new a(e)},e.className="GRU",e}(RNN);serialization.registerClass(GRU);var LSTMCell=function(a){function e(e){var t=a.call(this,e)||this;return t.DEFAULT_ACTIVATION="tanh",t.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",t.DEFAULT_KERNEL_INITIALIZER="glorotNormal",t.DEFAULT_RECURRENT_INITIALIZER="orthogonal",t.DEFAULT_BIAS_INITIALIZER="zeros",t.units=e.units,t.activation=getActivation(void 0===e.activation?t.DEFAULT_ACTIVATION:e.activation),t.recurrentActivation=getActivation(void 0===e.recurrentActivation?t.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),t.useBias=null==e.useBias||e.useBias,t.kernelInitializer=getInitializer(e.kernelInitializer||t.DEFAULT_KERNEL_INITIALIZER),t.recurrentInitializer=getInitializer(e.recurrentInitializer||t.DEFAULT_RECURRENT_INITIALIZER),t.biasInitializer=getInitializer(e.biasInitializer||t.DEFAULT_BIAS_INITIALIZER),t.unitForgetBias=e.unitForgetBias,t.kernelRegularizer=getRegularizer(e.kernelRegularizer),t.recurrentRegularizer=getRegularizer(e.recurrentRegularizer),t.biasRegularizer=getRegularizer(e.biasRegularizer),t.kernelConstraint=getConstraint(e.kernelConstraint),t.recurrentConstraint=getConstraint(e.recurrentConstraint),t.biasConstraint=getConstraint(e.biasConstraint),t.dropout=min$1([1,max$1([0,null==e.dropout?0:e.dropout])]),t.recurrentDropout=min$1([1,max$1([0,null==e.recurrentDropout?0:e.recurrentDropout])]),t.implementation=e.implementation,t.stateSize=[t.units,t.units],t.dropoutMask=null,t.recurrentDropoutMask=null,t}return __extends$1(e,a),e.prototype.build=function(o){var s=(o=getExactlyOneShape(o))[o.length-1],r,p;if(this.kernel=this.addWeight("kernel",[s,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){var l=this.biasInitializer,i=this.units;r=new((p=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return __extends$1(e,a),e.prototype.apply=function(){var e=l.apply([i]),t=new Ones().apply([i]),a=l.apply([2*i]);return concatAlongFirstAxis(concatAlongFirstAxis(e,t),a)},e}(Initializer)).className="CustomInit",p)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0},e.prototype.call=function(b,x){var t=this;return tidy(function(){var e=null!=x.training&&x.training;if(3!==(b=b).length)throw new ValueError("LSTMCell expects 3 input Tensors (inputs, h, c), got "+b.length+".");var n=b[1],r=b[2];b=b[0],0t.dropout&&null==t.dropoutMask&&(t.dropoutMask=generateDropoutMask(function(){return onesLike(b)},t.dropout,e,4)),0t.recurrentDropout&&null==t.recurrentDropoutMask&&(t.recurrentDropoutMask=generateDropoutMask(function(){return onesLike(n)},t.recurrentDropout,e,4));var a=t.dropoutMask,c=t.recurrentDropoutMask,p,N,I,S;0t.dropout&&(b=mul(b,a[0]));var C=dot$1(b,t.kernel.read());0t.recurrentDropout&&(n=mul(n,c[0])),C=add(C,dot$1(n,t.recurrentKernel.read())),t.useBias&&(C=biasAdd(C,t.bias.read()));var k=split$1(C,4,C.rank-1),d=k[0],f=k[1],g=k[2],m=k[3];p=t.recurrentActivation.apply(d),N=t.recurrentActivation.apply(f),I=add(mul(N,r),mul(p,t.activation.apply(g))),S=t.recurrentActivation.apply(m);var y=mul(S,t.activation.apply(I));return[y,y,I]})},e.prototype.getConfig=function(){var e={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="LSTMCell",e}(RNNCell);serialization.registerClass(LSTMCell);var LSTM=function(s){function e(e){return 0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new LSTMCell(e),s.call(this,e)||this}return __extends$1(e,s),e.prototype.call=function(e,t){var n=this;return tidy(function(){null!=n.cell.dropoutMask&&(dispose(n.cell.dropoutMask),n.cell.dropoutMask=null),null!=n.cell.recurrentDropoutMask&&(dispose(n.cell.recurrentDropoutMask),n.cell.recurrentDropoutMask=null);var r=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return s.prototype.call.call(n,e,{mask:r,training:i,initialState:a})})},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"unitForgetBias",{get:function(){return this.cell.unitForgetBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:serializeActivation(this.activation),recurrentActivation:serializeActivation(this.recurrentActivation),useBias:this.useBias,kernelInitializer:serializeInitializer(this.kernelInitializer),recurrentInitializer:serializeInitializer(this.recurrentInitializer),biasInitializer:serializeInitializer(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:serializeRegularizer(this.kernelRegularizer),recurrentRegularizer:serializeRegularizer(this.recurrentRegularizer),biasRegularizer:serializeRegularizer(this.biasRegularizer),activityRegularizer:serializeRegularizer(this.activityRegularizer),kernelConstraint:serializeConstraint(this.kernelConstraint),recurrentConstraint:serializeConstraint(this.recurrentConstraint),biasConstraint:serializeConstraint(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=s.prototype.getConfig.call(this);return delete t.cell,Object.assign(e,t),e},e.fromConfig=function(a,e){return 0===e.implmentation&&(e.implementation=1),new a(e)},e.className="LSTM",e}(RNN);serialization.registerClass(LSTM);var StackedRNNCells=function(s){function e(e){var t=s.call(this,e)||this;return t.cells=e.cells,t}return __extends$1(e,s),Object.defineProperty(e.prototype,"stateSize",{get:function(){for(var a=[],e=0,o=this.cells.slice().reverse(),n;e(e=getExactlyOneShape(e)).length)throw new ValueError("TimeDistributed layer expects an input shape >= 3D, but received input shape "+JSON.stringify(e));this.inputSpec=[{shape:e}];var r=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(r),this.layer.built=!0),a.prototype.build.call(this,e)},e.prototype.computeOutputShape=function(a){var o=[(a=getExactlyOneShape(a))[0]].concat(a.slice(2)),t=this.layer.computeOutputShape(o),n=a[1];return[t[0],n].concat(t.slice(1))},e.prototype.call=function(a,r){var t=this;return tidy(function(){return rnn(function(a){return[getExactlyOneTensor(t.layer.call(a,r)),[]]},a=getExactlyOneTensor(a),[],!1,null,null,!1,!0)[1]})},e.className="TimeDistributed",e}(Wrapper);serialization.registerClass(TimeDistributed);var VALID_BIDIRECTIONAL_MERGE_MODES=["sum","mul","concat","ave"],Bidirectional=function(y){function e(e){var t=y.call(this,e)||this,a=e.layer.getConfig();if(t.forwardLayer=deserialize({className:e.layer.getClassName(),config:a}),a.goBackwards=!0!==a.goBackwards,t.backwardLayer=deserialize({className:e.layer.getClassName(),config:a}),t.forwardLayer.name="forward_"+t.forwardLayer.name,t.backwardLayer.name="backward_"+t.backwardLayer.name,checkBidirectionalMergeMode(e.mergeMode),t.mergeMode=e.mergeMode,e.weights)throw new NotImplementedError("weights support is not implemented for Bidirectional layer yet.");return t._stateful=e.layer.stateful,t.returnSequences=e.layer.returnSequences,t.returnState=e.layer.returnState,t.supportsMasking=!0,t._trainable=!0,t.inputSpec=e.layer.inputSpec,t.numConstants=null,t}return __extends$1(e,y),Object.defineProperty(e.prototype,"trainable",{get:function(){return this._trainable},set:function(t){this._trainable=t,null!=this.forwardLayer&&(this.forwardLayer.trainable=t),null!=this.backwardLayer&&(this.backwardLayer.trainable=t)},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},e.prototype.setWeights=function(a){var e=a.length,t=_Mathfloor(e/2);this.forwardLayer.setWeights(a.slice(0,t)),this.backwardLayer.setWeights(a.slice(t))},e.prototype.computeOutputShape=function(a){var e=this.forwardLayer.computeOutputShape(a),o,s,p;return Array.isArray(e)&&Array.isArray(e[0])||(e=[e]),e=e,this.returnState?(p=e.slice(1),o=e[0]):o=e[0],o=o,"concat"===this.mergeMode?(o[o.length-1]*=2,s=[o]):s=null==this.mergeMode?[o,o.slice()]:[o],this.returnState?null==this.mergeMode?s.concat(p).concat(p.slice()):[o].concat(p).concat(p.slice()):singletonOrArray(s)},e.prototype.apply=function(e,b){var x=null==b?null:b.initialState,N=null==b?null:b.constants;null==b&&(b={});var I=standardizeArgs(e,x,N,this.numConstants);if(e=I.inputs,x=I.initialState,N=I.constants,Array.isArray(e)&&(x=e.slice(1),e=e[0]),(null==x||0===x.length)&&null==N)return y.prototype.apply.call(this,e,b);var a=[],o=[];if(null!=x){var s=x.length;if(0a;)i[l[a]=26>a?a+65:52>a?a+71:62>a?a-4:43|a-59]=a++;t.encode=function(r,e,d){for(var a=null,u=[],s=0,c=0,h,g;e>2],h=(3&g)<<4,c=1):1==c?(u[s++]=l[h|g>>4],h=(15&g)<<2,c=2):2==c?(u[s++]=l[h|g>>6],u[s++]=l[63&g],c=0):void 0,8191>4,u=c,o=2):2==o?(e[t++]=(15&u)<<4|(60&c)>>2,u=c,o=3):3==o?(e[t++]=(3&u)<<6|c,o=0):void 0}if(1==o)throw Error("invalid encoding");return t-l},t.test=function(t){return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}}),eventemitter=EventEmitter;EventEmitter.prototype.on=function(n,e,t){return(this._listeners[n]||(this._listeners[n]=[])).push({fn:e,ctx:t||this}),this},EventEmitter.prototype.off=function(n,e){if(void 0===n)this._listeners={};else if(void 0===e)this._listeners[n]=[];else for(var t=this._listeners[n],a=0;a(o=n.charCodeAt(s))?e+=1:2048>o?e+=2:55296==(64512&o)&&56320==(64512&n.charCodeAt(s+1))?(++s,e+=4):e+=3;return e},t.read=function(i,e,p){if(1>p-e)return"";for(var a=null,l=[],o=0,d;e(d=i[e++])?l[o++]=d:191d?l[o++]=(31&d)<<6|63&i[e++]:239d?(d=((7&d)<<18|(63&i[e++])<<12|(63&i[e++])<<6|63&i[e++])-65536,l[o++]=55296+(d>>10),l[o++]=56320+(1023&d)):l[o++]=(15&d)<<12|(63&i[e++])<<6|63&i[e++],8191(l=i.charCodeAt(o))?e[t++]=l:2048>l?(e[t++]=192|l>>6,e[t++]=128|63&l):55296==(64512&l)&&56320==(64512&(d=i.charCodeAt(o+1)))?(l=65536+((1023&l)<<10)+(1023&d),++o,e[t++]=240|l>>18,e[t++]=128|63&l>>12,e[t++]=128|63&l>>6,e[t++]=128|63&l):(e[t++]=224|l>>12,e[t++]=128|63&l>>6,e[t++]=128|63&l);return t-p}}),pool_1=pool$1,longbits=LongBits,zero=LongBits.zero=new LongBits(0,0);zero.toNumber=function(){return 0},zero.zzEncode=zero.zzDecode=function(){return this},zero.length=function(){return 1};var zeroHash=LongBits.zeroHash="\0\0\0\0\0\0\0\0";LongBits.fromNumber=function(n){if(0===n)return zero;var o=0>n;o&&(n=-n);var t=n>>>0,s=(n-t)/4294967296>>>0;return o&&(s=~s>>>0,t=~t>>>0,4294967295<++t&&(t=0,4294967295<++s&&(s=0))),new LongBits(t,s)},LongBits.from=function(t){if("number"==typeof t)return LongBits.fromNumber(t);if(minimal.isString(t)){if(!minimal.Long)return LongBits.fromNumber(parseInt(t,10));t=minimal.Long.fromString(t)}return t.low||t.high?new LongBits(t.low>>>0,t.high>>>0):zero},LongBits.prototype.toNumber=function(n){if(!n&&this.hi>>>31){var e=1+~this.lo>>>0,t=~this.hi>>>0;return e||(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi},LongBits.prototype.toLong=function(t){return minimal.Long?new minimal.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}};var charCodeAt=String.prototype.charCodeAt;LongBits.fromHash=function(t){return t===zeroHash?zero:new LongBits((charCodeAt.call(t,0)|charCodeAt.call(t,1)<<8|charCodeAt.call(t,2)<<16|charCodeAt.call(t,3)<<24)>>>0,(charCodeAt.call(t,4)|charCodeAt.call(t,5)<<8|charCodeAt.call(t,6)<<16|charCodeAt.call(t,7)<<24)>>>0)},LongBits.prototype.toHash=function(){return _StringfromCharCode(255&this.lo,255&this.lo>>>8,255&this.lo>>>16,this.lo>>>24,255&this.hi,255&this.hi>>>8,255&this.hi>>>16,this.hi>>>24)},LongBits.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},LongBits.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},LongBits.prototype.length=function(){var n=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,t=this.hi>>>24;return 0==t?0==e?16384>n?128>n?1:2:2097152>n?3:4:16384>e?128>e?5:6:2097152>e?7:8:128>t?9:10};var minimal=createCommonjsModule$1(function(o,e){function s(o,e,t){for(var a=Object.keys(e),r=0;r(t>>>=0)?1:16384>t?2:2097152>t?3:268435456>t?4:5,t)).len,this},Writer.prototype.int32=function(t){return 0>t?this._push(writeVarint64,10,LongBits$1.fromNumber(t)):this.uint32(t)},Writer.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},Writer.prototype.uint64=function(a){var e=LongBits$1.from(a);return this._push(writeVarint64,e.length(),e)},Writer.prototype.int64=Writer.prototype.uint64,Writer.prototype.sint64=function(a){var e=LongBits$1.from(a).zzEncode();return this._push(writeVarint64,e.length(),e)},Writer.prototype.bool=function(t){return this._push(writeByte,1,t?1:0)},Writer.prototype.fixed32=function(t){return this._push(writeFixed32,4,t>>>0)},Writer.prototype.sfixed32=Writer.prototype.fixed32,Writer.prototype.fixed64=function(a){var e=LongBits$1.from(a);return this._push(writeFixed32,4,e.lo)._push(writeFixed32,4,e.hi)},Writer.prototype.sfixed64=Writer.prototype.fixed64,Writer.prototype.float=function(t){return this._push(minimal.float.writeFloatLE,4,t)},Writer.prototype.double=function(t){return this._push(minimal.float.writeDoubleLE,8,t)};var writeBytes=minimal.Array.prototype.set?function(n,e,t){e.set(n,t)}:function(n,e,t){for(var a=0;a>>0;if(!r)return this._push(writeByte,1,0);if(minimal.isString(n)){var o=Writer.alloc(r=base64.length(n));base64.decode(n,o,0),n=o}return this.uint32(r)._push(writeBytes,r,n)},Writer.prototype.string=function(a){var e=utf8.length(a);return e?this.uint32(e)._push(utf8.write,e,a):this._push(writeByte,1,0)},Writer.prototype.fork=function(){return this.states=new State(this),this.head=this.tail=new Op(noop,0,0),this.len=0,this},Writer.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new Op(noop,0,0),this.len=0),this},Writer.prototype.ldelim=function(){var n=this.head,e=this.tail,t=this.len;return this.reset().uint32(t),t&&(this.tail.next=n.next,this.tail=e,this.len+=t),this},Writer.prototype.finish=function(){for(var n=this.head.next,r=this.constructor.alloc(this.len),t=0;n;)n.fn(n.val,r,t),t+=n.len,n=n.next;return r},Writer._configure=function(t){BufferWriter=t};var writer_buffer=BufferWriter$1;(BufferWriter$1.prototype=Object.create(writer.prototype)).constructor=BufferWriter$1;var Buffer$1=minimal.Buffer;BufferWriter$1.alloc=function(t){return(BufferWriter$1.alloc=minimal._Buffer_allocUnsafe)(t)};var writeBytesBuffer=Buffer$1&&Buffer$1.prototype instanceof Uint8Array&&"set"===Buffer$1.prototype.set.name?function(n,e,t){e.set(n,t)}:function(n,e,t){if(n.copy)n.copy(e,t,0,n.length);else for(var o=0;o>>0;return this.uint32(n),n&&this._push(writeBytesBuffer,n,a),this},BufferWriter$1.prototype.string=function(a){var e=Buffer$1.byteLength(a);return this.uint32(e),e&&this._push(writeStringBuffer,e,a),this};var reader=Reader,LongBits$2=minimal.LongBits,utf8$1=minimal.utf8,create_array="undefined"==typeof Uint8Array?function(t){if(Array.isArray(t))return new Reader(t);throw Error("illegal buffer")}:function(t){if(t instanceof Uint8Array||Array.isArray(t))return new Reader(t);throw Error("illegal buffer")},BufferReader;Reader.create=minimal.Buffer?function(t){return(Reader.create=function(t){return minimal.Buffer.isBuffer(t)?new BufferReader(t):create_array(t)})(t)}:create_array,Reader.prototype._slice=minimal.Array.prototype.subarray||minimal.Array.prototype.slice,Reader.prototype.uint32=function(){var t=4294967295;return function(){if(t=(127&this.buf[this.pos])>>>0,128>this.buf[this.pos++])return t;if(t=(t|(127&this.buf[this.pos])<<7)>>>0,128>this.buf[this.pos++])return t;if(t=(t|(127&this.buf[this.pos])<<14)>>>0,128>this.buf[this.pos++])return t;if(t=(t|(127&this.buf[this.pos])<<21)>>>0,128>this.buf[this.pos++])return t;if(t=(t|(15&this.buf[this.pos])<<28)>>>0,128>this.buf[this.pos++])return t;if((this.pos+=5)>this.len)throw this.pos=this.len,indexOutOfRange(this,10);return t}}(),Reader.prototype.int32=function(){return 0|this.uint32()},Reader.prototype.sint32=function(){var t=this.uint32();return 0|t>>>1^-(1&t)},Reader.prototype.bool=function(){return 0!==this.uint32()},Reader.prototype.fixed32=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return readFixed32_end(this.buf,this.pos+=4)},Reader.prototype.sfixed32=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);return 0|readFixed32_end(this.buf,this.pos+=4)},Reader.prototype.float=function(){if(this.pos+4>this.len)throw indexOutOfRange(this,4);var t=minimal.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},Reader.prototype.double=function(){if(this.pos+8>this.len)throw indexOutOfRange(this,4);var t=minimal.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},Reader.prototype.bytes=function(){var n=this.uint32(),e=this.pos,t=this.pos+n;if(t>this.len)throw indexOutOfRange(this,n);return this.pos+=n,Array.isArray(this.buf)?this.buf.slice(e,t):e===t?new this.buf.constructor(0):this._slice.call(this.buf,e,t)},Reader.prototype.string=function(){var t=this.bytes();return utf8$1.read(t,0,t.length)},Reader.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw indexOutOfRange(this,t);this.pos+=t}else do if(this.pos>=this.len)throw indexOutOfRange(this);while(128&this.buf[this.pos++]);return this},Reader.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;;){if(4==(t=7&this.uint32()))break;this.skipType(t)}break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos);}return this},Reader._configure=function(a){BufferReader=a;var e=minimal.Long?"toLong":"toNumber";minimal.merge(Reader.prototype,{int64:function(){return readLongVarint.call(this)[e](!1)},uint64:function(){return readLongVarint.call(this)[e](!0)},sint64:function(){return readLongVarint.call(this).zzDecode()[e](!1)},fixed64:function(){return readFixed64.call(this)[e](!0)},sfixed64:function(){return readFixed64.call(this)[e](!1)}})};var reader_buffer=BufferReader$1;(BufferReader$1.prototype=Object.create(reader.prototype)).constructor=BufferReader$1,minimal.Buffer&&(BufferReader$1.prototype._slice=minimal.Buffer.prototype.slice),BufferReader$1.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice(this.pos,this.pos=_Mathmin(this.pos+t,this.len))};var service=Service;(Service.prototype=Object.create(minimal.EventEmitter.prototype)).constructor=Service,Service.prototype.rpcCall=function i(p,e,t,a,n){if(!a)throw TypeError("request must be specified");var r=this;if(!n)return minimal.asPromise(i,r,p,e,t,a);if(r.rpcImpl)try{return r.rpcImpl(p,e[r.requestDelimited?"encodeDelimited":"encode"](a).finish(),function(o,e){if(o)return r.emit("error",o,p),n(o);if(null!==e){if(!(e instanceof t))try{e=t[r.responseDelimited?"decodeDelimited":"decode"](e)}catch(t){return r.emit("error",t,p),n(t)}return r.emit("data",e,p),n(null,e)}r.end(!0)})}catch(t){return r.emit("error",t,p),void setTimeout(function(){n(t)},0)}else setTimeout(function(){n(Error("already ended"))},0)},Service.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this};var rpc_1=createCommonjsModule$1(function(a,e){e.Service=service}),roots={},indexMinimal=createCommonjsModule$1(function(n,e){function t(){r.Reader._configure(r.BufferReader),r.util._configure()}var r=e;r.build="minimal",r.Writer=writer,r.BufferWriter=writer_buffer,r.Reader=reader,r.BufferReader=reader_buffer,r.util=minimal,r.rpc=rpc_1,r.roots=roots,r.configure=t,r.Writer._configure(r.BufferWriter),t()}),minimal$1=indexMinimal,minimal_1=minimal$1.roots,minimal_2=minimal$1.Reader,minimal_3=minimal$1.util,$Reader=minimal$1.Reader,$util=minimal$1.util,$root=minimal$1.roots.default||(minimal$1.roots.default={});$root.tensorflow=function(){var n={},a,r;return n.Any=function(){function t(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.typeUrl=o.string();break;case 2:a.value=o.bytes();break;default:o.skipType(7&r);}return a},t}(),n.DataType=(a={},(r=Object.create(a))[a[0]="DT_INVALID"]=0,r[a[1]="DT_FLOAT"]=1,r[a[2]="DT_DOUBLE"]=2,r[a[3]="DT_INT32"]=3,r[a[4]="DT_UINT8"]=4,r[a[5]="DT_INT16"]=5,r[a[6]="DT_INT8"]=6,r[a[7]="DT_STRING"]=7,r[a[8]="DT_COMPLEX64"]=8,r[a[9]="DT_INT64"]=9,r[a[10]="DT_BOOL"]=10,r[a[11]="DT_QINT8"]=11,r[a[12]="DT_QUINT8"]=12,r[a[13]="DT_QINT32"]=13,r[a[14]="DT_BFLOAT16"]=14,r[a[101]="DT_FLOAT_REF"]=101,r[a[102]="DT_DOUBLE_REF"]=102,r[a[103]="DT_INT32_REF"]=103,r[a[104]="DT_UINT8_REF"]=104,r[a[105]="DT_INT16_REF"]=105,r[a[106]="DT_INT8_REF"]=106,r[a[107]="DT_STRING_REF"]=107,r[a[108]="DT_COMPLEX64_REF"]=108,r[a[109]="DT_INT64_REF"]=109,r[a[110]="DT_BOOL_REF"]=110,r[a[111]="DT_QINT8_REF"]=111,r[a[112]="DT_QUINT8_REF"]=112,r[a[113]="DT_QINT32_REF"]=113,r[a[114]="DT_BFLOAT16_REF"]=114,r),n.TensorShape=function(){function t(n){if(this.dim=[],n)for(var e=Object.keys(n),t=0;t>>3){case 2:a.dim&&a.dim.length||(a.dim=[]),a.dim.push($root.tensorflow.TensorShape.Dim.decode(o,o.uint32()));break;case 3:a.unknownRank=o.bool();break;default:o.skipType(7&r);}return a},t.Dim=function(){function t(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.size=o.int64();break;case 2:a.name=o.string();break;default:o.skipType(7&r);}return a},t}(),t}(),n.Tensor=function(){function t(n){if(this.floatVal=[],this.doubleVal=[],this.intVal=[],this.stringVal=[],this.scomplexVal=[],this.int64Val=[],this.boolVal=[],this.uint32Val=[],this.uint64Val=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.dtype=s.int32();break;case 2:a.tensorShape=$root.tensorflow.TensorShape.decode(s,s.uint32());break;case 3:a.versionNumber=s.int32();break;case 4:a.tensorContent=s.bytes();break;case 5:if(a.floatVal&&a.floatVal.length||(a.floatVal=[]),2==(7&r))for(var p=s.uint32()+s.pos;s.pos>>3){case 1:a.list=$root.tensorflow.AttrValue.ListValue.decode(o,o.uint32());break;case 2:a.s=o.bytes();break;case 3:a.i=o.int64();break;case 4:a.f=o.float();break;case 5:a.b=o.bool();break;case 6:a.type=o.int32();break;case 7:a.shape=$root.tensorflow.TensorShape.decode(o,o.uint32());break;case 8:a.tensor=$root.tensorflow.Tensor.decode(o,o.uint32());break;case 9:a.placeholder=o.string();break;case 10:a.func=$root.tensorflow.NameAttrList.decode(o,o.uint32());break;default:o.skipType(7&r);}return a},a.ListValue=function(){function t(n){if(this.s=[],this.i=[],this.f=[],this.b=[],this.type=[],this.shape=[],this.tensor=[],this.func=[],n)for(var e=Object.keys(n),t=0;t>>3){case 2:a.s&&a.s.length||(a.s=[]),a.s.push(s.bytes());break;case 3:if(a.i&&a.i.length||(a.i=[]),2==(7&r))for(var p=s.uint32()+s.pos;s.pos>>3){case 1:r.name=s.string();break;case 2:s.skip().pos++,r.attr===$util.emptyObject&&(r.attr={}),n=s.string(),s.pos++,r.attr[n]=$root.tensorflow.AttrValue.decode(s,s.uint32());break;default:s.skipType(7&p);}return r},t}(),n.NodeDef=function(){function t(n){if(this.input=[],this.attr={},n)for(var e=Object.keys(n),t=0;t>>3){case 1:r.name=s.string();break;case 2:r.op=s.string();break;case 3:r.input&&r.input.length||(r.input=[]),r.input.push(s.string());break;case 4:r.device=s.string();break;case 5:s.skip().pos++,r.attr===$util.emptyObject&&(r.attr={}),n=s.string(),s.pos++,r.attr[n]=$root.tensorflow.AttrValue.decode(s,s.uint32());break;default:s.skipType(7&p);}return r},t}(),n.VersionDef=function(){function t(n){if(this.badConsumers=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.producer=s.int32();break;case 2:a.minConsumer=s.int32();break;case 3:if(a.badConsumers&&a.badConsumers.length||(a.badConsumers=[]),2==(7&r))for(var p=s.uint32()+s.pos;s.pos>>3){case 1:a.node&&a.node.length||(a.node=[]),a.node.push($root.tensorflow.NodeDef.decode(o,o.uint32()));break;case 4:a.versions=$root.tensorflow.VersionDef.decode(o,o.uint32());break;case 2:a.library=$root.tensorflow.FunctionDefLibrary.decode(o,o.uint32());break;default:o.skipType(7&r);}return a},t}(),n.CollectionDef=function(){function a(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.nodeList=$root.tensorflow.CollectionDef.NodeList.decode(o,o.uint32());break;case 2:a.bytesList=$root.tensorflow.CollectionDef.BytesList.decode(o,o.uint32());break;case 3:a.int64List=$root.tensorflow.CollectionDef.Int64List.decode(o,o.uint32());break;case 4:a.floatList=$root.tensorflow.CollectionDef.FloatList.decode(o,o.uint32());break;case 5:a.anyList=$root.tensorflow.CollectionDef.AnyList.decode(o,o.uint32());break;default:o.skipType(7&r);}return a},a.NodeList=function(){function t(n){if(this.value=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.value&&a.value.length||(a.value=[]),a.value.push(o.string());break;default:o.skipType(7&r);}return a},t}(),a.BytesList=function(){function t(n){if(this.value=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.value&&a.value.length||(a.value=[]),a.value.push(o.bytes());break;default:o.skipType(7&r);}return a},t}(),a.Int64List=function(){function t(n){if(this.value=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:if(a.value&&a.value.length||(a.value=[]),2==(7&r))for(var p=s.uint32()+s.pos;s.pos>>3){case 1:if(a.value&&a.value.length||(a.value=[]),2==(7&r))for(var p=s.uint32()+s.pos;s.pos>>3){case 1:a.value&&a.value.length||(a.value=[]),a.value.push($root.tensorflow.Any.decode(o,o.uint32()));break;default:o.skipType(7&r);}return a},t}(),a}(),n.SaverDef=function(){function n(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.filenameTensorName=o.string();break;case 2:a.saveTensorName=o.string();break;case 3:a.restoreOpName=o.string();break;case 4:a.maxToKeep=o.int32();break;case 5:a.sharded=o.bool();break;case 6:a.keepCheckpointEveryNHours=o.float();break;case 7:a.version=o.int32();break;default:o.skipType(7&r);}return a},n.CheckpointFormatVersion=(e={},(r=Object.create(e))[e[0]="LEGACY"]=0,r[e[1]="V1"]=1,r[e[2]="V2"]=2,r),n}(),n.TensorInfo=function(){function a(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.name=o.string();break;case 4:a.cooSparse=$root.tensorflow.TensorInfo.CooSparse.decode(o,o.uint32());break;case 2:a.dtype=o.int32();break;case 3:a.tensorShape=$root.tensorflow.TensorShape.decode(o,o.uint32());break;default:o.skipType(7&r);}return a},a.CooSparse=function(){function t(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.valuesTensorName=o.string();break;case 2:a.indicesTensorName=o.string();break;case 3:a.denseShapeTensorName=o.string();break;default:o.skipType(7&r);}return a},t}(),a}(),n.SignatureDef=function(){function t(n){if(this.inputs={},this.outputs={},n)for(var e=Object.keys(n),t=0;t>>3){case 1:s.skip().pos++,r.inputs===$util.emptyObject&&(r.inputs={}),n=s.string(),s.pos++,r.inputs[n]=$root.tensorflow.TensorInfo.decode(s,s.uint32());break;case 2:s.skip().pos++,r.outputs===$util.emptyObject&&(r.outputs={}),n=s.string(),s.pos++,r.outputs[n]=$root.tensorflow.TensorInfo.decode(s,s.uint32());break;case 3:r.methodName=s.string();break;default:s.skipType(7&p);}return r},t}(),n.AssetFileDef=function(){function t(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.tensorInfo=$root.tensorflow.TensorInfo.decode(o,o.uint32());break;case 2:a.filename=o.string();break;default:o.skipType(7&r);}return a},t}(),n.OpDef=function(){function t(n){if(this.inputArg=[],this.outputArg=[],this.attr=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.name=o.string();break;case 2:a.inputArg&&a.inputArg.length||(a.inputArg=[]),a.inputArg.push($root.tensorflow.OpDef.ArgDef.decode(o,o.uint32()));break;case 3:a.outputArg&&a.outputArg.length||(a.outputArg=[]),a.outputArg.push($root.tensorflow.OpDef.ArgDef.decode(o,o.uint32()));break;case 4:a.attr&&a.attr.length||(a.attr=[]),a.attr.push($root.tensorflow.OpDef.AttrDef.decode(o,o.uint32()));break;case 8:a.deprecation=$root.tensorflow.OpDef.OpDeprecation.decode(o,o.uint32());break;case 5:a.summary=o.string();break;case 6:a.description=o.string();break;case 18:a.isCommutative=o.bool();break;case 16:a.isAggregate=o.bool();break;case 17:a.isStateful=o.bool();break;case 19:a.allowsUninitializedInput=o.bool();break;default:o.skipType(7&r);}return a},t.ArgDef=function(){function t(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.name=o.string();break;case 2:a.description=o.string();break;case 3:a.type=o.int32();break;case 4:a.typeAttr=o.string();break;case 5:a.numberAttr=o.string();break;case 6:a.typeListAttr=o.string();break;case 16:a.isRef=o.bool();break;default:o.skipType(7&r);}return a},t}(),t.AttrDef=function(){function t(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.name=o.string();break;case 2:a.type=o.string();break;case 3:a.defaultValue=$root.tensorflow.AttrValue.decode(o,o.uint32());break;case 4:a.description=o.string();break;case 5:a.hasMinimum=o.bool();break;case 6:a.minimum=o.int64();break;case 7:a.allowedValues=$root.tensorflow.AttrValue.decode(o,o.uint32());break;default:o.skipType(7&r);}return a},t}(),t.OpDeprecation=function(){function t(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.version=o.int32();break;case 2:a.explanation=o.string();break;default:o.skipType(7&r);}return a},t}(),t}(),n.OpList=function(){function t(n){if(this.op=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.op&&a.op.length||(a.op=[]),a.op.push($root.tensorflow.OpDef.decode(o,o.uint32()));break;default:o.skipType(7&r);}return a},t}(),n.MetaGraphDef=function(){function t(n){if(this.collectionDef={},this.signatureDef={},this.assetFileDef=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:r.metaInfoDef=$root.tensorflow.MetaGraphDef.MetaInfoDef.decode(s,s.uint32());break;case 2:r.graphDef=$root.tensorflow.GraphDef.decode(s,s.uint32());break;case 3:r.saverDef=$root.tensorflow.SaverDef.decode(s,s.uint32());break;case 4:s.skip().pos++,r.collectionDef===$util.emptyObject&&(r.collectionDef={}),n=s.string(),s.pos++,r.collectionDef[n]=$root.tensorflow.CollectionDef.decode(s,s.uint32());break;case 5:s.skip().pos++,r.signatureDef===$util.emptyObject&&(r.signatureDef={}),n=s.string(),s.pos++,r.signatureDef[n]=$root.tensorflow.SignatureDef.decode(s,s.uint32());break;case 6:r.assetFileDef&&r.assetFileDef.length||(r.assetFileDef=[]),r.assetFileDef.push($root.tensorflow.AssetFileDef.decode(s,s.uint32()));break;default:s.skipType(7&p);}return r},t.MetaInfoDef=function(){function t(n){if(this.tags=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.metaGraphVersion=o.string();break;case 2:a.strippedOpList=$root.tensorflow.OpList.decode(o,o.uint32());break;case 3:a.anyInfo=$root.tensorflow.Any.decode(o,o.uint32());break;case 4:a.tags&&a.tags.length||(a.tags=[]),a.tags.push(o.string());break;case 5:a.tensorflowVersion=o.string();break;case 6:a.tensorflowGitVersion=o.string();break;default:o.skipType(7&r);}return a},t}(),t}(),n.SavedModel=function(){function t(n){if(this.metaGraphs=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.savedModelSchemaVersion=o.int64();break;case 2:a.metaGraphs&&a.metaGraphs.length||(a.metaGraphs=[]),a.metaGraphs.push($root.tensorflow.MetaGraphDef.decode(o,o.uint32()));break;default:o.skipType(7&r);}return a},t}(),n.FunctionDefLibrary=function(){function t(n){if(this.function=[],this.gradient=[],n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.function&&a.function.length||(a.function=[]),a.function.push($root.tensorflow.FunctionDef.decode(o,o.uint32()));break;case 2:a.gradient&&a.gradient.length||(a.gradient=[]),a.gradient.push($root.tensorflow.GradientDef.decode(o,o.uint32()));break;default:o.skipType(7&r);}return a},t}(),n.FunctionDef=function(){function t(n){if(this.attr={},this.nodeDef=[],this.ret={},n)for(var e=Object.keys(n),t=0;t>>3){case 1:r.signature=$root.tensorflow.OpDef.decode(s,s.uint32());break;case 5:s.skip().pos++,r.attr===$util.emptyObject&&(r.attr={}),n=s.string(),s.pos++,r.attr[n]=$root.tensorflow.AttrValue.decode(s,s.uint32());break;case 3:r.nodeDef&&r.nodeDef.length||(r.nodeDef=[]),r.nodeDef.push($root.tensorflow.NodeDef.decode(s,s.uint32()));break;case 4:s.skip().pos++,r.ret===$util.emptyObject&&(r.ret={}),n=s.string(),s.pos++,r.ret[n]=s.string();break;default:s.skipType(7&p);}return r},t}(),n.GradientDef=function(){function t(n){if(n)for(var e=Object.keys(n),t=0;t>>3){case 1:a.functionName=o.string();break;case 2:a.gradientFunc=o.string();break;default:o.skipType(7&r);}return a},t}(),n}();var compiled_api=$root,compiled_api_1=compiled_api.tensorflow,json=[{tfOpName:"Add",dlOpName:"add",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",dlOpName:"addN",category:"arithmetic",params:[{tfInputIndex:0,tfInputParamLength:0,dlParamName:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",dlOpName:"add",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",dlOpName:"sub",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",dlOpName:"div",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",dlOpName:"div",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",dlOpName:"floorDiv",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",dlOpName:"mul",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",dlOpName:"maximum",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"}]},{tfOpName:"Minimum",dlOpName:"minimum",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"}]},{tfOpName:"Pow",dlOpName:"pow",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",dlOpName:"squaredDifference",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",dlOpName:"mod",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",dlOpName:"mod",category:"arithmetic",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}],arithmetic=Object.freeze({json:json}),json$1=[{tfOpName:"Abs",dlOpName:"abs",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",dlOpName:"acos",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",dlOpName:"asin",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",dlOpName:"atan",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",dlOpName:"atan2",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"y",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",dlOpName:"ceil",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",dlOpName:"clipByValue",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"clip_value_min",dlParamName:"clipValueMin",type:"number"},{tfParamName:"clip_value_max",dlParamName:"clipValueMax",type:"number"}]},{tfOpName:"Cos",dlOpName:"cos",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",dlOpName:"cosh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",dlOpName:"elu",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",dlOpName:"exp",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",dlOpName:"floor",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",dlOpName:"log",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",dlOpName:"neg",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",dlOpName:"relu",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",dlOpName:"clipByValue",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0},{dlParamName:"clipValueMin",type:"number",defaultValue:0},{dlParamName:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",dlOpName:"selu",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",dlOpName:"sigmoid",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",dlOpName:"sin",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",dlOpName:"sinh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",dlOpName:"sqrt",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",dlOpName:"rsqrt",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",dlOpName:"square",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",dlOpName:"tan",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",dlOpName:"tanh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",dlOpName:"sign",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",dlOpName:"round",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",dlOpName:"expm1",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",dlOpName:"log1p",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",dlOpName:"reciprocal",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",dlOpName:"reciprocal",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",dlOpName:"softplus",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",dlOpName:"asinh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",dlOpName:"acosh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",dlOpName:"atanh",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",dlOpName:"erf",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",dlOpName:"prod",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axes",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool",notSupported:!0},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",dlOpName:"leakyRelu",category:"basic_math",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"alpha",dlParamName:"alpha",type:"number",defaultValue:.2},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}],basicMath=Object.freeze({json:json$1}),json$2=[{tfOpName:"LoopCond",dlOpName:"loopCond",category:"control",params:[{tfInputIndex:0,dlParamName:"pred",type:"tensor"}]},{tfOpName:"Switch",dlOpName:"switch",category:"control",params:[{tfInputIndex:0,dlParamName:"data",type:"tensor"},{tfInputIndex:1,dlParamName:"pred",type:"tensor"}]},{tfOpName:"Merge",dlOpName:"merge",category:"control",params:[{tfInputIndex:0,tfInputParamLength:0,dlParamName:"tensors",type:"tensors"}]},{tfOpName:"Enter",dlOpName:"enter",category:"control",params:[{tfInputIndex:0,dlParamName:"tensor",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0},{tfParamName:"frame_name",dlParamName:"frameName",type:"string"},{tfParamName:"is_constant",dlParamName:"isConstant",type:"bool"}]},{tfOpName:"Exit",dlOpName:"exit",category:"control",params:[{tfInputIndex:0,dlParamName:"tensor",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",dlOpName:"nextIteration",category:"control",params:[{tfInputIndex:0,dlParamName:"tensor",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",dlOpName:"tensorArray",category:"control",params:[{tfInputIndex:0,dlParamName:"size",type:"number"},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"},{tfParamName:"element_shape",dlParamName:"elementShape",type:"shape"},{tfParamName:"dynamic_size",dlParamName:"dynamicSize",type:"bool"},{tfParamName:"clear_after_read",dlParamName:"clearAfterRead",type:"bool"},{tfParamName:"identical_element_shapes",dlParamName:"identicalElementShapes",type:"bool"},{tfParamName:"tensor_array_name",dlParamName:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",dlOpName:"tensorArrayWrite",category:"control",params:[{tfInputIndex:0,dlParamName:"tensorArrayId",type:"number"},{tfInputIndex:1,dlParamName:"index",type:"number"},{tfInputIndex:2,dlParamName:"tensor",type:"tensor"},{tfInputIndex:3,dlParamName:"flowIn",type:"number"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",dlOpName:"tensorArrayRead",category:"control",params:[{tfInputIndex:0,dlParamName:"tensorArrayId",type:"number"},{tfInputIndex:1,dlParamName:"index",type:"number"},{tfInputIndex:2,dlParamName:"flowIn",type:"number"},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",dlOpName:"tensorArrayGather",category:"control",params:[{tfInputIndex:0,dlParamName:"tensorArrayId",type:"number"},{tfInputIndex:1,dlParamName:"indices",type:"number[]"},{tfInputIndex:2,dlParamName:"flowIn",type:"number"},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"},{tfParamName:"element_shape",dlParamName:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",dlOpName:"tensorArrayScatter",category:"control",params:[{tfInputIndex:0,dlParamName:"tensorArrayId",type:"number"},{tfInputIndex:1,dlParamName:"indices",type:"number[]"},{tfInputIndex:2,dlParamName:"tensor",type:"tensor"},{tfInputIndex:3,dlParamName:"flowIn",type:"number"},{tfParamName:"T",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",dlOpName:"tensorArrayConcat",category:"control",params:[{tfInputIndex:0,dlParamName:"tensorArrayId",type:"number"},{tfInputIndex:1,dlParamName:"flowIn",type:"number"},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"},{tfParamName:"element_shape_except0",dlParamName:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",dlOpName:"tensorArraySplit",category:"control",params:[{tfInputIndex:0,dlParamName:"tensorArrayId",type:"number"},{tfInputIndex:1,dlParamName:"tensor",type:"tensor"},{tfInputIndex:2,dlParamName:"lengths",type:"number[]"},{tfInputIndex:3,dlParamName:"flowIn",type:"number"},{tfParamName:"T",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",dlOpName:"tensorArraySize",category:"control",params:[{tfInputIndex:0,dlParamName:"tensorArrayId",type:"number"},{tfInputIndex:1,dlParamName:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",dlOpName:"tensorArrayClose",category:"control",params:[{tfInputIndex:0,dlParamName:"tensorArrayId",type:"number"}]}],control=Object.freeze({json:json$2}),json$3=[{tfOpName:"AvgPool",dlOpName:"avgPool",category:"convolution",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0},{tfParamName:"ksize",dlParamName:"kernelSize",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",dlOpName:"maxPool",category:"convolution",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0},{tfParamName:"ksize",dlParamName:"kernelSize",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",dlOpName:"conv1d",category:"convolution",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfParamName:"stride",dlParamName:"stride",type:"number"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",defaultValue:"NWC"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0},{tfParamName:"dilation",dlParamName:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",dlOpName:"conv2d",category:"convolution",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"useCudnnOnGpu",dlParamName:"useCudnnOnGpu",type:"bool"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",defaultValue:"NHWC"},{tfParamName:"dilations",dlParamName:"dilations",type:"number[]"}]},{tfOpName:"Conv2DBackpropInput",dlOpName:"conv2dTranspose",category:"convolution",params:[{tfInputIndex:2,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfInputIndex:0,dlParamName:"outputShape",type:"number[]"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",dlOpName:"depthwiseConv2d",category:"convolution",params:[{tfInputIndex:0,dlParamName:"input",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",defaultValue:"NHWC"},{tfParamName:"dilations",dlParamName:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",dlOpName:"depthwiseConv2d",category:"convolution",params:[{tfInputIndex:0,dlParamName:"input",type:"tensor"},{tfInputIndex:1,dlParamName:"filter",type:"tensor"},{tfParamName:"strides",dlParamName:"strides",type:"number[]"},{tfParamName:"padding",dlParamName:"pad",type:"string"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",defaultValue:"NHWC"},{tfParamName:"dilations",dlParamName:"dilations",type:"number[]"}]}],convolution=Object.freeze({json:json$3}),json$4=[{tfOpName:"Fill",dlOpName:"fill",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfInputIndex:1,dlParamName:"value",type:"number"},{tfParamName:"T",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",dlOpName:"linspace",category:"creation",params:[{tfInputIndex:0,dlParamName:"start",type:"number"},{tfInputIndex:1,dlParamName:"stop",type:"number"},{tfInputIndex:2,dlParamName:"num",type:"number"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",dlOpName:"oneHot",category:"creation",params:[{tfInputIndex:0,dlParamName:"indices",type:"tensor"},{tfInputIndex:1,dlParamName:"depth",type:"number"},{tfInputIndex:2,dlParamName:"onValue",type:"number",defaultValue:1},{tfInputIndex:3,dlParamName:"offValue",type:"number",defaultValue:0},{tfParamName:"axis",dlParamName:"axis",type:"number",notSupported:!0},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",dlOpName:"ones",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",dlOpName:"onesLike",category:"creation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",dlOpName:"randomUniform",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfParamName:"minval",dlParamName:"minval",type:"number",defaultValue:0},{tfParamName:"maxval",dlParamName:"maxval",type:"number",defaultValue:1},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"},{tfParamName:"seed",dlParamName:"seed",type:"number",defaultValue:0},{tfParamName:"seed2",dlParamName:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfParamName:"T",dlParamName:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",dlOpName:"range",category:"creation",params:[{tfInputIndex:0,dlParamName:"start",type:"number"},{tfInputIndex:1,dlParamName:"stop",type:"number"},{tfInputIndex:2,dlParamName:"step",type:"number",defaultValue:0},{tfParamName:"Tidx",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"truncatedNormal",dlOpName:"truncatedNormal",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfParamName:"means",dlParamName:"mean",type:"number",defaultValue:0},{tfParamName:"stddev",dlParamName:"stdDev",type:"number",defaultValue:1},{tfParamName:"seed",dlParamName:"seed",type:"number"},{tfParamName:"seed2",dlParamName:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"},{tfParamName:"T",dlParamName:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",dlOpName:"zeros",category:"creation",params:[{tfInputIndex:0,dlParamName:"shape",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",dlOpName:"zerosLike",category:"creation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype"}]}],creation=Object.freeze({json:json$4}),json$5=[{tfOpName:"NonMaxSuppressionV2",dlOpName:"nonMaxSuppression",category:"dynamic",params:[{tfInputIndex:0,dlParamName:"boxes",type:"tensor"},{tfInputIndex:1,dlParamName:"scores",type:"tensor"},{tfInputIndex:2,dlParamName:"maxOutputSize",type:"number"},{tfInputIndex:3,dlParamName:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",dlOpName:"nonMaxSuppression",category:"dynamic",params:[{tfInputIndex:0,dlParamName:"boxes",type:"tensor"},{tfInputIndex:1,dlParamName:"scores",type:"tensor"},{tfInputIndex:2,dlParamName:"maxOutputSize",type:"number"},{tfInputIndex:3,dlParamName:"iouThreshold",type:"number"},{tfInputIndex:4,dlParamName:"scoreThreshold",type:"number"}]},{tfOpName:"Where",dlOpName:"whereAsync",category:"dynamic",params:[{tfInputIndex:0,dlParamName:"condition",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",dlOpName:"setdiff1dAsync",category:"dynamic",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"y",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}],dynamic=Object.freeze({json:json$5}),json$6=[{tfOpName:"TopKV2",dlOpName:"topK",category:"evaluation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"k",type:"number"},{tfParamName:"sorted",dlParamName:"sorted",type:"bool"}]}],evaluation=Object.freeze({json:json$6}),json$7=[{tfOpName:"PlaceholderWithDefault",dlOpName:"placeholder",category:"graph",params:[{tfInputIndex:0,dlParamName:"default",type:"tensor"},{tfParamName:"shape",dlParamName:"shape",type:"shape"},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",dlOpName:"placeholder",category:"graph",params:[{tfParamName:"shape",dlParamName:"shape",type:"shape"},{tfParamName:"dtype",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"Const",dlOpName:"const",category:"graph"},{tfOpName:"Identity",dlOpName:"identity",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"Snapshot",dlOpName:"snapshot",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"Rank",dlOpName:"rank",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"Size",dlOpName:"size",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"Shape",dlOpName:"shape",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"ShapeN",dlOpName:"shapeN",category:"graph",params:[{tfInputIndex:0,tfInputParamLength:0,dlParamName:"x",type:"tensors"}]},{tfOpName:"Print",dlOpName:"print",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,tfInputParamLength:1,dlParamName:"data",type:"tensors"},{tfParamName:"message",dlParamName:"message",type:"string"},{tfParamName:"first_n",dlParamName:"firstN",type:"number",notSupprted:!0},{tfParamName:"summarize",dlParamName:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",dlOpName:"noop",category:"graph",params:[]},{tfOpName:"StopGradient",dlOpName:"stopGradient",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",dlOpName:"fakeQuantWithMinMaxVars",category:"graph",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"min",dlParamName:"min",type:"number"},{tfParamName:"max",dlParamName:"max",type:"number"}]}],graph=Object.freeze({json:json$7}),json$8=[{tfOpName:"ResizeBilinear",dlOpName:"resizeBilinear",category:"image",params:[{tfInputIndex:0,dlParamName:"images",type:"tensor"},{tfInputIndex:1,dlParamName:"size",type:"number[]"},{tfParamName:"align_corners",dlParamName:"alignCorners",type:"bool"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",dlOpName:"resizeNearestNeighbor",category:"image",params:[{tfInputIndex:0,dlParamName:"images",type:"tensor"},{tfInputIndex:1,dlParamName:"size",type:"number[]"},{tfParamName:"align_corners",dlParamName:"alignCorners",type:"bool"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",dlOpName:"cropAndResize",category:"image",params:[{tfInputIndex:0,dlParamName:"image",type:"tensor"},{tfInputIndex:1,dlParamName:"boxes",type:"tensor"},{tfInputIndex:2,dlParamName:"boxInd",type:"tensor"},{tfInputIndex:3,dlParamName:"cropSize",type:"number[]"},{tfParamName:"method",dlParamName:"method",type:"string"},{tfParamName:"extrapolation_value",dlParamName:"extrapolationValue",type:"number"}]}],image$1=Object.freeze({json:json$8}),json$9=[{tfOpName:"Equal",dlOpName:"equal",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",dlOpName:"notEqual",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",dlOpName:"greater",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",dlOpName:"greaterEqual",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",dlOpName:"less",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",dlOpName:"lessEqual",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",dlOpName:"logicalAnd",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",dlOpName:"logicalNot",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",dlOpName:"logicalOr",category:"logical",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",dlOpName:"where",category:"logical",params:[{tfInputIndex:0,dlParamName:"condition",type:"tensor"},{tfInputIndex:1,dlParamName:"a",type:"tensor"},{tfInputIndex:2,dlParamName:"b",type:"tensor"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}],logical=Object.freeze({json:json$9}),json$10=[{tfOpName:"MatMul",dlOpName:"matMul",category:"matrices",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"transpose_a",dlParamName:"transposeA",type:"bool",defaultValue:!1},{tfParamName:"transpose_b",dlParamName:"transposeB",type:"bool",defaultValue:!1},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",dlOpName:"matMul",category:"matrices",params:[{tfInputIndex:0,dlParamName:"a",type:"tensor"},{tfInputIndex:1,dlParamName:"b",type:"tensor"},{tfParamName:"adj_x",dlParamName:"transposeA",type:"bool",defaultValue:!1},{tfParamName:"adj_y",dlParamName:"transposeB",type:"bool",defaultValue:!1},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",dlOpName:"transpose",category:"matrices",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"perm",type:"number[]"},{tfParamName:"T",dlParamName:"dtype",type:"dtype",notSupported:!0}]}],matrices=Object.freeze({json:json$10}),json$11=[{tfOpName:"FusedBatchNorm",dlOpName:"batchNormalization",category:"normalization",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"scale",type:"tensor"},{tfInputIndex:2,dlParamName:"offset",type:"tensor"},{tfInputIndex:3,dlParamName:"mean",type:"tensor"},{tfInputIndex:4,dlParamName:"variance",type:"tensor"},{tfParamName:"epsilon",dlParamName:"epsilon",type:"number",defaultValue:.001},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",dlOpName:"batchNormalization",category:"normalization",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"scale",type:"tensor"},{tfInputIndex:2,dlParamName:"offset",type:"tensor"},{tfInputIndex:3,dlParamName:"mean",type:"tensor"},{tfInputIndex:4,dlParamName:"variance",type:"tensor"},{tfParamName:"epsilon",dlParamName:"epsilon",type:"number",defaultValue:.001},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",dlOpName:"localResponseNormalization",category:"normalization",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"depth_radius",dlParamName:"radius",type:"number",defaultValue:5},{tfParamName:"bias",dlParamName:"bias",type:"number",defaultValue:1},{tfParamName:"alpha",dlParamName:"alpha",type:"number",defaultValue:1},{tfParamName:"beta",dlParamName:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",dlOpName:"softmax",category:"normalization",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",dlOpName:"logSoftmax",category:"normalization",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"}]},{tfOpName:"SparseToDense",dlOpName:"sparseToDense",category:"normalization",params:[{tfInputIndex:0,dlParamName:"sparseIndices",type:"tensor"},{tfInputIndex:1,dlParamName:"outputShape",type:"number[]"},{tfInputIndex:2,dlParamName:"sparseValues",type:"tensor"},{tfInputIndex:3,dlParamName:"defaultValue",type:"tensor"},{tfParamName:"validate_indices",dlParamName:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],normalization=Object.freeze({json:json$11}),json$12=[{tfOpName:"Max",dlOpName:"max",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"Mean",dlOpName:"mean",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"Min",dlOpName:"min",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"Sum",dlOpName:"sum",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"All",dlOpName:"all",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"Any",dlOpName:"any",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",dlOpName:"argMax",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number"}]},{tfOpName:"ArgMin",dlOpName:"argMin",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number"}]},{tfOpName:"Prod",dlOpName:"prod",category:"reduction",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"},{tfParamName:"keep_dims",dlParamName:"keepDims",type:"bool"}]}],reduction=Object.freeze({json:json$12}),json$13=[{tfOpName:"ConcatV2",dlOpName:"concat",category:"slice_join",params:[{tfInputIndex:0,tfInputParamLength:1,dlParamName:"tensors",type:"tensors"},{tfInputIndex:-1,dlParamName:"axis",type:"number"}]},{tfOpName:"Concat",dlOpName:"concat",category:"slice_join",params:[{tfInputIndex:1,tfInputParamLength:1,dlParamName:"tensors",type:"tensors"},{tfInputIndex:0,dlParamName:"axis",type:"number"}]},{tfOpName:"GatherV2",dlOpName:"gather",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"indices",type:"tensor"},{tfInputIndex:2,dlParamName:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",dlOpName:"gather",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"indices",type:"tensor"},{tfParamName:"axis",dlParamName:"axis",type:"number",defaultValue:0},{tfParamName:"validate_indices",dlParamName:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",dlOpName:"reverse",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",dlOpName:"reverse",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"axis",type:"number[]"}]},{tfOpName:"Slice",dlOpName:"slice",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"begin",type:"number[]"},{tfInputIndex:2,dlParamName:"size",type:"number[]"}]},{tfOpName:"StridedSlice",dlOpName:"stridedSlice",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"begin",type:"number[]"},{tfInputIndex:2,dlParamName:"end",type:"number[]"},{tfInputIndex:3,dlParamName:"strides",type:"number[]"},{tfParamName:"begin_mask",dlParamName:"beginMask",type:"number",defaultValue:0},{tfParamName:"end_mask",dlParamName:"endMask",type:"number",defaultValue:0},{tfParamName:"new_axis_mask",dlParamName:"newAxisMask",type:"number",defaultValue:0},{tfParamName:"ellipsis_mask",dlParamName:"ellipsisMask",type:"number",defaultValue:0},{tfParamName:"shrink_axis_mask",dlParamName:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",dlOpName:"stack",category:"slice_join",params:[{tfInputIndex:0,tfInputParamLength:0,dlParamName:"tensors",type:"tensors"},{tfParamName:"axis",dlParamName:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",dlOpName:"unstack",category:"slice_join",params:[{tfInputIndex:0,tfInputParamLength:0,dlParamName:"tensor",type:"tensor"},{tfParamName:"axis",dlParamName:"axis",type:"number",defaultValue:0},{tfParamName:"num",dlParamName:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",dlOpName:"tile",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"reps",type:"number[]"}]},{tfOpName:"Split",dlOpName:"split",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"axis",type:"number",defaultValue:0},{tfInputIndex:1,dlParamName:"x",type:"tensor"},{tfParamName:"num_split",dlParamName:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",dlOpName:"split",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"numOrSizeSplits",type:"number[]"},{tfInputIndex:2,dlParamName:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",dlOpName:"scatterNd",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"indices",type:"tensor"},{tfInputIndex:1,dlParamName:"values",type:"tensor"},{tfInputIndex:2,dlParamName:"shape",type:"number[]"}]},{tfOpName:"GatherNd",dlOpName:"gatherNd",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",dlOpName:"sparseToDense",category:"slice_join",params:[{tfInputIndex:0,dlParamName:"sparseIndices",type:"tensor"},{tfInputIndex:1,dlParamName:"outputShape",type:"number[]"},{tfInputIndex:2,dlParamName:"sparseValues",type:"tensor"},{tfInputIndex:3,dlParamName:"defaultValue",type:"tensor"},{tfParamName:"validate_indices",dlParamName:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}],sliceJoin=Object.freeze({json:json$13}),json$14=[{tfOpName:"Cast",dlOpName:"cast",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"SrcT",dlParamName:"sdtype",type:"dtype",notSupported:!0},{tfParamName:"DstT",dlParamName:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",dlOpName:"expandDims",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,tfParamNameDeprecated:"dim",dlParamName:"axis",type:"number"}]},{tfOpName:"Pad",dlOpName:"pad",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"padding",type:"number[]"},{tfParamName:"constant_value",dlParamName:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",dlOpName:"pad",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"padding",type:"number[]"},{tfInputIndex:2,dlParamName:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",dlOpName:"reshape",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"shape",type:"number[]"}]},{tfOpName:"Squeeze",dlOpName:"squeeze",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"axis",tfParamNameDeprecated:"squeeze_dims",dlParamName:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",dlOpName:"spaceToBatchND",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"blockShape",type:"number[]"},{tfInputIndex:2,dlParamName:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",dlOpName:"batchToSpaceND",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfInputIndex:1,dlParamName:"blockShape",type:"number[]"},{tfInputIndex:2,dlParamName:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",dlOpName:"depthToSpace",category:"transformation",params:[{tfInputIndex:0,dlParamName:"x",type:"tensor"},{tfParamName:"block_size",dlParamName:"blockSize",type:"number"},{tfParamName:"data_format",dlParamName:"dataFormat",type:"string"}]}],transformation=Object.freeze({json:json$14}),CONTROL_FLOW_OPS=["Switch","Merge","Enter","Exit","NextIteration"],DYNAMIC_SHAPE_OPS=["NonMaxSuppressionV2","NonMaxSuppressionV3","Where"],OperationMapper=function(){function t(){var e=[].concat.apply([],[arithmetic,basicMath,control,convolution,creation,dynamic,evaluation,logical,image$1,graph,matrices,normalization,reduction,sliceJoin,transformation].map(function(t){return t.json}));this.opMappers=e.reduce(function(a,e){return a[e.tfOpName]=e,a},{})}return Object.defineProperty(t,"Instance",{get:function(){return this._instance||(this._instance=new this)},enumerable:!0,configurable:!0}),t.prototype.isControlFlow=function(a){return CONTROL_FLOW_OPS.some(function(e){return e===a.op})},t.prototype.isDynamicShape=function(a){return DYNAMIC_SHAPE_OPS.some(function(e){return e===a.op})},t.prototype.transformGraph=function(l){var d=this,t=!1,u=!1,c=[],n=[],o=l.node.reduce(function(a,e){return a[e.name]=d.mapNode(e),d.isControlFlow(e)&&(t=!0),d.isDynamicShape(e)&&(u=!0),"Placeholder"===e.op&&c.push(a[e.name]),"Const"===e.op&&n.push(a[e.name]),a},{}),s=[],i=[];return Object.keys(o).forEach(function(a){var n=o[a];n.inputNames.forEach(function(t){var e=getNodeNameAndIndex(t)[0];n.inputs.push(o[e]),o[e].children.push(n)}),0===n.inputs.length&&s.push(n)}),Object.keys(o).forEach(function(a){var e=o[a];0===e.children.length&&i.push(e)}),{nodes:o,inputs:s,outputs:i,weights:n,placeholders:c,withControlFlow:t,withDynamicShape:u}},t.prototype.mapNode=function(n){var e=this,t=this.opMappers[n.op];if(void 0===t)throw new Error("Tensorflow Op is not supported: "+n.op);var a={name:n.name,op:t.dlOpName,category:t.category,inputNames:(n.input||[]).map(function(t){return t.startsWith("^")?t.substr(1):t}),inputs:[],children:[],params:{}};return t.params&&(a.params=t.params.reduce(function(t,a){var r=a.tfInputIndex,p=a.tfInputParamLength,o=a.type,s;if(void 0===r)switch(a.type){case"string":void 0===(s=e.getStringParam(n.attr,a.tfParamName,a.defaultValue))&&a.tfParamNameDeprecated&&(s=e.getStringParam(n.attr,a.tfParamNameDeprecated,a.defaultValue));break;case"number":void 0===(s=e.getNumberParam(n.attr,a.tfParamName,a.defaultValue))&&a.tfParamNameDeprecated&&(s=e.getNumberParam(n.attr,a.tfParamNameDeprecated,a.defaultValue));break;case"number[]":void 0===(s=e.getNumericArrayParam(n.attr,a.tfParamName,a.defaultValue))&&a.tfParamNameDeprecated&&(s=e.getNumericArrayParam(n.attr,a.tfParamNameDeprecated,a.defaultValue));break;case"bool":void 0===(s=e.getBoolParam(n.attr,a.tfParamName,a.defaultValue))&&a.tfParamNameDeprecated&&(s=e.getBoolParam(n.attr,a.tfParamNameDeprecated,a.defaultValue));break;case"shape":void 0===(s=e.getTensorShapeParam(n.attr,a.tfParamName,a.defaultValue))&&a.tfParamNameDeprecated&&(s=e.getTensorShapeParam(n.attr,a.tfParamNameDeprecated,a.defaultValue));break;case"dtype":void 0===(s=e.getDtypeParam(n.attr,a.tfParamName,a.defaultValue))&&a.tfParamNameDeprecated&&(s=e.getDtypeParam(n.attr,a.tfParamNameDeprecated,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+a.type+" for op: "+n.op);}return t[a.dlParamName]={value:s,inputIndex:r,type:o,inputParamLength:p},t},{})),a},t.prototype.getStringParam=function(s,e,t,a){void 0===a&&(a=!1);var i=s[e];if(void 0!==i){var n=_StringfromCharCode.apply(null,i.s);return a?n:n.toLowerCase()}return t},t.prototype.getBoolParam=function(n,e,t){var a=n[e];return a?a.b:t},t.prototype.getNumberParam=function(o,e,t){var a=o[e],r=a?a[a.value]:t;return"number"==typeof r?r:r.toInt()},t.prototype.getDtypeParam=function(n,e,t){var a=n[e];if(a&&a.type)switch(a.type){case compiled_api_1.DataType.DT_FLOAT:return"float32";case compiled_api_1.DataType.DT_INT32:return"int32";case compiled_api_1.DataType.DT_BOOL:return"bool";default:return t;}return t},t.prototype.getTensorShapeParam=function(n,e,t){var a=n[e];return a&&a.shape?a.shape.dim.map(function(t){return"number"==typeof t.size?t.size:t.size.toInt()}):t},t.prototype.getNumericArrayParam=function(n,e,t){var a=n[e];return a?(a.list.f&&a.list.f.length?a.list.f:a.list.i).map(function(t){return"number"==typeof t?t:t.toInt()}):t},t}(),executeOp=function(n,e,t){switch(n.op){case"add":return[add(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];case"addN":return[addN(getParamValue("tensors",n,e,t))];case"mod":return[mod(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];case"mul":return[mul(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];case"div":return[div(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];case"floorDiv":return[floorDiv(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];case"sub":return[sub(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];case"minimum":return[minimum(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];case"maximum":return[maximum(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];case"pow":return[pow(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];case"squaredDifference":return[squaredDifference(getParamValue("a",n,e,t),getParamValue("b",n,e,t))];default:throw TypeError("Node type "+n.op+" is not implemented");}},executeOp$1=function(n,e,t){switch(n.op){case"abs":return[abs(getParamValue("x",n,e,t))];case"acos":return[acos(getParamValue("x",n,e,t))];case"acosh":return[acosh(getParamValue("x",n,e,t))];case"asin":return[asin(getParamValue("x",n,e,t))];case"asinh":return[asinh(getParamValue("x",n,e,t))];case"atan":return[atan(getParamValue("x",n,e,t))];case"atan2":return[atan2(getParamValue("x",n,e,t),getParamValue("y",n,e,t))];case"atanh":return[atanh(getParamValue("x",n,e,t))];case"ceil":return[ceil(getParamValue("x",n,e,t))];case"cos":return[cos(getParamValue("x",n,e,t))];case"cosh":return[cosh(getParamValue("x",n,e,t))];case"elu":return[elu(getParamValue("x",n,e,t))];case"erf":return[erf(getParamValue("x",n,e,t))];case"exp":return[exp(getParamValue("x",n,e,t))];case"expm1":return[expm1(getParamValue("x",n,e,t))];case"floor":return[floor(getParamValue("x",n,e,t))];case"log":return[log$1(getParamValue("x",n,e,t))];case"log1p":return[log1p(getParamValue("x",n,e,t))];case"neg":return[neg(getParamValue("x",n,e,t))];case"reciprocal":return[reciprocal(getParamValue("x",n,e,t))];case"relu":return[relu(getParamValue("x",n,e,t))];case"round":return[round(getParamValue("x",n,e,t))];case"selu":return[selu(getParamValue("x",n,e,t))];case"sigmoid":return[sigmoid(getParamValue("x",n,e,t))];case"sin":return[sin(getParamValue("x",n,e,t))];case"sign":return[sign(getParamValue("x",n,e,t))];case"sinh":return[sinh(getParamValue("x",n,e,t))];case"softplus":return[softplus(getParamValue("x",n,e,t))];case"sqrt":return[sqrt(getParamValue("x",n,e,t))];case"square":return[square(getParamValue("x",n,e,t))];case"tanh":return[tanh$1(getParamValue("x",n,e,t))];case"tan":return[tan(getParamValue("x",n,e,t))];case"clipByValue":return[clipByValue(getParamValue("x",n,e,t),getParamValue("clipValueMin",n,e,t),getParamValue("clipValueMax",n,e,t))];case"rsqrt":return[div(scalar(1,"float32"),sqrt(getTensor(n.inputNames[0],e,t)))];case"prod":return[prod(getParamValue("x",n,e,t),getParamValue("axes",n,e,t))];case"leakyRelu":return[leakyRelu(getParamValue("x",n,e,t),getParamValue("alpha",n,e,t))];default:throw TypeError("Node type "+n.op+" is not implemented");}},TensorArray=function(){function p(e,t,a,r,n,o,s){this.name=e,this.dtype=t,this.maxSize=a,this.elementShape=r,this.identicalElementShapes=n,this.dynamicSize=o,this.clearAfterRead=s,this.tensors=[],this.closed_=!1,this.id=p.nextId++}return Object.defineProperty(p.prototype,"closed",{get:function(){return this.closed_},enumerable:!0,configurable:!0}),p.prototype.clearAndClose=function(){this.tensors.forEach(function(t){return t.tensor.dispose()}),this.tensors=[],this.closed_=!0},p.prototype.size=function(){return this.tensors.length},p.prototype.read=function(a){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(0>a||a>=this.tensors.length)throw new Error("Tried to read from index "+a+", but array size is: "+this.tensors.length);var e=this.tensors[a];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+a+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},p.prototype.readMany=function(a){var n=this;return a.map(function(t){return n.read(t)})},p.prototype.write=function(n,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(0>n||!this.dynamicSize&&n>=this.maxSize)throw new Error("Tried to write to index "+n+", but array is not resizeable and size is: "+this.maxSize);var t=this.tensors[n]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+n+",\n because the value dtype is "+e.dtype+", but TensorArray dtype is "+this.dtype+".");if(0===this.size()&&0===this.elementShape.length&&(this.elementShape=e.shape),this.assertShapesMatch(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+n+"."),t&&t.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+n+", because it has already been read.");if(t&&t.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+n+", because it has already been written.");t.tensor=e,t.written=!0,this.tensors[n]=t},p.prototype.writeMany=function(n,o){var t=this;if(n.length!==o.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+n.length+" is not the same as tensors size: "+o.length+".");n.forEach(function(a,e){return t.write(a,o[e])})},p.prototype.gather=function(n,o){if(o&&o!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+o);if(!n){n=[];for(var t=0;t=this.maxSize)throw new Error("Max index must be < array size ("+t+" vs. "+this.maxSize+")");this.writeMany(n,unstack(e,0))},p.prototype.split=function(l,e){var d=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var a=0,u=l.map(function(t){return a+=t});if(a!==e.shape[0])throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+a+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&l.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+l.length+"), and the TensorArray is not marked as dynamically resizeable");var n=0===a?0:e.size/a,o=[];tidy(function(){e=e.reshape([1,a,n]);for(var t=0;tawait e.data()),e.map(async e=>e.dispose())}async detect(e){let t=Date.now();const[a,n]=getInputTensorDimensions(e),r=getValidResolution(this.modelParams.imageScaleFactor,a,this.modelParams.outputStride),o=getValidResolution(this.modelParams.imageScaleFactor,n,this.modelParams.outputStride),s=tidy(()=>{const t=fromPixels(e);return this.modelParams.flipHorizontal?t.reverse(1).resizeBilinear([r,o]).expandDims(0):t.resizeBilinear([r,o]).expandDims(0)});return self=this,this.model.executeAsync(s).then(function(e){const r=e[0].dataSync(),o=e[1].dataSync();s.dispose(),dispose(e);// console.log("scores result",scores, boxes) +const[i,p]=calculateMaxScores(r,e[0].shape[1],e[0].shape[2]),l=getBackend();setBackend("cpu");const d=tidy(()=>{const t=tensor2d(o,[e[1].shape[1],e[1].shape[3]]);return image_ops.nonMaxSuppression(t,r,self.modelParams.maxNumBoxes,// maxNumBoxes +self.modelParams.iouThreshold,// iou_threshold +self.modelParams.scoreThreshold// score_threshold +)}),u=d.dataSync();d.dispose(),setBackend(l);const c=self.buildDetectedObjects(n,a,o,r,u,p);let m=Date.now();return self.fps=_Mathround(1e3/(m-t)),c})}buildDetectedObjects(e,t,a,n,r,o){const s=r.length,p=[];for(let l=0;le;e++)s[e]=a[4*r[l]+e];const i=s[0]*t,d=s[1]*e,u=s[2]*t,c=s[3]*e;s[0]=d,s[1]=i,s[2]=c-d,s[3]=u-i,p.push({bbox:s,class:o[r[l]],score:n[r[l]]})}return p}getFPS(){return this.fps}setModelParameters(e){this.modelParams=Object.assign({},this.modelParams,e)}getModelParameters(){return this.modelParams}renderPredictions(e,t,a,n){a.clearRect(0,0,t.width,t.height),t.width=n.width,t.height=n.height,a.save(),this.modelParams.flipHorizontal&&(a.scale(-1,1),a.translate(-n.width,0)),a.drawImage(n,0,0,n.width,n.height),a.restore(),a.font="10px Arial";// console.log('number of detections: ', predictions.length); +for(let r=0;r= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this +} + +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} + +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest +} + +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} + +module.exports = HashBase + +},{"inherits":101,"safe-buffer":142,"stream":151}],87:[function(require,module,exports){ +var hash = exports; + +hash.utils = require('./hash/utils'); +hash.common = require('./hash/common'); +hash.sha = require('./hash/sha'); +hash.ripemd = require('./hash/ripemd'); +hash.hmac = require('./hash/hmac'); + +// Proxy hash functions to the main object +hash.sha1 = hash.sha.sha1; +hash.sha256 = hash.sha.sha256; +hash.sha224 = hash.sha.sha224; +hash.sha384 = hash.sha.sha384; +hash.sha512 = hash.sha.sha512; +hash.ripemd160 = hash.ripemd.ripemd160; + +},{"./hash/common":88,"./hash/hmac":89,"./hash/ripemd":90,"./hash/sha":91,"./hash/utils":98}],88:[function(require,module,exports){ +'use strict'; + +var utils = require('./utils'); +var assert = require('minimalistic-assert'); + +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = 'big'; + + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +exports.BlockHash = BlockHash; + +BlockHash.prototype.update = function update(msg, enc) { + // Convert message to array, pad it, and join into 32bit blocks + msg = utils.toArray(msg, enc); + if (!this.pending) + this.pending = msg; + else + this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + + // Enough data, try updating + if (this.pending.length >= this._delta8) { + msg = this.pending; + + // Process pending data in blocks + var r = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r, msg.length); + if (this.pending.length === 0) + this.pending = null; + + msg = utils.join32(msg, 0, msg.length - r, this.endian); + for (var i = 0; i < msg.length; i += this._delta32) + this._update(msg, i, i + this._delta32); + } + + return this; +}; + +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + assert(this.pending === null); + + return this._digest(enc); +}; + +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - ((len + this.padLength) % bytes); + var res = new Array(k + this.padLength); + res[0] = 0x80; + for (var i = 1; i < k; i++) + res[i] = 0; + + // Append length + len <<= 3; + if (this.endian === 'big') { + for (var t = 8; t < this.padLength; t++) + res[i++] = 0; + + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = (len >>> 24) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = len & 0xff; + } else { + res[i++] = len & 0xff; + res[i++] = (len >>> 8) & 0xff; + res[i++] = (len >>> 16) & 0xff; + res[i++] = (len >>> 24) & 0xff; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + + for (t = 8; t < this.padLength; t++) + res[i++] = 0; + } + + return res; +}; + +},{"./utils":98,"minimalistic-assert":106}],89:[function(require,module,exports){ +'use strict'; + +var utils = require('./utils'); +var assert = require('minimalistic-assert'); + +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) + return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + + this._init(utils.toArray(key, enc)); +} +module.exports = Hmac; + +Hmac.prototype._init = function init(key) { + // Shorten key, if needed + if (key.length > this.blockSize) + key = new this.Hash().update(key).digest(); + assert(key.length <= this.blockSize); + + // Add padding to key + for (var i = key.length; i < this.blockSize; i++) + key.push(0); + + for (i = 0; i < key.length; i++) + key[i] ^= 0x36; + this.inner = new this.Hash().update(key); + + // 0x36 ^ 0x5c = 0x6a + for (i = 0; i < key.length; i++) + key[i] ^= 0x6a; + this.outer = new this.Hash().update(key); +}; + +Hmac.prototype.update = function update(msg, enc) { + this.inner.update(msg, enc); + return this; +}; + +Hmac.prototype.digest = function digest(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; + +},{"./utils":98,"minimalistic-assert":106}],90:[function(require,module,exports){ +'use strict'; + +var utils = require('./utils'); +var common = require('./common'); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_3 = utils.sum32_3; +var sum32_4 = utils.sum32_4; +var BlockHash = common.BlockHash; + +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) + return new RIPEMD160(); + + BlockHash.call(this); + + this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; + this.endian = 'little'; +} +utils.inherits(RIPEMD160, BlockHash); +exports.ripemd160 = RIPEMD160; + +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; +RIPEMD160.padLength = 64; + +RIPEMD160.prototype._update = function update(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for (var j = 0; j < 80; j++) { + var T = sum32( + rotl32( + sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), + s[j]), + E); + A = E; + E = D; + D = rotl32(C, 10); + C = B; + B = T; + T = sum32( + rotl32( + sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), + sh[j]), + Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3(this.h[1], C, Dh); + this.h[1] = sum32_3(this.h[2], D, Eh); + this.h[2] = sum32_3(this.h[3], E, Ah); + this.h[3] = sum32_3(this.h[4], A, Bh); + this.h[4] = sum32_3(this.h[0], B, Ch); + this.h[0] = T; +}; + +RIPEMD160.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'little'); + else + return utils.split32(this.h, 'little'); +}; + +function f(j, x, y, z) { + if (j <= 15) + return x ^ y ^ z; + else if (j <= 31) + return (x & y) | ((~x) & z); + else if (j <= 47) + return (x | (~y)) ^ z; + else if (j <= 63) + return (x & z) | (y & (~z)); + else + return x ^ (y | (~z)); +} + +function K(j) { + if (j <= 15) + return 0x00000000; + else if (j <= 31) + return 0x5a827999; + else if (j <= 47) + return 0x6ed9eba1; + else if (j <= 63) + return 0x8f1bbcdc; + else + return 0xa953fd4e; +} + +function Kh(j) { + if (j <= 15) + return 0x50a28be6; + else if (j <= 31) + return 0x5c4dd124; + else if (j <= 47) + return 0x6d703ef3; + else if (j <= 63) + return 0x7a6d76e9; + else + return 0x00000000; +} + +var r = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +]; + +var rh = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +]; + +var s = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +]; + +var sh = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +]; + +},{"./common":88,"./utils":98}],91:[function(require,module,exports){ +'use strict'; + +exports.sha1 = require('./sha/1'); +exports.sha224 = require('./sha/224'); +exports.sha256 = require('./sha/256'); +exports.sha384 = require('./sha/384'); +exports.sha512 = require('./sha/512'); + +},{"./sha/1":92,"./sha/224":93,"./sha/256":94,"./sha/384":95,"./sha/512":96}],92:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); +var common = require('../common'); +var shaCommon = require('./common'); + +var rotl32 = utils.rotl32; +var sum32 = utils.sum32; +var sum32_5 = utils.sum32_5; +var ft_1 = shaCommon.ft_1; +var BlockHash = common.BlockHash; + +var sha1_K = [ + 0x5A827999, 0x6ED9EBA1, + 0x8F1BBCDC, 0xCA62C1D6 +]; + +function SHA1() { + if (!(this instanceof SHA1)) + return new SHA1(); + + BlockHash.call(this); + this.h = [ + 0x67452301, 0xefcdab89, 0x98badcfe, + 0x10325476, 0xc3d2e1f0 ]; + this.W = new Array(80); +} + +utils.inherits(SHA1, BlockHash); +module.exports = SHA1; + +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; +SHA1.padLength = 64; + +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + + for(; i < W.length; i++) + W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + + for (i = 0; i < W.length; i++) { + var s = ~~(i / 20); + var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); + e = d; + d = c; + c = rotl32(b, 30); + b = a; + a = t; + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); +}; + +SHA1.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +},{"../common":88,"../utils":98,"./common":97}],93:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); +var SHA256 = require('./256'); + +function SHA224() { + if (!(this instanceof SHA224)) + return new SHA224(); + + SHA256.call(this); + this.h = [ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, + 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; +} +utils.inherits(SHA224, SHA256); +module.exports = SHA224; + +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; +SHA224.padLength = 64; + +SHA224.prototype._digest = function digest(enc) { + // Just truncate output + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 7), 'big'); + else + return utils.split32(this.h.slice(0, 7), 'big'); +}; + + +},{"../utils":98,"./256":94}],94:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); +var common = require('../common'); +var shaCommon = require('./common'); +var assert = require('minimalistic-assert'); + +var sum32 = utils.sum32; +var sum32_4 = utils.sum32_4; +var sum32_5 = utils.sum32_5; +var ch32 = shaCommon.ch32; +var maj32 = shaCommon.maj32; +var s0_256 = shaCommon.s0_256; +var s1_256 = shaCommon.s1_256; +var g0_256 = shaCommon.g0_256; +var g1_256 = shaCommon.g1_256; + +var BlockHash = common.BlockHash; + +var sha256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]; + +function SHA256() { + if (!(this instanceof SHA256)) + return new SHA256(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash); +module.exports = SHA256; + +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; + +SHA256.prototype._update = function _update(msg, start) { + var W = this.W; + + for (var i = 0; i < 16; i++) + W[i] = msg[start + i]; + for (; i < W.length; i++) + W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); + + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + + assert(this.k.length === W.length); + for (i = 0; i < W.length; i++) { + var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); + var T2 = sum32(s0_256(a), maj32(a, b, c)); + h = g; + g = f; + f = e; + e = sum32(d, T1); + d = c; + c = b; + b = a; + a = sum32(T1, T2); + } + + this.h[0] = sum32(this.h[0], a); + this.h[1] = sum32(this.h[1], b); + this.h[2] = sum32(this.h[2], c); + this.h[3] = sum32(this.h[3], d); + this.h[4] = sum32(this.h[4], e); + this.h[5] = sum32(this.h[5], f); + this.h[6] = sum32(this.h[6], g); + this.h[7] = sum32(this.h[7], h); +}; + +SHA256.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +},{"../common":88,"../utils":98,"./common":97,"minimalistic-assert":106}],95:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); + +var SHA512 = require('./512'); + +function SHA384() { + if (!(this instanceof SHA384)) + return new SHA384(); + + SHA512.call(this); + this.h = [ + 0xcbbb9d5d, 0xc1059ed8, + 0x629a292a, 0x367cd507, + 0x9159015a, 0x3070dd17, + 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, + 0x8eb44a87, 0x68581511, + 0xdb0c2e0d, 0x64f98fa7, + 0x47b5481d, 0xbefa4fa4 ]; +} +utils.inherits(SHA384, SHA512); +module.exports = SHA384; + +SHA384.blockSize = 1024; +SHA384.outSize = 384; +SHA384.hmacStrength = 192; +SHA384.padLength = 128; + +SHA384.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h.slice(0, 12), 'big'); + else + return utils.split32(this.h.slice(0, 12), 'big'); +}; + +},{"../utils":98,"./512":96}],96:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); +var common = require('../common'); +var assert = require('minimalistic-assert'); + +var rotr64_hi = utils.rotr64_hi; +var rotr64_lo = utils.rotr64_lo; +var shr64_hi = utils.shr64_hi; +var shr64_lo = utils.shr64_lo; +var sum64 = utils.sum64; +var sum64_hi = utils.sum64_hi; +var sum64_lo = utils.sum64_lo; +var sum64_4_hi = utils.sum64_4_hi; +var sum64_4_lo = utils.sum64_4_lo; +var sum64_5_hi = utils.sum64_5_hi; +var sum64_5_lo = utils.sum64_5_lo; + +var BlockHash = common.BlockHash; + +var sha512_K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; + +function SHA512() { + if (!(this instanceof SHA512)) + return new SHA512(); + + BlockHash.call(this); + this.h = [ + 0x6a09e667, 0xf3bcc908, + 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, + 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, + 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, + 0x5be0cd19, 0x137e2179 ]; + this.k = sha512_K; + this.W = new Array(160); +} +utils.inherits(SHA512, BlockHash); +module.exports = SHA512; + +SHA512.blockSize = 1024; +SHA512.outSize = 512; +SHA512.hmacStrength = 192; +SHA512.padLength = 128; + +SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + + // 32 x 32bit words + for (var i = 0; i < 32; i++) + W[i] = msg[start + i]; + for (; i < W.length; i += 2) { + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; // i - 7 + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; // i - 16 + var c3_lo = W[i - 31]; + + W[i] = sum64_4_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + W[i + 1] = sum64_4_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo); + } +}; + +SHA512.prototype._update = function _update(msg, start) { + this._prepareBlock(msg, start); + + var W = this.W; + + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + + assert(this.k.length === W.length); + for (var i = 0; i < W.length; i += 2) { + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + + var T1_hi = sum64_5_hi( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + var T1_lo = sum64_5_lo( + c0_hi, c0_lo, + c1_hi, c1_lo, + c2_hi, c2_lo, + c3_hi, c3_lo, + c4_hi, c4_lo); + + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + + var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); + + hh = gh; + hl = gl; + + gh = fh; + gl = fl; + + fh = eh; + fl = el; + + eh = sum64_hi(dh, dl, T1_hi, T1_lo); + el = sum64_lo(dl, dl, T1_hi, T1_lo); + + dh = ch; + dl = cl; + + ch = bh; + cl = bl; + + bh = ah; + bl = al; + + ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); + } + + sum64(this.h, 0, ah, al); + sum64(this.h, 2, bh, bl); + sum64(this.h, 4, ch, cl); + sum64(this.h, 6, dh, dl); + sum64(this.h, 8, eh, el); + sum64(this.h, 10, fh, fl); + sum64(this.h, 12, gh, gl); + sum64(this.h, 14, hh, hl); +}; + +SHA512.prototype._digest = function digest(enc) { + if (enc === 'hex') + return utils.toHex32(this.h, 'big'); + else + return utils.split32(this.h, 'big'); +}; + +function ch64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ ((~xh) & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ ((~xl) & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_hi(xh, xl, yh, yl, zh) { + var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); + if (r < 0) + r += 0x100000000; + return r; +} + +function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 28); + var c1_hi = rotr64_hi(xl, xh, 2); // 34 + var c2_hi = rotr64_hi(xl, xh, 7); // 39 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 28); + var c1_lo = rotr64_lo(xl, xh, 2); // 34 + var c2_lo = rotr64_lo(xl, xh, 7); // 39 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 14); + var c1_hi = rotr64_hi(xh, xl, 18); + var c2_hi = rotr64_hi(xl, xh, 9); // 41 + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 14); + var c1_lo = rotr64_lo(xh, xl, 18); + var c2_lo = rotr64_lo(xl, xh, 9); // 41 + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 1); + var c1_hi = rotr64_hi(xh, xl, 8); + var c2_hi = shr64_hi(xh, xl, 7); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 1); + var c1_lo = rotr64_lo(xh, xl, 8); + var c2_lo = shr64_lo(xh, xl, 7); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi(xh, xl, 19); + var c1_hi = rotr64_hi(xl, xh, 29); // 61 + var c2_hi = shr64_hi(xh, xl, 6); + + var r = c0_hi ^ c1_hi ^ c2_hi; + if (r < 0) + r += 0x100000000; + return r; +} + +function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo(xh, xl, 19); + var c1_lo = rotr64_lo(xl, xh, 29); // 61 + var c2_lo = shr64_lo(xh, xl, 6); + + var r = c0_lo ^ c1_lo ^ c2_lo; + if (r < 0) + r += 0x100000000; + return r; +} + +},{"../common":88,"../utils":98,"minimalistic-assert":106}],97:[function(require,module,exports){ +'use strict'; + +var utils = require('../utils'); +var rotr32 = utils.rotr32; + +function ft_1(s, x, y, z) { + if (s === 0) + return ch32(x, y, z); + if (s === 1 || s === 3) + return p32(x, y, z); + if (s === 2) + return maj32(x, y, z); +} +exports.ft_1 = ft_1; + +function ch32(x, y, z) { + return (x & y) ^ ((~x) & z); +} +exports.ch32 = ch32; + +function maj32(x, y, z) { + return (x & y) ^ (x & z) ^ (y & z); +} +exports.maj32 = maj32; + +function p32(x, y, z) { + return x ^ y ^ z; +} +exports.p32 = p32; + +function s0_256(x) { + return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); +} +exports.s0_256 = s0_256; + +function s1_256(x) { + return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); +} +exports.s1_256 = s1_256; + +function g0_256(x) { + return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); +} +exports.g0_256 = g0_256; + +function g1_256(x) { + return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); +} +exports.g1_256 = g1_256; + +},{"../utils":98}],98:[function(require,module,exports){ +'use strict'; + +var assert = require('minimalistic-assert'); +var inherits = require('inherits'); + +exports.inherits = inherits; + +function isSurrogatePair(msg, i) { + if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { + return false; + } + if (i < 0 || i + 1 >= msg.length) { + return false; + } + return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; +} + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg === 'string') { + if (!enc) { + // Inspired by stringToUtf8ByteArray() in closure-library by Google + // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 + // Apache License 2.0 + // https://github.com/google/closure-library/blob/master/LICENSE + var p = 0; + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + if (c < 128) { + res[p++] = c; + } else if (c < 2048) { + res[p++] = (c >> 6) | 192; + res[p++] = (c & 63) | 128; + } else if (isSurrogatePair(msg, i)) { + c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); + res[p++] = (c >> 18) | 240; + res[p++] = ((c >> 12) & 63) | 128; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } else { + res[p++] = (c >> 12) | 224; + res[p++] = ((c >> 6) & 63) | 128; + res[p++] = (c & 63) | 128; + } + } + } else if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for (i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + } + return res; +} +exports.toArray = toArray; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +exports.toHex = toHex; + +function htonl(w) { + var res = (w >>> 24) | + ((w >>> 8) & 0xff00) | + ((w << 8) & 0xff0000) | + ((w & 0xff) << 24); + return res >>> 0; +} +exports.htonl = htonl; + +function toHex32(msg, endian) { + var res = ''; + for (var i = 0; i < msg.length; i++) { + var w = msg[i]; + if (endian === 'little') + w = htonl(w); + res += zero8(w.toString(16)); + } + return res; +} +exports.toHex32 = toHex32; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +exports.zero2 = zero2; + +function zero8(word) { + if (word.length === 7) + return '0' + word; + else if (word.length === 6) + return '00' + word; + else if (word.length === 5) + return '000' + word; + else if (word.length === 4) + return '0000' + word; + else if (word.length === 3) + return '00000' + word; + else if (word.length === 2) + return '000000' + word; + else if (word.length === 1) + return '0000000' + word; + else + return word; +} +exports.zero8 = zero8; + +function join32(msg, start, end, endian) { + var len = end - start; + assert(len % 4 === 0); + var res = new Array(len / 4); + for (var i = 0, k = start; i < res.length; i++, k += 4) { + var w; + if (endian === 'big') + w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; + else + w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; + res[i] = w >>> 0; + } + return res; +} +exports.join32 = join32; + +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for (var i = 0, k = 0; i < msg.length; i++, k += 4) { + var m = msg[i]; + if (endian === 'big') { + res[k] = m >>> 24; + res[k + 1] = (m >>> 16) & 0xff; + res[k + 2] = (m >>> 8) & 0xff; + res[k + 3] = m & 0xff; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = (m >>> 16) & 0xff; + res[k + 1] = (m >>> 8) & 0xff; + res[k] = m & 0xff; + } + } + return res; +} +exports.split32 = split32; + +function rotr32(w, b) { + return (w >>> b) | (w << (32 - b)); +} +exports.rotr32 = rotr32; + +function rotl32(w, b) { + return (w << b) | (w >>> (32 - b)); +} +exports.rotl32 = rotl32; + +function sum32(a, b) { + return (a + b) >>> 0; +} +exports.sum32 = sum32; + +function sum32_3(a, b, c) { + return (a + b + c) >>> 0; +} +exports.sum32_3 = sum32_3; + +function sum32_4(a, b, c, d) { + return (a + b + c + d) >>> 0; +} +exports.sum32_4 = sum32_4; + +function sum32_5(a, b, c, d, e) { + return (a + b + c + d + e) >>> 0; +} +exports.sum32_5 = sum32_5; + +function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; +} +exports.sum64 = sum64; + +function sum64_hi(ah, al, bh, bl) { + var lo = (al + bl) >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; +} +exports.sum64_hi = sum64_hi; + +function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; +} +exports.sum64_lo = sum64_lo; + +function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; +} +exports.sum64_4_hi = sum64_4_hi; + +function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; +} +exports.sum64_4_lo = sum64_4_lo; + +function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = (lo + bl) >>> 0; + carry += lo < al ? 1 : 0; + lo = (lo + cl) >>> 0; + carry += lo < cl ? 1 : 0; + lo = (lo + dl) >>> 0; + carry += lo < dl ? 1 : 0; + lo = (lo + el) >>> 0; + carry += lo < el ? 1 : 0; + + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; +} +exports.sum64_5_hi = sum64_5_hi; + +function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + + return lo >>> 0; +} +exports.sum64_5_lo = sum64_5_lo; + +function rotr64_hi(ah, al, num) { + var r = (al << (32 - num)) | (ah >>> num); + return r >>> 0; +} +exports.rotr64_hi = rotr64_hi; + +function rotr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.rotr64_lo = rotr64_lo; + +function shr64_hi(ah, al, num) { + return ah >>> num; +} +exports.shr64_hi = shr64_hi; + +function shr64_lo(ah, al, num) { + var r = (ah << (32 - num)) | (al >>> num); + return r >>> 0; +} +exports.shr64_lo = shr64_lo; + +},{"inherits":101,"minimalistic-assert":106}],99:[function(require,module,exports){ +'use strict'; + +var hash = require('hash.js'); +var utils = require('minimalistic-crypto-utils'); +var assert = require('minimalistic-assert'); + +function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) + return new HmacDRBG(options); + this.hash = options.hash; + this.predResist = !!options.predResist; + + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; + + this._reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + + var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); + var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); + var pers = utils.toArray(options.pers, options.persEnc || 'hex'); + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + this._init(entropy, nonce, pers); +} +module.exports = HmacDRBG; + +HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for (var i = 0; i < this.V.length; i++) { + this.K[i] = 0x00; + this.V[i] = 0x01; + } + + this._update(seed); + this._reseed = 1; + this.reseedInterval = 0x1000000000000; // 2^48 +}; + +HmacDRBG.prototype._hmac = function hmac() { + return new hash.hmac(this.hash, this.K); +}; + +HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac() + .update(this.V) + .update([ 0x00 ]); + if (seed) + kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) + return; + + this.K = this._hmac() + .update(this.V) + .update([ 0x01 ]) + .update(seed) + .digest(); + this.V = this._hmac().update(this.V).digest(); +}; + +HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { + // Optional entropy enc + if (typeof entropyEnc !== 'string') { + addEnc = add; + add = entropyEnc; + entropyEnc = null; + } + + entropy = utils.toArray(entropy, entropyEnc); + add = utils.toArray(add, addEnc); + + assert(entropy.length >= (this.minEntropy / 8), + 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); + + this._update(entropy.concat(add || [])); + this._reseed = 1; +}; + +HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { + if (this._reseed > this.reseedInterval) + throw new Error('Reseed is required'); + + // Optional encoding + if (typeof enc !== 'string') { + addEnc = add; + add = enc; + enc = null; + } + + // Optional additional data + if (add) { + add = utils.toArray(add, addEnc || 'hex'); + this._update(add); + } + + var temp = []; + while (temp.length < len) { + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + + var res = temp.slice(0, len); + this._update(add); + this._reseed++; + return utils.encode(res, enc); +}; + +},{"hash.js":87,"minimalistic-assert":106,"minimalistic-crypto-utils":107}],100:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],101:[function(require,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 + } +} + +},{}],102:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +},{}],103:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],104:[function(require,module,exports){ +'use strict' +var inherits = require('inherits') +var HashBase = require('hash-base') +var Buffer = require('safe-buffer').Buffer + +var ARRAY16 = new Array(16) + +function MD5 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 +} + +inherits(MD5, HashBase) + +MD5.prototype._update = function () { + var M = ARRAY16 + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) + + var a = this._a + var b = this._b + var c = this._c + var d = this._d + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) + c = fnF(c, d, a, b, M[2], 0x242070db, 17) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 +} + +MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.allocUnsafe(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 +} + +function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 +} + +function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 +} + +function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 +} + +module.exports = MD5 + +},{"hash-base":86,"inherits":101,"safe-buffer":142}],105:[function(require,module,exports){ +var bn = require('bn.js'); +var brorand = require('brorand'); + +function MillerRabin(rand) { + this.rand = rand || new brorand.Rand(); +} +module.exports = MillerRabin; + +MillerRabin.create = function create(rand) { + return new MillerRabin(rand); +}; + +MillerRabin.prototype._randbelow = function _randbelow(n) { + var len = n.bitLength(); + var min_bytes = Math.ceil(len / 8); + + // Generage random bytes until a number less than n is found. + // This ensures that 0..n-1 have an equal probability of being selected. + do + var a = new bn(this.rand.generate(min_bytes)); + while (a.cmp(n) >= 0); + + return a; +}; + +MillerRabin.prototype._randrange = function _randrange(start, stop) { + // Generate a random number greater than or equal to start and less than stop. + var size = stop.sub(start); + return start.add(this._randbelow(size)); +}; + +MillerRabin.prototype.test = function test(n, k, cb) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + var prime = true; + for (; k > 0; k--) { + var a = this._randrange(new bn(2), n1); + if (cb) + cb(a); + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return false; + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) + return false; + } + + return prime; +}; + +MillerRabin.prototype.getDivisor = function getDivisor(n, k) { + var len = n.bitLength(); + var red = bn.mont(n); + var rone = new bn(1).toRed(red); + + if (!k) + k = Math.max(1, (len / 48) | 0); + + // Find d and s, (n - 1) = (2 ^ s) * d; + var n1 = n.subn(1); + for (var s = 0; !n1.testn(s); s++) {} + var d = n.shrn(s); + + var rn1 = n1.toRed(red); + + for (; k > 0; k--) { + var a = this._randrange(new bn(2), n1); + + var g = n.gcd(a); + if (g.cmpn(1) !== 0) + return g; + + var x = a.toRed(red).redPow(d); + if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) + continue; + + for (var i = 1; i < s; i++) { + x = x.redSqr(); + + if (x.cmp(rone) === 0) + return x.fromRed().subn(1).gcd(n); + if (x.cmp(rn1) === 0) + break; + } + + if (i === s) { + x = x.redSqr(); + return x.fromRed().subn(1).gcd(n); + } + } + + return false; +}; + +},{"bn.js":16,"brorand":17}],106:[function(require,module,exports){ +module.exports = assert; + +function assert(val, msg) { + if (!val) + throw new Error(msg || 'Assertion failed'); +} + +assert.equal = function assertEqual(l, r, msg) { + if (l != r) + throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); +}; + +},{}],107:[function(require,module,exports){ +'use strict'; + +var utils = exports; + +function toArray(msg, enc) { + if (Array.isArray(msg)) + return msg.slice(); + if (!msg) + return []; + var res = []; + if (typeof msg !== 'string') { + for (var i = 0; i < msg.length; i++) + res[i] = msg[i] | 0; + return res; + } + if (enc === 'hex') { + msg = msg.replace(/[^a-z0-9]+/ig, ''); + if (msg.length % 2 !== 0) + msg = '0' + msg; + for (var i = 0; i < msg.length; i += 2) + res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for (var i = 0; i < msg.length; i++) { + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 0xff; + if (hi) + res.push(hi, lo); + else + res.push(lo); + } + } + return res; +} +utils.toArray = toArray; + +function zero2(word) { + if (word.length === 1) + return '0' + word; + else + return word; +} +utils.zero2 = zero2; + +function toHex(msg) { + var res = ''; + for (var i = 0; i < msg.length; i++) + res += zero2(msg[i].toString(16)); + return res; +} +utils.toHex = toHex; + +utils.encode = function encode(arr, enc) { + if (enc === 'hex') + return toHex(arr); + else + return arr; +}; + +},{}],108:[function(require,module,exports){ +module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", +"2.16.840.1.101.3.4.1.2": "aes-128-cbc", +"2.16.840.1.101.3.4.1.3": "aes-128-ofb", +"2.16.840.1.101.3.4.1.4": "aes-128-cfb", +"2.16.840.1.101.3.4.1.21": "aes-192-ecb", +"2.16.840.1.101.3.4.1.22": "aes-192-cbc", +"2.16.840.1.101.3.4.1.23": "aes-192-ofb", +"2.16.840.1.101.3.4.1.24": "aes-192-cfb", +"2.16.840.1.101.3.4.1.41": "aes-256-ecb", +"2.16.840.1.101.3.4.1.42": "aes-256-cbc", +"2.16.840.1.101.3.4.1.43": "aes-256-ofb", +"2.16.840.1.101.3.4.1.44": "aes-256-cfb" +} +},{}],109:[function(require,module,exports){ +// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js +// Fedor, you are amazing. +'use strict' + +var asn1 = require('asn1.js') + +exports.certificate = require('./certificate') + +var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('modulus').int(), + this.key('publicExponent').int(), + this.key('privateExponent').int(), + this.key('prime1').int(), + this.key('prime2').int(), + this.key('exponent1').int(), + this.key('exponent2').int(), + this.key('coefficient').int() + ) +}) +exports.RSAPrivateKey = RSAPrivateKey + +var RSAPublicKey = asn1.define('RSAPublicKey', function () { + this.seq().obj( + this.key('modulus').int(), + this.key('publicExponent').int() + ) +}) +exports.RSAPublicKey = RSAPublicKey + +var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ) +}) +exports.PublicKey = PublicKey + +var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('none').null_().optional(), + this.key('curve').objid().optional(), + this.key('params').seq().obj( + this.key('p').int(), + this.key('q').int(), + this.key('g').int() + ).optional() + ) +}) + +var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { + this.seq().obj( + this.key('version').int(), + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPrivateKey').octstr() + ) +}) +exports.PrivateKey = PrivateKeyInfo +var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { + this.seq().obj( + this.key('algorithm').seq().obj( + this.key('id').objid(), + this.key('decrypt').seq().obj( + this.key('kde').seq().obj( + this.key('id').objid(), + this.key('kdeparams').seq().obj( + this.key('salt').octstr(), + this.key('iters').int() + ) + ), + this.key('cipher').seq().obj( + this.key('algo').objid(), + this.key('iv').octstr() + ) + ) + ), + this.key('subjectPrivateKey').octstr() + ) +}) + +exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo + +var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('p').int(), + this.key('q').int(), + this.key('g').int(), + this.key('pub_key').int(), + this.key('priv_key').int() + ) +}) +exports.DSAPrivateKey = DSAPrivateKey + +exports.DSAparam = asn1.define('DSAparam', function () { + this.int() +}) + +var ECPrivateKey = asn1.define('ECPrivateKey', function () { + this.seq().obj( + this.key('version').int(), + this.key('privateKey').octstr(), + this.key('parameters').optional().explicit(0).use(ECParameters), + this.key('publicKey').optional().explicit(1).bitstr() + ) +}) +exports.ECPrivateKey = ECPrivateKey + +var ECParameters = asn1.define('ECParameters', function () { + this.choice({ + namedCurve: this.objid() + }) +}) + +exports.signature = asn1.define('signature', function () { + this.seq().obj( + this.key('r').int(), + this.key('s').int() + ) +}) + +},{"./certificate":110,"asn1.js":1}],110:[function(require,module,exports){ +// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js +// thanks to @Rantanen + +'use strict' + +var asn = require('asn1.js') + +var Time = asn.define('Time', function () { + this.choice({ + utcTime: this.utctime(), + generalTime: this.gentime() + }) +}) + +var AttributeTypeValue = asn.define('AttributeTypeValue', function () { + this.seq().obj( + this.key('type').objid(), + this.key('value').any() + ) +}) + +var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { + this.seq().obj( + this.key('algorithm').objid(), + this.key('parameters').optional(), + this.key('curve').objid().optional() + ) +}) + +var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { + this.seq().obj( + this.key('algorithm').use(AlgorithmIdentifier), + this.key('subjectPublicKey').bitstr() + ) +}) + +var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { + this.setof(AttributeTypeValue) +}) + +var RDNSequence = asn.define('RDNSequence', function () { + this.seqof(RelativeDistinguishedName) +}) + +var Name = asn.define('Name', function () { + this.choice({ + rdnSequence: this.use(RDNSequence) + }) +}) + +var Validity = asn.define('Validity', function () { + this.seq().obj( + this.key('notBefore').use(Time), + this.key('notAfter').use(Time) + ) +}) + +var Extension = asn.define('Extension', function () { + this.seq().obj( + this.key('extnID').objid(), + this.key('critical').bool().def(false), + this.key('extnValue').octstr() + ) +}) + +var TBSCertificate = asn.define('TBSCertificate', function () { + this.seq().obj( + this.key('version').explicit(0).int().optional(), + this.key('serialNumber').int(), + this.key('signature').use(AlgorithmIdentifier), + this.key('issuer').use(Name), + this.key('validity').use(Validity), + this.key('subject').use(Name), + this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), + this.key('issuerUniqueID').implicit(1).bitstr().optional(), + this.key('subjectUniqueID').implicit(2).bitstr().optional(), + this.key('extensions').explicit(3).seqof(Extension).optional() + ) +}) + +var X509Certificate = asn.define('X509Certificate', function () { + this.seq().obj( + this.key('tbsCertificate').use(TBSCertificate), + this.key('signatureAlgorithm').use(AlgorithmIdentifier), + this.key('signatureValue').bitstr() + ) +}) + +module.exports = X509Certificate + +},{"asn1.js":1}],111:[function(require,module,exports){ +// adapted from https://github.com/apatil/pemstrip +var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r\+\/\=]+)[\n\r]+/m +var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m +var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r\+\/\=]+)-----END \1-----$/m +var evp = require('evp_bytestokey') +var ciphers = require('browserify-aes') +var Buffer = require('safe-buffer').Buffer +module.exports = function (okey, password) { + var key = okey.toString() + var match = key.match(findProc) + var decrypted + if (!match) { + var match2 = key.match(fullRegex) + decrypted = new Buffer(match2[2].replace(/[\r\n]/g, ''), 'base64') + } else { + var suite = 'aes' + match[1] + var iv = Buffer.from(match[2], 'hex') + var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64') + var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key + var out = [] + var cipher = ciphers.createDecipheriv(suite, cipherKey, iv) + out.push(cipher.update(cipherText)) + out.push(cipher.final()) + decrypted = Buffer.concat(out) + } + var tag = key.match(startRegex)[1] + return { + tag: tag, + data: decrypted + } +} + +},{"browserify-aes":21,"evp_bytestokey":83,"safe-buffer":142}],112:[function(require,module,exports){ +var asn1 = require('./asn1') +var aesid = require('./aesid.json') +var fixProc = require('./fixProc') +var ciphers = require('browserify-aes') +var compat = require('pbkdf2') +var Buffer = require('safe-buffer').Buffer +module.exports = parseKeys + +function parseKeys (buffer) { + var password + if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { + password = buffer.passphrase + buffer = buffer.key + } + if (typeof buffer === 'string') { + buffer = Buffer.from(buffer) + } + + var stripped = fixProc(buffer, password) + + var type = stripped.tag + var data = stripped.data + var subtype, ndata + switch (type) { + case 'CERTIFICATE': + ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo + // falls through + case 'PUBLIC KEY': + if (!ndata) { + ndata = asn1.PublicKey.decode(data, 'der') + } + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der') + case '1.2.840.10045.2.1': + ndata.subjectPrivateKey = ndata.subjectPublicKey + return { + type: 'ec', + data: ndata + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der') + return { + type: 'dsa', + data: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'ENCRYPTED PRIVATE KEY': + data = asn1.EncryptedPrivateKey.decode(data, 'der') + data = decrypt(data, password) + // falls through + case 'PRIVATE KEY': + ndata = asn1.PrivateKey.decode(data, 'der') + subtype = ndata.algorithm.algorithm.join('.') + switch (subtype) { + case '1.2.840.113549.1.1.1': + return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der') + case '1.2.840.10045.2.1': + return { + curve: ndata.algorithm.curve, + privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey + } + case '1.2.840.10040.4.1': + ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der') + return { + type: 'dsa', + params: ndata.algorithm.params + } + default: throw new Error('unknown key id ' + subtype) + } + throw new Error('unknown key type ' + type) + case 'RSA PUBLIC KEY': + return asn1.RSAPublicKey.decode(data, 'der') + case 'RSA PRIVATE KEY': + return asn1.RSAPrivateKey.decode(data, 'der') + case 'DSA PRIVATE KEY': + return { + type: 'dsa', + params: asn1.DSAPrivateKey.decode(data, 'der') + } + case 'EC PRIVATE KEY': + data = asn1.ECPrivateKey.decode(data, 'der') + return { + curve: data.parameters.value, + privateKey: data.privateKey + } + default: throw new Error('unknown key type ' + type) + } +} +parseKeys.signature = asn1.signature +function decrypt (data, password) { + var salt = data.algorithm.decrypt.kde.kdeparams.salt + var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10) + var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')] + var iv = data.algorithm.decrypt.cipher.iv + var cipherText = data.subjectPrivateKey + var keylen = parseInt(algo.split('-')[1], 10) / 8 + var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1') + var cipher = ciphers.createDecipheriv(algo, key, iv) + var out = [] + out.push(cipher.update(cipherText)) + out.push(cipher.final()) + return Buffer.concat(out) +} + +},{"./aesid.json":108,"./asn1":109,"./fixProc":111,"browserify-aes":21,"pbkdf2":113,"safe-buffer":142}],113:[function(require,module,exports){ +exports.pbkdf2 = require('./lib/async') +exports.pbkdf2Sync = require('./lib/sync') + +},{"./lib/async":114,"./lib/sync":117}],114:[function(require,module,exports){ +(function (process,global){ +var checkParameters = require('./precondition') +var defaultEncoding = require('./default-encoding') +var sync = require('./sync') +var Buffer = require('safe-buffer').Buffer + +var ZERO_BUF +var subtle = global.crypto && global.crypto.subtle +var toBrowser = { + 'sha': 'SHA-1', + 'sha-1': 'SHA-1', + 'sha1': 'SHA-1', + 'sha256': 'SHA-256', + 'sha-256': 'SHA-256', + 'sha384': 'SHA-384', + 'sha-384': 'SHA-384', + 'sha-512': 'SHA-512', + 'sha512': 'SHA-512' +} +var checks = [] +function checkNative (algo) { + if (global.process && !global.process.browser) { + return Promise.resolve(false) + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false) + } + if (checks[algo] !== undefined) { + return checks[algo] + } + ZERO_BUF = ZERO_BUF || Buffer.alloc(8) + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) + .then(function () { + return true + }).catch(function () { + return false + }) + checks[algo] = prom + return prom +} + +function browserPbkdf2 (password, salt, iterations, length, algo) { + return subtle.importKey( + 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits'] + ).then(function (key) { + return subtle.deriveBits({ + name: 'PBKDF2', + salt: salt, + iterations: iterations, + hash: { + name: algo + } + }, key, length << 3) + }).then(function (res) { + return Buffer.from(res) + }) +} + +function resolvePromise (promise, callback) { + promise.then(function (out) { + process.nextTick(function () { + callback(null, out) + }) + }, function (e) { + process.nextTick(function () { + callback(e) + }) + }) +} +module.exports = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } + + digest = digest || 'sha1' + var algo = toBrowser[digest.toLowerCase()] + + if (!algo || typeof global.Promise !== 'function') { + return process.nextTick(function () { + var out + try { + out = sync(password, salt, iterations, keylen, digest) + } catch (e) { + return callback(e) + } + callback(null, out) + }) + } + + checkParameters(password, salt, iterations, keylen) + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) + + resolvePromise(checkNative(algo).then(function (resp) { + if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo) + + return sync(password, salt, iterations, keylen, digest) + }), callback) +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./default-encoding":115,"./precondition":116,"./sync":117,"_process":119,"safe-buffer":142}],115:[function(require,module,exports){ +(function (process){ +var defaultEncoding +/* istanbul ignore next */ +if (process.browser) { + defaultEncoding = 'utf-8' +} else { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) + + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' +} +module.exports = defaultEncoding + +}).call(this,require('_process')) +},{"_process":119}],116:[function(require,module,exports){ +(function (Buffer){ +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs + +function checkBuffer (buf, name) { + if (typeof buf !== 'string' && !Buffer.isBuffer(buf)) { + throw new TypeError(name + ' must be a buffer or string') + } +} + +module.exports = function (password, salt, iterations, keylen) { + checkBuffer(password, 'Password') + checkBuffer(salt, 'Salt') + + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } + + if (iterations < 0) { + throw new TypeError('Bad iterations') + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } + + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length') + } +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":102}],117:[function(require,module,exports){ +var md5 = require('create-hash/md5') +var RIPEMD160 = require('ripemd160') +var sha = require('sha.js') + +var checkParameters = require('./precondition') +var defaultEncoding = require('./default-encoding') +var Buffer = require('safe-buffer').Buffer +var ZEROS = Buffer.alloc(128) +var sizes = { + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + rmd160: 20, + ripemd160: 20 +} + +function Hmac (alg, key, saltLen) { + var hash = getDigest(alg) + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + if (key.length > blocksize) { + key = hash(key) + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) + var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) + ipad.copy(ipad1, 0, 0, blocksize) + this.ipad1 = ipad1 + this.ipad2 = ipad + this.opad = opad + this.alg = alg + this.blocksize = blocksize + this.hash = hash + this.size = sizes[alg] +} + +Hmac.prototype.run = function (data, ipad) { + data.copy(ipad, this.blocksize) + var h = this.hash(ipad) + h.copy(this.opad, this.blocksize) + return this.hash(this.opad) +} + +function getDigest (alg) { + function shaFunc (data) { + return sha(alg).update(data).digest() + } + function rmd160Func (data) { + return new RIPEMD160().update(data).digest() + } + + if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func + if (alg === 'md5') return md5 + return shaFunc +} + +function pbkdf2 (password, salt, iterations, keylen, digest) { + checkParameters(password, salt, iterations, keylen) + + if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) + + digest = digest || 'sha1' + + var hmac = new Hmac(digest, password, salt.length) + + var DK = Buffer.allocUnsafe(keylen) + var block1 = Buffer.allocUnsafe(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + + var destPos = 0 + var hLen = sizes[digest] + var l = Math.ceil(keylen / hLen) + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + + var T = hmac.run(block1, hmac.ipad1) + var U = T + + for (var j = 1; j < iterations; j++) { + U = hmac.run(U, hmac.ipad2) + for (var k = 0; k < hLen; k++) T[k] ^= U[k] + } + + T.copy(DK, destPos) + destPos += hLen + } + + return DK +} + +module.exports = pbkdf2 + +},{"./default-encoding":115,"./precondition":116,"create-hash/md5":52,"ripemd160":141,"safe-buffer":142,"sha.js":144}],118:[function(require,module,exports){ +(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: nextTick }; +} else { + module.exports = process +} + +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); + }); + } +} + + +}).call(this,require('_process')) +},{"_process":119}],119:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; } - curr[0] = element; - }; - SymbolTree.prototype.getDefault = function (path, mkDefaultElement, max) { - return this.get(path, mkDefaultElement, max); - }; - /** - * Returns the payload of the path - * If a default element creator is given, it will insert it at the path - */ - SymbolTree.prototype.get = function (path, mkDefaultElement, max) { - var curr = this.tree; - var _max = max !== undefined ? max : path.length; - for (var i = 0; i < _max; i++) { - var n = this.mapper(path[i]); - var child = curr[1][n]; - if (!child) { - if (mkDefaultElement) { - child = [undefined, {}]; - curr[1][n] = child; - } - else { - return undefined; - } - } - curr = child; + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; } - if (mkDefaultElement && !curr[0]) { - curr[0] = mkDefaultElement(); + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); } - return curr[0]; - }; - SymbolTree.prototype.delete = function (path) { - var curr = this.tree; - for (var i = 0; i < path.length - 1; i++) { - var child = curr[1][this.mapper(path[i])]; - if (!child) { - return; - } - curr = child; + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); } - delete curr[1][this.mapper(path[path.length - 1])]; - }; - return SymbolTree; -}()); -exports.default = SymbolTree; - -},{}],11:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var vnode_1 = require("snabbdom/vnode"); -var h_1 = require("snabbdom/h"); -var snabbdom_selector_1 = require("snabbdom-selector"); -var utils_1 = require("./utils"); -var VNodeWrapper = /** @class */ (function () { - function VNodeWrapper(rootElement) { - this.rootElement = rootElement; - } - VNodeWrapper.prototype.call = function (vnode) { - if (utils_1.isDocFrag(this.rootElement)) { - return this.wrapDocFrag(vnode === null ? [] : [vnode]); + } + + + +} +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 = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } } - if (vnode === null) { - return this.wrap([]); + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(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]; } - var _a = snabbdom_selector_1.selectorParser(vnode), selTagName = _a.tagName, selId = _a.id; - var vNodeClassName = snabbdom_selector_1.classNameFromVNode(vnode); - var vNodeData = vnode.data || {}; - var vNodeDataProps = vNodeData.props || {}; - var _b = vNodeDataProps.id, vNodeId = _b === void 0 ? selId : _b; - var isVNodeAndRootElementIdentical = typeof vNodeId === 'string' && - vNodeId.toUpperCase() === this.rootElement.id.toUpperCase() && - selTagName.toUpperCase() === this.rootElement.tagName.toUpperCase() && - vNodeClassName.toUpperCase() === this.rootElement.className.toUpperCase(); - if (isVNodeAndRootElementIdentical) { - return vnode; + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// 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.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +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; }; + +},{}],120:[function(require,module,exports){ +exports.publicEncrypt = require('./publicEncrypt') +exports.privateDecrypt = require('./privateDecrypt') + +exports.privateEncrypt = function privateEncrypt (key, buf) { + return exports.publicEncrypt(key, buf, true) +} + +exports.publicDecrypt = function publicDecrypt (key, buf) { + return exports.privateDecrypt(key, buf, true) +} + +},{"./privateDecrypt":122,"./publicEncrypt":123}],121:[function(require,module,exports){ +var createHash = require('create-hash') +var Buffer = require('safe-buffer').Buffer + +module.exports = function (seed, len) { + var t = Buffer.alloc(0) + var i = 0 + var c + while (t.length < len) { + c = i2ops(i++) + t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]) + } + return t.slice(0, len) +} + +function i2ops (c) { + var out = Buffer.allocUnsafe(4) + out.writeUInt32BE(c, 0) + return out +} + +},{"create-hash":51,"safe-buffer":142}],122:[function(require,module,exports){ +var parseKeys = require('parse-asn1') +var mgf = require('./mgf') +var xor = require('./xor') +var BN = require('bn.js') +var crt = require('browserify-rsa') +var createHash = require('create-hash') +var withPublic = require('./withPublic') +var Buffer = require('safe-buffer').Buffer + +module.exports = function privateDecrypt (privateKey, enc, reverse) { + var padding + if (privateKey.padding) { + padding = privateKey.padding + } else if (reverse) { + padding = 1 + } else { + padding = 4 + } + + var key = parseKeys(privateKey) + var k = key.modulus.byteLength() + if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) { + throw new Error('decryption error') + } + var msg + if (reverse) { + msg = withPublic(new BN(enc), key) + } else { + msg = crt(enc, key) + } + var zBuffer = Buffer.alloc(k - msg.length) + msg = Buffer.concat([zBuffer, msg], k) + if (padding === 4) { + return oaep(key, msg) + } else if (padding === 1) { + return pkcs1(key, msg, reverse) + } else if (padding === 3) { + return msg + } else { + throw new Error('unknown padding') + } +} + +function oaep (key, msg) { + var k = key.modulus.byteLength() + var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() + var hLen = iHash.length + if (msg[0] !== 0) { + throw new Error('decryption error') + } + var maskedSeed = msg.slice(1, hLen + 1) + var maskedDb = msg.slice(hLen + 1) + var seed = xor(maskedSeed, mgf(maskedDb, hLen)) + var db = xor(maskedDb, mgf(seed, k - hLen - 1)) + if (compare(iHash, db.slice(0, hLen))) { + throw new Error('decryption error') + } + var i = hLen + while (db[i] === 0) { + i++ + } + if (db[i++] !== 1) { + throw new Error('decryption error') + } + return db.slice(i) +} + +function pkcs1 (key, msg, reverse) { + var p1 = msg.slice(0, 2) + var i = 2 + var status = 0 + while (msg[i++] !== 0) { + if (i >= msg.length) { + status++ + break + } + } + var ps = msg.slice(2, i - 1) + + if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) { + status++ + } + if (ps.length < 8) { + status++ + } + if (status) { + throw new Error('decryption error') + } + return msg.slice(i) +} +function compare (a, b) { + a = Buffer.from(a) + b = Buffer.from(b) + var dif = 0 + var len = a.length + if (a.length !== b.length) { + dif++ + len = Math.min(a.length, b.length) + } + var i = -1 + while (++i < len) { + dif += (a[i] ^ b[i]) + } + return dif +} + +},{"./mgf":121,"./withPublic":124,"./xor":125,"bn.js":16,"browserify-rsa":39,"create-hash":51,"parse-asn1":112,"safe-buffer":142}],123:[function(require,module,exports){ +var parseKeys = require('parse-asn1') +var randomBytes = require('randombytes') +var createHash = require('create-hash') +var mgf = require('./mgf') +var xor = require('./xor') +var BN = require('bn.js') +var withPublic = require('./withPublic') +var crt = require('browserify-rsa') +var Buffer = require('safe-buffer').Buffer + +module.exports = function publicEncrypt (publicKey, msg, reverse) { + var padding + if (publicKey.padding) { + padding = publicKey.padding + } else if (reverse) { + padding = 1 + } else { + padding = 4 + } + var key = parseKeys(publicKey) + var paddedMsg + if (padding === 4) { + paddedMsg = oaep(key, msg) + } else if (padding === 1) { + paddedMsg = pkcs1(key, msg, reverse) + } else if (padding === 3) { + paddedMsg = new BN(msg) + if (paddedMsg.cmp(key.modulus) >= 0) { + throw new Error('data too long for modulus') + } + } else { + throw new Error('unknown padding') + } + if (reverse) { + return crt(paddedMsg, key) + } else { + return withPublic(paddedMsg, key) + } +} + +function oaep (key, msg) { + var k = key.modulus.byteLength() + var mLen = msg.length + var iHash = createHash('sha1').update(Buffer.alloc(0)).digest() + var hLen = iHash.length + var hLen2 = 2 * hLen + if (mLen > k - hLen2 - 2) { + throw new Error('message too long') + } + var ps = Buffer.alloc(k - mLen - hLen2 - 2) + var dblen = k - hLen - 1 + var seed = randomBytes(hLen) + var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen)) + var maskedSeed = xor(seed, mgf(maskedDb, hLen)) + return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k)) +} +function pkcs1 (key, msg, reverse) { + var mLen = msg.length + var k = key.modulus.byteLength() + if (mLen > k - 11) { + throw new Error('message too long') + } + var ps + if (reverse) { + ps = Buffer.alloc(k - mLen - 3, 0xff) + } else { + ps = nonZero(k - mLen - 3) + } + return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k)) +} +function nonZero (len) { + var out = Buffer.allocUnsafe(len) + var i = 0 + var cache = randomBytes(len * 2) + var cur = 0 + var num + while (i < len) { + if (cur === cache.length) { + cache = randomBytes(len * 2) + cur = 0 + } + num = cache[cur++] + if (num) { + out[i++] = num + } + } + return out +} + +},{"./mgf":121,"./withPublic":124,"./xor":125,"bn.js":16,"browserify-rsa":39,"create-hash":51,"parse-asn1":112,"randombytes":126,"safe-buffer":142}],124:[function(require,module,exports){ +var BN = require('bn.js') +var Buffer = require('safe-buffer').Buffer + +function withPublic (paddedMsg, key) { + return Buffer.from(paddedMsg + .toRed(BN.mont(key.modulus)) + .redPow(new BN(key.publicExponent)) + .fromRed() + .toArray()) +} + +module.exports = withPublic + +},{"bn.js":16,"safe-buffer":142}],125:[function(require,module,exports){ +module.exports = function xor (a, b) { + var len = a.length + var i = -1 + while (++i < len) { + a[i] ^= b[i] + } + return a +} + +},{}],126:[function(require,module,exports){ +(function (process,global){ +'use strict' + +// limit of Crypto.getRandomValues() +// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues +var MAX_BYTES = 65536 + +// Node supports requesting up to this number of bytes +// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 +var MAX_UINT32 = 4294967295 + +function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +} + +var Buffer = require('safe-buffer').Buffer +var crypto = global.crypto || global.msCrypto + +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} + +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer.allocUnsafe(size) + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) + } + } else { + crypto.getRandomValues(bytes) + } + } + + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } + + return bytes +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":119,"safe-buffer":142}],127:[function(require,module,exports){ +(function (process,global){ +'use strict' + +function oldBrowser () { + throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') +} +var safeBuffer = require('safe-buffer') +var randombytes = require('randombytes') +var Buffer = safeBuffer.Buffer +var kBufferMaxLength = safeBuffer.kMaxLength +var crypto = global.crypto || global.msCrypto +var kMaxUint32 = Math.pow(2, 32) - 1 +function assertOffset (offset, length) { + if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare + throw new TypeError('offset must be a number') + } + + if (offset > kMaxUint32 || offset < 0) { + throw new TypeError('offset must be a uint32') + } + + if (offset > kBufferMaxLength || offset > length) { + throw new RangeError('offset out of range') + } +} + +function assertSize (size, offset, length) { + if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare + throw new TypeError('size must be a number') + } + + if (size > kMaxUint32 || size < 0) { + throw new TypeError('size must be a uint32') + } + + if (size + offset > length || size > kBufferMaxLength) { + throw new RangeError('buffer too small') + } +} +if ((crypto && crypto.getRandomValues) || !process.browser) { + exports.randomFill = randomFill + exports.randomFillSync = randomFillSync +} else { + exports.randomFill = oldBrowser + exports.randomFillSync = oldBrowser +} +function randomFill (buf, offset, size, cb) { + if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array') + } + + if (typeof offset === 'function') { + cb = offset + offset = 0 + size = buf.length + } else if (typeof size === 'function') { + cb = size + size = buf.length - offset + } else if (typeof cb !== 'function') { + throw new TypeError('"cb" argument must be a function') + } + assertOffset(offset, buf.length) + assertSize(size, offset, buf.length) + return actualFill(buf, offset, size, cb) +} + +function actualFill (buf, offset, size, cb) { + if (process.browser) { + var ourBuf = buf.buffer + var uint = new Uint8Array(ourBuf, offset, size) + crypto.getRandomValues(uint) + if (cb) { + process.nextTick(function () { + cb(null, buf) + }) + return + } + return buf + } + if (cb) { + randombytes(size, function (err, bytes) { + if (err) { + return cb(err) + } + bytes.copy(buf, offset) + cb(null, buf) + }) + return + } + var bytes = randombytes(size) + bytes.copy(buf, offset) + return buf +} +function randomFillSync (buf, offset, size) { + if (typeof offset === 'undefined') { + offset = 0 + } + if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { + throw new TypeError('"buf" argument must be a Buffer or Uint8Array') + } + + assertOffset(offset, buf.length) + + if (size === undefined) size = buf.length - offset + + assertSize(size, offset, buf.length) + + return actualFill(buf, offset, size) +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":119,"randombytes":126,"safe-buffer":142}],128:[function(require,module,exports){ +module.exports = require('./lib/_stream_duplex.js'); + +},{"./lib/_stream_duplex.js":129}],129:[function(require,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. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + pna.nextTick(cb, err); +}; +},{"./_stream_readable":131,"./_stream_writable":133,"core-util-is":49,"inherits":101,"process-nextick-args":118}],130:[function(require,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. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":132,"core-util-is":49,"inherits":101}],131:[function(require,module,exports){ +(function (process,global){ +// 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. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); } - return this.wrap([vnode]); - }; - VNodeWrapper.prototype.wrapDocFrag = function (children) { - return vnode_1.vnode('', { isolate: [] }, children, undefined, this - .rootElement); - }; - VNodeWrapper.prototype.wrap = function (children) { - var _a = this.rootElement, tagName = _a.tagName, id = _a.id, className = _a.className; - var selId = id ? "#" + id : ''; - var selClass = className ? "." + className.split(" ").join(".") : ''; - var vnode = h_1.h("" + tagName.toLowerCase() + selId + selClass, {}, children); - vnode.data = vnode.data || {}; - vnode.data.isolate = vnode.data.isolate || []; - return vnode; - }; - return VNodeWrapper; -}()); -exports.VNodeWrapper = VNodeWrapper; - -},{"./utils":20,"snabbdom-selector":30,"snabbdom/h":34,"snabbdom/vnode":45}],12:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var xstream_1 = require("xstream"); -function fromEvent(element, eventName, useCapture, preventDefault, passive) { - if (useCapture === void 0) { useCapture = false; } - if (preventDefault === void 0) { preventDefault = false; } - if (passive === void 0) { passive = false; } - var next = null; - return xstream_1.Stream.create({ - start: function start(listener) { - if (preventDefault) { - next = function _next(event) { - preventDefaultConditional(event, preventDefault); - listener.next(event); - }; - } - else { - next = function _next(event) { - listener.next(event); - }; - } - element.addEventListener(eventName, next, { - capture: useCapture, - passive: passive, - }); - }, - stop: function stop() { - element.removeEventListener(eventName, next, useCapture); - next = null; - }, + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + + var state = this._readableState; + var paused = false; + + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + + _this.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return this; +}; + +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":129,"./internal/streams/BufferList":134,"./internal/streams/destroy":135,"./internal/streams/stream":136,"_process":119,"core-util-is":49,"events":82,"inherits":101,"isarray":103,"process-nextick-args":118,"safe-buffer":142,"string_decoder/":152,"util":18}],132:[function(require,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. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); + + cb(er); + + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} + +function prefinish() { + var _this = this; + + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); + + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} +},{"./_stream_duplex":129,"core-util-is":49,"inherits":101}],133:[function(require,module,exports){ +(function (process,global,setImmediate){ +// 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. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ + +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ + +var destroyImpl = require('./internal/streams/destroy'); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) +},{"./_stream_duplex":129,"./internal/streams/destroy":135,"./internal/streams/stream":136,"_process":119,"core-util-is":49,"inherits":101,"process-nextick-args":118,"safe-buffer":142,"timers":153,"util-deprecate":154}],134:[function(require,module,exports){ +'use strict'; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = require('safe-buffer').Buffer; +var util = require('util'); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); + +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; + }; } -exports.fromEvent = fromEvent; -function matchObject(matcher, obj) { - var keys = Object.keys(matcher); - var n = keys.length; - for (var i = 0; i < n; i++) { - var k = keys[i]; - if (typeof matcher[k] === 'object' && typeof obj[k] === 'object') { - if (!matchObject(matcher[k], obj[k])) { - return false; - } - } - else if (matcher[k] !== obj[k]) { - return false; - } +},{"safe-buffer":142,"util":18}],135:[function(require,module,exports){ +'use strict'; + +/**/ + +var pna = require('process-nextick-args'); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + pna.nextTick(emitErrorNT, this, err); } - return true; + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + pna.nextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); + + return this; } -function preventDefaultConditional(event, preventDefault) { - if (preventDefault) { - if (typeof preventDefault === 'boolean') { - event.preventDefault(); - } - else if (isPredicate(preventDefault)) { - if (preventDefault(event)) { - event.preventDefault(); - } - } - else if (typeof preventDefault === 'object') { - if (matchObject(preventDefault, event)) { - event.preventDefault(); - } - } - else { - throw new Error('preventDefault has to be either a boolean, predicate function or object'); - } + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; +},{"process-nextick-args":118}],136:[function(require,module,exports){ +module.exports = require('events').EventEmitter; + +},{"events":82}],137:[function(require,module,exports){ +module.exports = require('./readable').PassThrough + +},{"./readable":138}],138:[function(require,module,exports){ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +},{"./lib/_stream_duplex.js":129,"./lib/_stream_passthrough.js":130,"./lib/_stream_readable.js":131,"./lib/_stream_transform.js":132,"./lib/_stream_writable.js":133}],139:[function(require,module,exports){ +module.exports = require('./readable').Transform + +},{"./readable":138}],140:[function(require,module,exports){ +module.exports = require('./lib/_stream_writable.js'); + +},{"./lib/_stream_writable.js":133}],141:[function(require,module,exports){ +'use strict' +var Buffer = require('buffer').Buffer +var inherits = require('inherits') +var HashBase = require('hash-base') + +var ARRAY16 = new Array(16) + +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] +var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] + +function RIPEMD160 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 +} + +inherits(RIPEMD160, HashBase) + +RIPEMD160.prototype._update = function () { + var words = ARRAY16 + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) + + var al = this._a | 0 + var bl = this._b | 0 + var cl = this._c | 0 + var dl = this._d | 0 + var el = this._e | 0 + + var ar = this._a | 0 + var br = this._b | 0 + var cr = this._c | 0 + var dr = this._d | 0 + var er = this._e | 0 + + // computation + for (var i = 0; i < 80; i += 1) { + var tl + var tr + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) } + + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = tl + + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = tr + } + + // update state + var t = (this._b + cl + dr) | 0 + this._b = (this._c + dl + er) | 0 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t } -exports.preventDefaultConditional = preventDefaultConditional; -function isPredicate(fn) { - return typeof fn === 'function'; + +RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer } -},{"xstream":55}],13:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -// tslint:disable:max-file-line-count -var h_1 = require("snabbdom/h"); -function isValidString(param) { - return typeof param === 'string' && param.length > 0; +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) } -function isSelector(param) { - return isValidString(param) && (param[0] === '.' || param[0] === '#'); + +function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 } -function createTagFunction(tagName) { - return function hyperscript(a, b, c) { - var hasA = typeof a !== 'undefined'; - var hasB = typeof b !== 'undefined'; - var hasC = typeof c !== 'undefined'; - if (isSelector(a)) { - if (hasB && hasC) { - return h_1.h(tagName + a, b, c); - } - else if (hasB) { - return h_1.h(tagName + a, b); - } - else { - return h_1.h(tagName + a, {}); - } - } - else if (hasC) { - return h_1.h(tagName + a, b, c); - } - else if (hasB) { - return h_1.h(tagName, a, b); - } - else if (hasA) { - return h_1.h(tagName, a); - } - else { - return h_1.h(tagName, {}); - } - }; + +function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 } -var SVG_TAG_NAMES = [ - 'a', - 'altGlyph', - 'altGlyphDef', - 'altGlyphItem', - 'animate', - 'animateColor', - 'animateMotion', - 'animateTransform', - 'circle', - 'clipPath', - 'colorProfile', - 'cursor', - 'defs', - 'desc', - 'ellipse', - 'feBlend', - 'feColorMatrix', - 'feComponentTransfer', - 'feComposite', - 'feConvolveMatrix', - 'feDiffuseLighting', - 'feDisplacementMap', - 'feDistantLight', - 'feFlood', - 'feFuncA', - 'feFuncB', - 'feFuncG', - 'feFuncR', - 'feGaussianBlur', - 'feImage', - 'feMerge', - 'feMergeNode', - 'feMorphology', - 'feOffset', - 'fePointLight', - 'feSpecularLighting', - 'feSpotlight', - 'feTile', - 'feTurbulence', - 'filter', - 'font', - 'fontFace', - 'fontFaceFormat', - 'fontFaceName', - 'fontFaceSrc', - 'fontFaceUri', - 'foreignObject', - 'g', - 'glyph', - 'glyphRef', - 'hkern', - 'image', - 'line', - 'linearGradient', - 'marker', - 'mask', - 'metadata', - 'missingGlyph', - 'mpath', - 'path', - 'pattern', - 'polygon', - 'polyline', - 'radialGradient', - 'rect', - 'script', - 'set', - 'stop', - 'style', - 'switch', - 'symbol', - 'text', - 'textPath', - 'title', - 'tref', - 'tspan', - 'use', - 'view', - 'vkern', -]; -var svg = createTagFunction('svg'); -SVG_TAG_NAMES.forEach(function (tag) { - svg[tag] = createTagFunction(tag); -}); -var TAG_NAMES = [ - 'a', - 'abbr', - 'address', - 'area', - 'article', - 'aside', - 'audio', - 'b', - 'base', - 'bdi', - 'bdo', - 'blockquote', - 'body', - 'br', - 'button', - 'canvas', - 'caption', - 'cite', - 'code', - 'col', - 'colgroup', - 'dd', - 'del', - 'details', - 'dfn', - 'dir', - 'div', - 'dl', - 'dt', - 'em', - 'embed', - 'fieldset', - 'figcaption', - 'figure', - 'footer', - 'form', - 'h1', - 'h2', - 'h3', - 'h4', - 'h5', - 'h6', - 'head', - 'header', - 'hgroup', - 'hr', - 'html', - 'i', - 'iframe', - 'img', - 'input', - 'ins', - 'kbd', - 'keygen', - 'label', - 'legend', - 'li', - 'link', - 'main', - 'map', - 'mark', - 'menu', - 'meta', - 'nav', - 'noscript', - 'object', - 'ol', - 'optgroup', - 'option', - 'p', - 'param', - 'pre', - 'progress', - 'q', - 'rp', - 'rt', - 'ruby', - 's', - 'samp', - 'script', - 'section', - 'select', - 'small', - 'source', - 'span', - 'strong', - 'style', - 'sub', - 'summary', - 'sup', - 'table', - 'tbody', - 'td', - 'textarea', - 'tfoot', - 'th', - 'thead', - 'time', - 'title', - 'tr', - 'u', - 'ul', - 'video', -]; -var exported = { - SVG_TAG_NAMES: SVG_TAG_NAMES, - TAG_NAMES: TAG_NAMES, - svg: svg, - isSelector: isSelector, - createTagFunction: createTagFunction, -}; -TAG_NAMES.forEach(function (n) { - exported[n] = createTagFunction(n); -}); -exports.default = exported; - -},{"snabbdom/h":34}],14:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var thunk_1 = require("./thunk"); -exports.thunk = thunk_1.thunk; -var MainDOMSource_1 = require("./MainDOMSource"); -exports.MainDOMSource = MainDOMSource_1.MainDOMSource; -/** - * A factory for the DOM driver function. - * - * Takes a `container` to define the target on the existing DOM which this - * driver will operate on, and an `options` object as the second argument. The - * input to this driver is a stream of virtual DOM objects, or in other words, - * Snabbdom "VNode" objects. The output of this driver is a "DOMSource": a - * collection of Observables queried with the methods `select()` and `events()`. - * - * **`DOMSource.select(selector)`** returns a new DOMSource with scope - * restricted to the element(s) that matches the CSS `selector` given. To select - * the page's `document`, use `.select('document')`. To select the container - * element for this app, use `.select(':root')`. - * - * **`DOMSource.events(eventType, options)`** returns a stream of events of - * `eventType` happening on the elements that match the current DOMSource. The - * event object contains the `ownerTarget` property that behaves exactly like - * `currentTarget`. The reason for this is that some browsers doesn't allow - * `currentTarget` property to be mutated, hence a new property is created. The - * returned stream is an *xstream* Stream if you use `@cycle/xstream-run` to run - * your app with this driver, or it is an RxJS Observable if you use - * `@cycle/rxjs-run`, and so forth. - * - * **options for DOMSource.events** - * - * The `options` parameter on `DOMSource.events(eventType, options)` is an - * (optional) object with two optional fields: `useCapture` and - * `preventDefault`. - * - * `useCapture` is by default `false`, except it is `true` for event types that - * do not bubble. Read more here - * https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener - * about the `useCapture` and its purpose. - * - * `preventDefault` is by default `false`, and indicates to the driver whether - * `event.preventDefault()` should be invoked. This option can be configured in - * three ways: - * - * - `{preventDefault: boolean}` to invoke preventDefault if `true`, and not - * invoke otherwise. - * - `{preventDefault: (ev: Event) => boolean}` for conditional invocation. - * - `{preventDefault: NestedObject}` uses an object to be recursively compared - * to the `Event` object. `preventDefault` is invoked when all properties on the - * nested object match with the properties on the event object. - * - * Here are some examples: - * ```typescript - * // always prevent default - * DOMSource.select('input').events('keydown', { - * preventDefault: true - * }) - * - * // prevent default only when `ENTER` is pressed - * DOMSource.select('input').events('keydown', { - * preventDefault: e => e.keyCode === 13 - * }) - * - * // prevent defualt when `ENTER` is pressed AND target.value is 'HELLO' - * DOMSource.select('input').events('keydown', { - * preventDefault: { keyCode: 13, ownerTarget: { value: 'HELLO' } } - * }); - * ``` - * - * **`DOMSource.elements()`** returns a stream of arrays containing the DOM - * elements that match the selectors in the DOMSource (e.g. from previous - * `select(x)` calls). - * - * **`DOMSource.element()`** returns a stream of DOM elements. Notice that this - * is the singular version of `.elements()`, so the stream will emit an element, - * not an array. If there is no element that matches the selected DOMSource, - * then the returned stream will not emit anything. - * - * @param {(String|HTMLElement)} container the DOM selector for the element - * (or the element itself) to contain the rendering of the VTrees. - * @param {DOMDriverOptions} options an object with two optional properties: - * - * - `modules: array` overrides `@cycle/dom`'s default Snabbdom modules as - * as defined in [`src/modules.ts`](./src/modules.ts). - * @return {Function} the DOM driver function. The function expects a stream of - * VNode as input, and outputs the DOMSource object. - * @function makeDOMDriver - */ -var makeDOMDriver_1 = require("./makeDOMDriver"); -exports.makeDOMDriver = makeDOMDriver_1.makeDOMDriver; -/** - * A factory function to create mocked DOMSource objects, for testing purposes. - * - * Takes a `mockConfig` object as argument, and returns - * a DOMSource that can be given to any Cycle.js app that expects a DOMSource in - * the sources, for testing. - * - * The `mockConfig` parameter is an object specifying selectors, eventTypes and - * their streams. Example: - * - * ```js - * const domSource = mockDOMSource({ - * '.foo': { - * 'click': xs.of({target: {}}), - * 'mouseover': xs.of({target: {}}), - * }, - * '.bar': { - * 'scroll': xs.of({target: {}}), - * elements: xs.of({tagName: 'div'}), - * } - * }); - * - * // Usage - * const click$ = domSource.select('.foo').events('click'); - * const element$ = domSource.select('.bar').elements(); - * ``` - * - * The mocked DOM Source supports isolation. It has the functions `isolateSink` - * and `isolateSource` attached to it, and performs simple isolation using - * classNames. *isolateSink* with scope `foo` will append the class `___foo` to - * the stream of virtual DOM nodes, and *isolateSource* with scope `foo` will - * perform a conventional `mockedDOMSource.select('.__foo')` call. - * - * @param {Object} mockConfig an object where keys are selector strings - * and values are objects. Those nested objects have `eventType` strings as keys - * and values are streams you created. - * @return {Object} fake DOM source object, with an API containing `select()` - * and `events()` and `elements()` which can be used just like the DOM Driver's - * DOMSource. - * - * @function mockDOMSource - */ -var mockDOMSource_1 = require("./mockDOMSource"); -exports.mockDOMSource = mockDOMSource_1.mockDOMSource; -exports.MockedDOMSource = mockDOMSource_1.MockedDOMSource; -/** - * The hyperscript function `h()` is a function to create virtual DOM objects, - * also known as VNodes. Call - * - * ```js - * h('div.myClass', {style: {color: 'red'}}, []) - * ``` - * - * to create a VNode that represents a `DIV` element with className `myClass`, - * styled with red color, and no children because the `[]` array was passed. The - * API is `h(tagOrSelector, optionalData, optionalChildrenOrText)`. - * - * However, usually you should use "hyperscript helpers", which are shortcut - * functions based on hyperscript. There is one hyperscript helper function for - * each DOM tagName, such as `h1()`, `h2()`, `div()`, `span()`, `label()`, - * `input()`. For instance, the previous example could have been written - * as: - * - * ```js - * div('.myClass', {style: {color: 'red'}}, []) - * ``` - * - * There are also SVG helper functions, which apply the appropriate SVG - * namespace to the resulting elements. `svg()` function creates the top-most - * SVG element, and `svg.g`, `svg.polygon`, `svg.circle`, `svg.path` are for - * SVG-specific child elements. Example: - * - * ```js - * svg({attrs: {width: 150, height: 150}}, [ - * svg.polygon({ - * attrs: { - * class: 'triangle', - * points: '20 0 20 150 150 20' - * } - * }) - * ]) - * ``` - * - * @function h - */ -var h_1 = require("snabbdom/h"); -exports.h = h_1.h; -var hyperscript_helpers_1 = require("./hyperscript-helpers"); -exports.svg = hyperscript_helpers_1.default.svg; -exports.a = hyperscript_helpers_1.default.a; -exports.abbr = hyperscript_helpers_1.default.abbr; -exports.address = hyperscript_helpers_1.default.address; -exports.area = hyperscript_helpers_1.default.area; -exports.article = hyperscript_helpers_1.default.article; -exports.aside = hyperscript_helpers_1.default.aside; -exports.audio = hyperscript_helpers_1.default.audio; -exports.b = hyperscript_helpers_1.default.b; -exports.base = hyperscript_helpers_1.default.base; -exports.bdi = hyperscript_helpers_1.default.bdi; -exports.bdo = hyperscript_helpers_1.default.bdo; -exports.blockquote = hyperscript_helpers_1.default.blockquote; -exports.body = hyperscript_helpers_1.default.body; -exports.br = hyperscript_helpers_1.default.br; -exports.button = hyperscript_helpers_1.default.button; -exports.canvas = hyperscript_helpers_1.default.canvas; -exports.caption = hyperscript_helpers_1.default.caption; -exports.cite = hyperscript_helpers_1.default.cite; -exports.code = hyperscript_helpers_1.default.code; -exports.col = hyperscript_helpers_1.default.col; -exports.colgroup = hyperscript_helpers_1.default.colgroup; -exports.dd = hyperscript_helpers_1.default.dd; -exports.del = hyperscript_helpers_1.default.del; -exports.dfn = hyperscript_helpers_1.default.dfn; -exports.dir = hyperscript_helpers_1.default.dir; -exports.div = hyperscript_helpers_1.default.div; -exports.dl = hyperscript_helpers_1.default.dl; -exports.dt = hyperscript_helpers_1.default.dt; -exports.em = hyperscript_helpers_1.default.em; -exports.embed = hyperscript_helpers_1.default.embed; -exports.fieldset = hyperscript_helpers_1.default.fieldset; -exports.figcaption = hyperscript_helpers_1.default.figcaption; -exports.figure = hyperscript_helpers_1.default.figure; -exports.footer = hyperscript_helpers_1.default.footer; -exports.form = hyperscript_helpers_1.default.form; -exports.h1 = hyperscript_helpers_1.default.h1; -exports.h2 = hyperscript_helpers_1.default.h2; -exports.h3 = hyperscript_helpers_1.default.h3; -exports.h4 = hyperscript_helpers_1.default.h4; -exports.h5 = hyperscript_helpers_1.default.h5; -exports.h6 = hyperscript_helpers_1.default.h6; -exports.head = hyperscript_helpers_1.default.head; -exports.header = hyperscript_helpers_1.default.header; -exports.hgroup = hyperscript_helpers_1.default.hgroup; -exports.hr = hyperscript_helpers_1.default.hr; -exports.html = hyperscript_helpers_1.default.html; -exports.i = hyperscript_helpers_1.default.i; -exports.iframe = hyperscript_helpers_1.default.iframe; -exports.img = hyperscript_helpers_1.default.img; -exports.input = hyperscript_helpers_1.default.input; -exports.ins = hyperscript_helpers_1.default.ins; -exports.kbd = hyperscript_helpers_1.default.kbd; -exports.keygen = hyperscript_helpers_1.default.keygen; -exports.label = hyperscript_helpers_1.default.label; -exports.legend = hyperscript_helpers_1.default.legend; -exports.li = hyperscript_helpers_1.default.li; -exports.link = hyperscript_helpers_1.default.link; -exports.main = hyperscript_helpers_1.default.main; -exports.map = hyperscript_helpers_1.default.map; -exports.mark = hyperscript_helpers_1.default.mark; -exports.menu = hyperscript_helpers_1.default.menu; -exports.meta = hyperscript_helpers_1.default.meta; -exports.nav = hyperscript_helpers_1.default.nav; -exports.noscript = hyperscript_helpers_1.default.noscript; -exports.object = hyperscript_helpers_1.default.object; -exports.ol = hyperscript_helpers_1.default.ol; -exports.optgroup = hyperscript_helpers_1.default.optgroup; -exports.option = hyperscript_helpers_1.default.option; -exports.p = hyperscript_helpers_1.default.p; -exports.param = hyperscript_helpers_1.default.param; -exports.pre = hyperscript_helpers_1.default.pre; -exports.progress = hyperscript_helpers_1.default.progress; -exports.q = hyperscript_helpers_1.default.q; -exports.rp = hyperscript_helpers_1.default.rp; -exports.rt = hyperscript_helpers_1.default.rt; -exports.ruby = hyperscript_helpers_1.default.ruby; -exports.s = hyperscript_helpers_1.default.s; -exports.samp = hyperscript_helpers_1.default.samp; -exports.script = hyperscript_helpers_1.default.script; -exports.section = hyperscript_helpers_1.default.section; -exports.select = hyperscript_helpers_1.default.select; -exports.small = hyperscript_helpers_1.default.small; -exports.source = hyperscript_helpers_1.default.source; -exports.span = hyperscript_helpers_1.default.span; -exports.strong = hyperscript_helpers_1.default.strong; -exports.style = hyperscript_helpers_1.default.style; -exports.sub = hyperscript_helpers_1.default.sub; -exports.sup = hyperscript_helpers_1.default.sup; -exports.table = hyperscript_helpers_1.default.table; -exports.tbody = hyperscript_helpers_1.default.tbody; -exports.td = hyperscript_helpers_1.default.td; -exports.textarea = hyperscript_helpers_1.default.textarea; -exports.tfoot = hyperscript_helpers_1.default.tfoot; -exports.th = hyperscript_helpers_1.default.th; -exports.thead = hyperscript_helpers_1.default.thead; -exports.title = hyperscript_helpers_1.default.title; -exports.tr = hyperscript_helpers_1.default.tr; -exports.u = hyperscript_helpers_1.default.u; -exports.ul = hyperscript_helpers_1.default.ul; -exports.video = hyperscript_helpers_1.default.video; - -},{"./MainDOMSource":6,"./hyperscript-helpers":13,"./makeDOMDriver":16,"./mockDOMSource":17,"./thunk":19,"snabbdom/h":34}],15:[function(require,module,exports){ -"use strict"; -var __assign = (this && this.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -var utils_1 = require("./utils"); -function makeIsolateSink(namespace) { - return function (sink, scope) { - if (scope === ':root') { - return sink; - } - return sink.map(function (node) { - if (!node) { - return node; - } - var scopeObj = getScopeObj(scope); - var newNode = __assign({}, node, { data: __assign({}, node.data, { isolate: !node.data || !Array.isArray(node.data.isolate) - ? namespace.concat([scopeObj]) - : node.data.isolate }) }); - return __assign({}, newNode, { key: newNode.key !== undefined - ? newNode.key - : JSON.stringify(newNode.data.isolate) }); - }); - }; + +function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 } -exports.makeIsolateSink = makeIsolateSink; -function getScopeObj(scope) { - return { - type: utils_1.isClassOrId(scope) ? 'sibling' : 'total', - scope: scope, - }; + +function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } -exports.getScopeObj = getScopeObj; - -},{"./utils":20}],16:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var snabbdom_1 = require("snabbdom"); -var xstream_1 = require("xstream"); -var concat_1 = require("xstream/extra/concat"); -var sampleCombine_1 = require("xstream/extra/sampleCombine"); -var MainDOMSource_1 = require("./MainDOMSource"); -var tovnode_1 = require("snabbdom/tovnode"); -var VNodeWrapper_1 = require("./VNodeWrapper"); -var utils_1 = require("./utils"); -var modules_1 = require("./modules"); -var IsolateModule_1 = require("./IsolateModule"); -var EventDelegator_1 = require("./EventDelegator"); -function makeDOMDriverInputGuard(modules) { - if (!Array.isArray(modules)) { - throw new Error("Optional modules option must be an array for snabbdom modules"); - } -} -function domDriverInputGuard(view$) { - if (!view$ || - typeof view$.addListener !== "function" || - typeof view$.fold !== "function") { - throw new Error("The DOM driver function expects as input a Stream of " + - "virtual DOM elements"); - } -} -function dropCompletion(input) { - return xstream_1.default.merge(input, xstream_1.default.never()); -} -function unwrapElementFromVNode(vnode) { - return vnode.elm; -} -function reportSnabbdomError(err) { - (console.error || console.log)(err); -} -function makeDOMReady$() { - return xstream_1.default.create({ - start: function (lis) { - if (document.readyState === 'loading') { - document.addEventListener('readystatechange', function () { - var state = document.readyState; - if (state === 'interactive' || state === 'complete') { - lis.next(null); - lis.complete(); - } - }); - } - else { - lis.next(null); - lis.complete(); - } - }, - stop: function () { }, - }); + +function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 } -function addRootScope(vnode) { - vnode.data = vnode.data || {}; - vnode.data.isolate = []; - return vnode; -} -function makeDOMDriver(container, options) { - if (!options) { - options = {}; - } - utils_1.checkValidContainer(container); - var modules = options.modules || modules_1.default; - makeDOMDriverInputGuard(modules); - var isolateModule = new IsolateModule_1.IsolateModule(); - var patch = snabbdom_1.init([isolateModule.createModule()].concat(modules)); - var domReady$ = makeDOMReady$(); - var vnodeWrapper; - var mutationObserver; - var mutationConfirmed$ = xstream_1.default.create({ - start: function (listener) { - mutationObserver = new MutationObserver(function () { return listener.next(null); }); - }, - stop: function () { - mutationObserver.disconnect(); - }, - }); - function DOMDriver(vnode$, name) { - if (name === void 0) { name = 'DOM'; } - domDriverInputGuard(vnode$); - var sanitation$ = xstream_1.default.create(); - var firstRoot$ = domReady$.map(function () { - var firstRoot = utils_1.getValidNode(container) || document.body; - vnodeWrapper = new VNodeWrapper_1.VNodeWrapper(firstRoot); - return firstRoot; - }); - // We need to subscribe to the sink (i.e. vnode$) synchronously inside this - // driver, and not later in the map().flatten() because this sink is in - // reality a SinkProxy from @cycle/run, and we don't want to miss the first - // emission when the main() is connected to the drivers. - // Read more in issue #739. - var rememberedVNode$ = vnode$.remember(); - rememberedVNode$.addListener({}); - // The mutation observer internal to mutationConfirmed$ should - // exist before elementAfterPatch$ calls mutationObserver.observe() - mutationConfirmed$.addListener({}); - var elementAfterPatch$ = firstRoot$ - .map(function (firstRoot) { - return xstream_1.default - .merge(rememberedVNode$.endWhen(sanitation$), sanitation$) - .map(function (vnode) { return vnodeWrapper.call(vnode); }) - .startWith(addRootScope(tovnode_1.toVNode(firstRoot))) - .fold(patch, tovnode_1.toVNode(firstRoot)) - .drop(1) - .map(unwrapElementFromVNode) - .startWith(firstRoot) - .map(function (el) { - mutationObserver.observe(el, { - childList: true, - attributes: true, - characterData: true, - subtree: true, - attributeOldValue: true, - characterDataOldValue: true, - }); - return el; - }) - .compose(dropCompletion); - } // don't complete this stream - ) - .flatten(); - var rootElement$ = concat_1.default(domReady$, mutationConfirmed$) - .endWhen(sanitation$) - .compose(sampleCombine_1.default(elementAfterPatch$)) - .map(function (arr) { return arr[1]; }) - .remember(); - // Start the snabbdom patching, over time - rootElement$.addListener({ error: reportSnabbdomError }); - var delegator = new EventDelegator_1.EventDelegator(rootElement$, isolateModule); - return new MainDOMSource_1.MainDOMSource(rootElement$, sanitation$, [], isolateModule, delegator, name); - } - return DOMDriver; -} -exports.makeDOMDriver = makeDOMDriver; - -},{"./EventDelegator":4,"./IsolateModule":5,"./MainDOMSource":6,"./VNodeWrapper":11,"./modules":18,"./utils":20,"snabbdom":42,"snabbdom/tovnode":44,"xstream":55,"xstream/extra/concat":53,"xstream/extra/sampleCombine":54}],17:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var xstream_1 = require("xstream"); -var adapt_1 = require("@cycle/run/lib/adapt"); -var SCOPE_PREFIX = '___'; -var MockedDOMSource = /** @class */ (function () { - function MockedDOMSource(_mockConfig) { - this._mockConfig = _mockConfig; - if (_mockConfig.elements) { - this._elements = _mockConfig.elements; - } - else { - this._elements = adapt_1.adapt(xstream_1.default.empty()); - } - } - MockedDOMSource.prototype.elements = function () { - var out = this - ._elements; - out._isCycleSource = 'MockedDOM'; - return out; - }; - MockedDOMSource.prototype.element = function () { - var output$ = this.elements() - .filter(function (arr) { return arr.length > 0; }) - .map(function (arr) { return arr[0]; }) - .remember(); - var out = adapt_1.adapt(output$); - out._isCycleSource = 'MockedDOM'; - return out; - }; - MockedDOMSource.prototype.events = function (eventType, options, bubbles) { - var streamForEventType = this._mockConfig[eventType]; - var out = adapt_1.adapt(streamForEventType || xstream_1.default.empty()); - out._isCycleSource = 'MockedDOM'; - return out; - }; - MockedDOMSource.prototype.select = function (selector) { - var mockConfigForSelector = this._mockConfig[selector] || {}; - return new MockedDOMSource(mockConfigForSelector); - }; - MockedDOMSource.prototype.isolateSource = function (source, scope) { - return source.select('.' + SCOPE_PREFIX + scope); - }; - MockedDOMSource.prototype.isolateSink = function (sink, scope) { - return adapt_1.adapt(xstream_1.default.fromObservable(sink).map(function (vnode) { - if (vnode.sel && vnode.sel.indexOf(SCOPE_PREFIX + scope) !== -1) { - return vnode; - } - else { - vnode.sel += "." + SCOPE_PREFIX + scope; - return vnode; - } - })); - }; - return MockedDOMSource; -}()); -exports.MockedDOMSource = MockedDOMSource; -function mockDOMSource(mockConfig) { - return new MockedDOMSource(mockConfig); -} -exports.mockDOMSource = mockDOMSource; - -},{"@cycle/run/lib/adapt":21,"xstream":55}],18:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var class_1 = require("snabbdom/modules/class"); -exports.ClassModule = class_1.default; -var props_1 = require("snabbdom/modules/props"); -exports.PropsModule = props_1.default; -var attributes_1 = require("snabbdom/modules/attributes"); -exports.AttrsModule = attributes_1.default; -var style_1 = require("snabbdom/modules/style"); -exports.StyleModule = style_1.default; -var dataset_1 = require("snabbdom/modules/dataset"); -exports.DatasetModule = dataset_1.default; -var modules = [ - style_1.default, - class_1.default, - props_1.default, - attributes_1.default, - dataset_1.default, -]; -exports.default = modules; - -},{"snabbdom/modules/attributes":37,"snabbdom/modules/class":38,"snabbdom/modules/dataset":39,"snabbdom/modules/props":40,"snabbdom/modules/style":41}],19:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var h_1 = require("snabbdom/h"); -function copyToThunk(vnode, thunkVNode) { - thunkVNode.elm = vnode.elm; - vnode.data.fn = thunkVNode.data.fn; - vnode.data.args = thunkVNode.data.args; - vnode.data.isolate = thunkVNode.data.isolate; - thunkVNode.data = vnode.data; - thunkVNode.children = vnode.children; - thunkVNode.text = vnode.text; - thunkVNode.elm = vnode.elm; -} -function init(thunkVNode) { - var cur = thunkVNode.data; - var vnode = cur.fn.apply(undefined, cur.args); - copyToThunk(vnode, thunkVNode); -} -function prepatch(oldVnode, thunkVNode) { - var old = oldVnode.data, cur = thunkVNode.data; - var i; - var oldArgs = old.args, args = cur.args; - if (old.fn !== cur.fn || oldArgs.length !== args.length) { - copyToThunk(cur.fn.apply(undefined, args), thunkVNode); - } - for (i = 0; i < args.length; ++i) { - if (oldArgs[i] !== args[i]) { - copyToThunk(cur.fn.apply(undefined, args), thunkVNode); - return; - } - } - copyToThunk(oldVnode, thunkVNode); + +module.exports = RIPEMD160 + +},{"buffer":47,"hash-base":86,"inherits":101}],142:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } } -function thunk(sel, key, fn, args) { - if (args === undefined) { - args = fn; - fn = key; - key = undefined; - } - return h_1.h(sel, { - key: key, - hook: { init: init, prepatch: prepatch }, - fn: fn, - args: args, - }); +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer } -exports.thunk = thunk; -exports.default = thunk; - -},{"snabbdom/h":34}],20:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function isValidNode(obj) { - var ELEM_TYPE = 1; - var FRAG_TYPE = 11; - return typeof HTMLElement === 'object' - ? obj instanceof HTMLElement || obj instanceof DocumentFragment - : obj && - typeof obj === 'object' && - obj !== null && - (obj.nodeType === ELEM_TYPE || obj.nodeType === FRAG_TYPE) && - typeof obj.nodeName === 'string'; -} -function isClassOrId(str) { - return str.length > 1 && (str[0] === '.' || str[0] === '#'); -} -exports.isClassOrId = isClassOrId; -function isDocFrag(el) { - return el.nodeType === 11; -} -exports.isDocFrag = isDocFrag; -function checkValidContainer(container) { - if (typeof container !== 'string' && !isValidNode(container)) { - throw new Error('Given container is not a DOM element neither a selector string.'); - } -} -exports.checkValidContainer = checkValidContainer; -function getValidNode(selectors) { - var domElement = typeof selectors === 'string' - ? document.querySelector(selectors) - : selectors; - if (typeof selectors === 'string' && domElement === null) { - throw new Error("Cannot render into unknown element `" + selectors + "`"); - } - return domElement; -} -exports.getValidNode = getValidNode; -function getSelectors(namespace) { - var res = ''; - for (var i = namespace.length - 1; i >= 0; i--) { - if (namespace[i].type !== 'selector') { - break; - } - res = namespace[i].scope + ' ' + res; - } - return res.trim(); + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -exports.getSelectors = getSelectors; -function isEqualNamespace(a, b) { - if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) { - return false; - } - for (var i = 0; i < a.length; i++) { - if (a[i].type !== b[i].type || a[i].scope !== b[i].scope) { - return false; - } + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) } - return true; + } else { + buf.fill(0) + } + return buf } -exports.isEqualNamespace = isEqualNamespace; -function makeInsert(map) { - return function (type, elm, value) { - if (map.has(type)) { - var innerMap = map.get(type); - innerMap.set(elm, value); - } - else { - var innerMap = new Map(); - innerMap.set(elm, value); - map.set(type, innerMap); - } - }; + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) } -exports.makeInsert = makeInsert; -},{}],21:[function(require,module,exports){ -(function (global){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function getGlobal() { - var globalObj; - if (typeof window !== 'undefined') { - globalObj = window; - } - else if (typeof global !== 'undefined') { - globalObj = global; +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + +},{"buffer":47}],143:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer + +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = Buffer.alloc(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = Buffer.from(data, enc) + } + + var block = this._block + var blockSize = this._blockSize + var length = data.length + var accum = this._len + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize + var remainder = Math.min(length - offset, blockSize - assigned) + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i] } - else { - globalObj = this; + + accum += remainder + offset += remainder + + if ((accum % blockSize) === 0) { + this._update(block) } - globalObj.Cyclejs = globalObj.Cyclejs || {}; - globalObj = globalObj.Cyclejs; - globalObj.adaptStream = globalObj.adaptStream || (function (x) { return x; }); - return globalObj; + } + + this._len += length + return this +} + +Hash.prototype.digest = function (enc) { + var rem = this._len % this._blockSize + + this._block[rem] = 0x80 + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1) + + if (rem >= this._finalSize) { + this._update(this._block) + this._block.fill(0) + } + + var bits = this._len * 8 + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4) + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0 + var highBits = (bits - lowBits) / 0x100000000 + + this._block.writeUInt32BE(highBits, this._blockSize - 8) + this._block.writeUInt32BE(lowBits, this._blockSize - 4) + } + + this._update(this._block) + var hash = this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash + +},{"safe-buffer":142}],144:[function(require,module,exports){ +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() + + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() +} + +exports.sha = require('./sha') +exports.sha1 = require('./sha1') +exports.sha224 = require('./sha224') +exports.sha256 = require('./sha256') +exports.sha384 = require('./sha384') +exports.sha512 = require('./sha512') + +},{"./sha":145,"./sha1":146,"./sha224":147,"./sha256":148,"./sha384":149,"./sha512":150}],145:[function(require,module,exports){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) + +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this } -function setAdapt(f) { - getGlobal().adaptStream = f; + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) } -exports.setAdapt = setAdapt; -function adapt(stream) { - return getGlobal().adaptStream(stream); + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d } -exports.adapt = adapt; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } -},{}],22:[function(require,module,exports){ -(function (global){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function getGlobal() { - var globalObj; - if (typeof window !== 'undefined') { - globalObj = window; - } - else if (typeof global !== 'undefined') { - globalObj = global; - } - else { - globalObj = this; - } - globalObj.Cyclejs = globalObj.Cyclejs || {}; - globalObj = globalObj.Cyclejs; - globalObj.adaptStream = globalObj.adaptStream || (function (x) { return x; }); - return globalObj; -} -function setAdapt(f) { - getGlobal().adaptStream = f; + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 } -exports.setAdapt = setAdapt; -function adapt(stream) { - return getGlobal().adaptStream(stream); + +Sha.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H } -exports.adapt = adapt; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +module.exports = Sha -},{}],23:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var internals_1 = require("./internals"); -/** - * A function that prepares the Cycle application to be executed. Takes a `main` - * function and prepares to circularly connects it to the given collection of - * driver functions. As an output, `setup()` returns an object with three - * properties: `sources`, `sinks` and `run`. Only when `run()` is called will - * the application actually execute. Refer to the documentation of `run()` for - * more details. - * - * **Example:** - * ```js - * import {setup} from '@cycle/run'; - * const {sources, sinks, run} = setup(main, drivers); - * // ... - * const dispose = run(); // Executes the application - * // ... - * dispose(); - * ``` - * - * @param {Function} main a function that takes `sources` as input and outputs - * `sinks`. - * @param {Object} drivers an object where keys are driver names and values - * are driver functions. - * @return {Object} an object with three properties: `sources`, `sinks` and - * `run`. `sources` is the collection of driver sources, `sinks` is the - * collection of driver sinks, these can be used for debugging or testing. `run` - * is the function that once called will execute the application. - * @function setup +},{"./hash":143,"inherits":101,"safe-buffer":142}],146:[function(require,module,exports){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. */ -function setup(main, drivers) { - if (typeof main !== "function") { - throw new Error("First argument given to Cycle must be the 'main' " + "function."); - } - if (typeof drivers !== "object" || drivers === null) { - throw new Error("Second argument given to Cycle must be an object " + - "with driver functions as properties."); - } - if (internals_1.isObjectEmpty(drivers)) { - throw new Error("Second argument given to Cycle must be an object " + - "with at least one driver function declared as a property."); - } - var engine = setupReusable(drivers); - var sinks = main(engine.sources); - if (typeof window !== 'undefined') { - window.Cyclejs = window.Cyclejs || {}; - window.Cyclejs.sinks = sinks; - } - function _run() { - var disposeRun = engine.run(sinks); - return function dispose() { - disposeRun(); - engine.dispose(); - }; - } - return { sinks: sinks, sources: engine.sources, run: _run }; + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) } -exports.setup = setup; -/** - * A partially-applied variant of setup() which accepts only the drivers, and - * allows many `main` functions to execute and reuse this same set of drivers. - * - * Takes an object with driver functions as input, and outputs an object which - * contains the generated sources (from those drivers) and a `run` function - * (which in turn expects sinks as argument). This `run` function can be called - * multiple times with different arguments, and it will reuse the drivers that - * were passed to `setupReusable`. - * - * **Example:** - * ```js - * import {setupReusable} from '@cycle/run'; - * const {sources, run, dispose} = setupReusable(drivers); - * // ... - * const sinks = main(sources); - * const disposeRun = run(sinks); - * // ... - * disposeRun(); - * // ... - * dispose(); // ends the reusability of drivers - * ``` - * - * @param {Object} drivers an object where keys are driver names and values - * are driver functions. - * @return {Object} an object with three properties: `sources`, `run` and - * `dispose`. `sources` is the collection of driver sources, `run` is the - * function that once called with 'sinks' as argument, will execute the - * application, tying together sources with sinks. `dispose` terminates the - * reusable resources used by the drivers. Note also that `run` returns a - * dispose function which terminates resources that are specific (not reusable) - * to that run. - * @function setupReusable - */ -function setupReusable(drivers) { - if (typeof drivers !== "object" || drivers === null) { - throw new Error("Argument given to setupReusable must be an object " + - "with driver functions as properties."); - } - if (internals_1.isObjectEmpty(drivers)) { - throw new Error("Argument given to setupReusable must be an object " + - "with at least one driver function declared as a property."); - } - var sinkProxies = internals_1.makeSinkProxies(drivers); - var rawSources = internals_1.callDrivers(drivers, sinkProxies); - var sources = internals_1.adaptSources(rawSources); - function _run(sinks) { - return internals_1.replicateMany(sinks, sinkProxies); - } - function disposeEngine() { - internals_1.disposeSources(sources); - internals_1.disposeSinkProxies(sinkProxies); - } - return { sources: sources, run: _run, dispose: disposeEngine }; + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this } -exports.setupReusable = setupReusable; -/** - * Takes a `main` function and circularly connects it to the given collection - * of driver functions. - * - * **Example:** - * ```js - * import run from '@cycle/run'; - * const dispose = run(main, drivers); - * // ... - * dispose(); - * ``` - * - * The `main` function expects a collection of "source" streams (returned from - * drivers) as input, and should return a collection of "sink" streams (to be - * given to drivers). A "collection of streams" is a JavaScript object where - * keys match the driver names registered by the `drivers` object, and values - * are the streams. Refer to the documentation of each driver to see more - * details on what types of sources it outputs and sinks it receives. - * - * @param {Function} main a function that takes `sources` as input and outputs - * `sinks`. - * @param {Object} drivers an object where keys are driver names and values - * are driver functions. - * @return {Function} a dispose function, used to terminate the execution of the - * Cycle.js program, cleaning up resources used. - * @function run - */ -function run(main, drivers) { - var program = setup(main, drivers); - if (typeof window !== 'undefined' && - window.CyclejsDevTool_startGraphSerializer) { - window.CyclejsDevTool_startGraphSerializer(program.sinks); - } - return program.run(); -} -exports.run = run; -exports.default = run; - -},{"./internals":24}],24:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var xstream_1 = require("xstream"); -var quicktask_1 = require("quicktask"); -var adapt_1 = require("./adapt"); -var scheduleMicrotask = quicktask_1.default(); -function makeSinkProxies(drivers) { - var sinkProxies = {}; - for (var name_1 in drivers) { - if (drivers.hasOwnProperty(name_1)) { - sinkProxies[name_1] = xstream_1.default.create(); - } - } - return sinkProxies; + +function rotl1 (num) { + return (num << 1) | (num >>> 31) } -exports.makeSinkProxies = makeSinkProxies; -function callDrivers(drivers, sinkProxies) { - var sources = {}; - for (var name_2 in drivers) { - if (drivers.hasOwnProperty(name_2)) { - sources[name_2] = drivers[name_2](sinkProxies[name_2], name_2); - if (sources[name_2] && typeof sources[name_2] === 'object') { - sources[name_2]._isCycleSource = name_2; - } - } - } - return sources; -} -exports.callDrivers = callDrivers; -// NOTE: this will mutate `sources`. -function adaptSources(sources) { - for (var name_3 in sources) { - if (sources.hasOwnProperty(name_3) && - sources[name_3] && - typeof sources[name_3].shamefullySendNext === - 'function') { - sources[name_3] = adapt_1.adapt(sources[name_3]); - } - } - return sources; -} -exports.adaptSources = adaptSources; -function replicateMany(sinks, sinkProxies) { - var sinkNames = Object.keys(sinks).filter(function (name) { return !!sinkProxies[name]; }); - var buffers = {}; - var replicators = {}; - sinkNames.forEach(function (name) { - buffers[name] = { _n: [], _e: [] }; - replicators[name] = { - next: function (x) { return buffers[name]._n.push(x); }, - error: function (err) { return buffers[name]._e.push(err); }, - complete: function () { }, - }; - }); - var subscriptions = sinkNames.map(function (name) { - return xstream_1.default.fromObservable(sinks[name]).subscribe(replicators[name]); - }); - sinkNames.forEach(function (name) { - var listener = sinkProxies[name]; - var next = function (x) { - scheduleMicrotask(function () { return listener._n(x); }); - }; - var error = function (err) { - scheduleMicrotask(function () { - (console.error || console.log)(err); - listener._e(err); - }); - }; - buffers[name]._n.forEach(next); - buffers[name]._e.forEach(error); - replicators[name].next = next; - replicators[name].error = error; - // because sink.subscribe(replicator) had mutated replicator to add - // _n, _e, _c, we must also update these: - replicators[name]._n = next; - replicators[name]._e = error; - }); - buffers = null; // free up for GC - return function disposeReplication() { - subscriptions.forEach(function (s) { return s.unsubscribe(); }); - }; + +function rotl5 (num) { + return (num << 5) | (num >>> 27) } -exports.replicateMany = replicateMany; -function disposeSinkProxies(sinkProxies) { - Object.keys(sinkProxies).forEach(function (name) { return sinkProxies[name]._c(); }); -} -exports.disposeSinkProxies = disposeSinkProxies; -function disposeSources(sources) { - for (var k in sources) { - if (sources.hasOwnProperty(k) && - sources[k] && - sources[k].dispose) { - sources[k].dispose(); - } - } + +function rotl30 (num) { + return (num << 30) | (num >>> 2) } -exports.disposeSources = disposeSources; -function isObjectEmpty(obj) { - return Object.keys(obj).length === 0; + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d } -exports.isObjectEmpty = isObjectEmpty; -},{"./adapt":22,"quicktask":26,"xstream":55}],25:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; +Sha1.prototype._update = function (M) { + var W = this._w -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 -var cachedSetTimeout; -var cachedClearTimeout; + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + e = d + d = c + c = rotl30(b) + b = a + a = t + } + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 } -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } +Sha1.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + return H } -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(); - } +module.exports = Sha1 + +},{"./hash":143,"inherits":101,"safe-buffer":142}],147:[function(require,module,exports){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Sha256 = require('./sha256') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) } -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; +inherits(Sha224, Sha256) - 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; - runClearTimeout(timeout); +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this } -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) { - runTimeout(drainQueue); - } -}; +Sha224.prototype._hash = function () { + var H = Buffer.allocUnsafe(28) -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H } -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() {} +module.exports = Sha224 -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; +},{"./hash":143,"./sha256":148,"inherits":101,"safe-buffer":142}],148:[function(require,module,exports){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ -process.listeners = function (name) { return [] } +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 +] -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; +var W = new Array(64) -},{}],26:[function(require,module,exports){ -(function (process,setImmediate){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function microtask() { - if (typeof MutationObserver !== 'undefined') { - var node_1 = document.createTextNode(''); - var queue_1 = []; - var i_1 = 0; - new MutationObserver(function () { - while (queue_1.length) { - queue_1.shift()(); - } - }).observe(node_1, { characterData: true }); - return function (fn) { - queue_1.push(fn); - node_1.data = i_1 = 1 - i_1; - }; - } - else if (typeof setImmediate !== 'undefined') { - return setImmediate; - } - else if (typeof process !== 'undefined') { - return process.nextTick; - } - else { - return setTimeout; - } -} -exports.default = microtask; +function Sha256 () { + this.init() -}).call(this,require('_process'),require("timers").setImmediate) + this._w = W // new Array(64) -},{"_process":25,"timers":48}],27:[function(require,module,exports){ -"use strict"; -var selectorParser_1 = require('./selectorParser'); -function classNameFromVNode(vNode) { - var _a = selectorParser_1.selectorParser(vNode).className, cn = _a === void 0 ? '' : _a; - if (!vNode.data) { - return cn; - } - var _b = vNode.data, dataClass = _b.class, props = _b.props; - if (dataClass) { - var c = Object.keys(dataClass) - .filter(function (cl) { return dataClass[cl]; }); - cn += " " + c.join(" "); - } - if (props && props.className) { - cn += " " + props.className; - } - return cn && cn.trim(); + Hash.call(this, 64, 56) } -exports.classNameFromVNode = classNameFromVNode; -},{"./selectorParser":33}],28:[function(require,module,exports){ -"use strict"; -function curry2(select) { - return function selector(sel, vNode) { - switch (arguments.length) { - case 0: return select; - case 1: return function (_vNode) { return select(sel, _vNode); }; - default: return select(sel, vNode); - } - }; +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this } -exports.curry2 = curry2; -; - -},{}],29:[function(require,module,exports){ -"use strict"; -var query_1 = require('./query'); -var parent_symbol_1 = require('./parent-symbol'); -function findMatches(cssSelector, vNode) { - if (!vNode) { - return []; - } - traverseVNode(vNode, addParent); // add mapping to the parent selectorParser - return query_1.querySelector(cssSelector, vNode); -} -exports.findMatches = findMatches; -function traverseVNode(vNode, f) { - function recurse(currentNode, isParent, parentVNode) { - var length = currentNode.children && currentNode.children.length || 0; - for (var i = 0; i < length; ++i) { - var children = currentNode.children; - if (children && children[i] && typeof children[i] !== 'string') { - var child = children[i]; - recurse(child, false, currentNode); - } - } - f(currentNode, isParent, isParent ? void 0 : parentVNode); - } - recurse(vNode, true); + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) } -function addParent(vNode, isParent, parent) { - if (isParent) { - return void 0; - } - if (!vNode.data) { - vNode.data = {}; - } - if (!vNode.data[parent_symbol_1.default]) { - Object.defineProperty(vNode.data, parent_symbol_1.default, { - value: parent, - }); - } + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) } -},{"./parent-symbol":31,"./query":32}],30:[function(require,module,exports){ -"use strict"; -var curry2_1 = require('./curry2'); -var findMatches_1 = require('./findMatches'); -exports.select = curry2_1.curry2(findMatches_1.findMatches); -var selectorParser_1 = require('./selectorParser'); -exports.selectorParser = selectorParser_1.selectorParser; -var classNameFromVNode_1 = require('./classNameFromVNode'); -exports.classNameFromVNode = classNameFromVNode_1.classNameFromVNode; +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} -},{"./classNameFromVNode":27,"./curry2":28,"./findMatches":29,"./selectorParser":33}],31:[function(require,module,exports){ -(function (global){ -"use strict"; -var root; -if (typeof self !== 'undefined') { - root = self; +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) } -else if (typeof window !== 'undefined') { - root = window; + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) } -else if (typeof global !== 'undefined') { - root = global; + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) } -else { - root = Function('return this')(); + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 + + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 } -var Symbol = root.Symbol; -var parentSymbol; -if (typeof Symbol === 'function') { - parentSymbol = Symbol('parent'); + +Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H } -else { - parentSymbol = '@@snabbdom-selector-parent'; + +module.exports = Sha256 + +},{"./hash":143,"inherits":101,"safe-buffer":142}],149:[function(require,module,exports){ +var inherits = require('inherits') +var SHA512 = require('./sha512') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) } -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = parentSymbol; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +inherits(Sha384, SHA512) -},{}],32:[function(require,module,exports){ -"use strict"; -var tree_selector_1 = require('tree-selector'); -var selectorParser_1 = require('./selectorParser'); -var classNameFromVNode_1 = require('./classNameFromVNode'); -var parent_symbol_1 = require('./parent-symbol'); -var options = { - tag: function (vNode) { return selectorParser_1.selectorParser(vNode).tagName; }, - className: function (vNode) { return classNameFromVNode_1.classNameFromVNode(vNode); }, - id: function (vNode) { return selectorParser_1.selectorParser(vNode).id || ''; }, - children: function (vNode) { return vNode.children || []; }, - parent: function (vNode) { return vNode.data[parent_symbol_1.default] || vNode; }, - contents: function (vNode) { return vNode.text || ''; }, - attr: function (vNode, attr) { - if (vNode.data) { - var _a = vNode.data, _b = _a.attrs, attrs = _b === void 0 ? {} : _b, _c = _a.props, props = _c === void 0 ? {} : _c, _d = _a.dataset, dataset = _d === void 0 ? {} : _d; - if (attrs[attr]) { - return attrs[attr]; - } - if (props[attr]) { - return props[attr]; - } - if (attr.indexOf('data-') === 0 && dataset[attr.slice(5)]) { - return dataset[attr.slice(5)]; - } - } - }, -}; -var matches = tree_selector_1.createMatches(options); -function customMatches(sel, vnode) { - var data = vnode.data; - var selector = matches.bind(null, sel); - if (data && data.fn) { - var n = void 0; - if (Array.isArray(data.args)) { - n = data.fn.apply(null, data.args); - } - else if (data.args) { - n = data.fn.call(null, data.args); - } - else { - n = data.fn(); - } - return selector(n) ? n : false; - } - return selector(vnode); +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this } -exports.querySelector = tree_selector_1.createQuerySelector(options, customMatches); -},{"./classNameFromVNode":27,"./parent-symbol":31,"./selectorParser":33,"tree-selector":49}],33:[function(require,module,exports){ -"use strict"; -function selectorParser(node) { - if (!node.sel) { - return { - tagName: '', - id: '', - className: '', - }; - } - var sel = node.sel; - var hashIdx = sel.indexOf('#'); - var dotIdx = sel.indexOf('.', hashIdx); - var hash = hashIdx > 0 ? hashIdx : sel.length; - var dot = dotIdx > 0 ? dotIdx : sel.length; - var tagName = hashIdx !== -1 || dotIdx !== -1 ? - sel.slice(0, Math.min(hash, dot)) : - sel; - var id = hash < dot ? sel.slice(hash + 1, dot) : void 0; - var className = dotIdx > 0 ? sel.slice(dot + 1).replace(/\./g, ' ') : void 0; - return { - tagName: tagName, - id: id, - className: className, - }; +Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H } -exports.selectorParser = selectorParser; -},{}],34:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var vnode_1 = require("./vnode"); -var is = require("./is"); -function addNS(data, children, sel) { - data.ns = 'http://www.w3.org/2000/svg'; - if (sel !== 'foreignObject' && children !== undefined) { - for (var i = 0; i < children.length; ++i) { - var childData = children[i].data; - if (childData !== undefined) { - addNS(childData, children[i].children, children[i].sel); - } - } - } +module.exports = Sha384 + +},{"./hash":143,"./sha512":150,"inherits":101,"safe-buffer":142}],150:[function(require,module,exports){ +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) } -function h(sel, b, c) { - var data = {}, children, text, i; - if (c !== undefined) { - data = b; - if (is.array(c)) { - children = c; - } - else if (is.primitive(c)) { - text = c; - } - else if (c && c.sel) { - children = [c]; - } - } - else if (b !== undefined) { - if (is.array(b)) { - children = b; - } - else if (is.primitive(b)) { - text = b; - } - else if (b && b.sel) { - children = [b]; - } - else { - data = b; - } - } - if (children !== undefined) { - for (i = 0; i < children.length; ++i) { - if (is.primitive(children[i])) - children[i] = vnode_1.vnode(undefined, undefined, undefined, children[i], undefined); - } - } - if (sel[0] === 's' && sel[1] === 'v' && sel[2] === 'g' && - (sel.length === 3 || sel[3] === '.' || sel[3] === '#')) { - addNS(data, children, sel); - } - return vnode_1.vnode(sel, data, children, text, undefined); -} -exports.h = h; -; -exports.default = h; - -},{"./is":36,"./vnode":45}],35:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function createElement(tagName) { - return document.createElement(tagName); -} -function createElementNS(namespaceURI, qualifiedName) { - return document.createElementNS(namespaceURI, qualifiedName); -} -function createTextNode(text) { - return document.createTextNode(text); -} -function createComment(text) { - return document.createComment(text); -} -function insertBefore(parentNode, newNode, referenceNode) { - parentNode.insertBefore(newNode, referenceNode); -} -function removeChild(node, child) { - node.removeChild(child); -} -function appendChild(node, child) { - node.appendChild(child); -} -function parentNode(node) { - return node.parentNode; -} -function nextSibling(node) { - return node.nextSibling; -} -function tagName(elm) { - return elm.tagName; -} -function setTextContent(node, text) { - node.textContent = text; -} -function getTextContent(node) { - return node.textContent; -} -function isElement(node) { - return node.nodeType === 1; -} -function isText(node) { - return node.nodeType === 3; -} -function isComment(node) { - return node.nodeType === 8; -} -exports.htmlDomApi = { - createElement: createElement, - createElementNS: createElementNS, - createTextNode: createTextNode, - createComment: createComment, - insertBefore: insertBefore, - removeChild: removeChild, - appendChild: appendChild, - parentNode: parentNode, - nextSibling: nextSibling, - tagName: tagName, - setTextContent: setTextContent, - getTextContent: getTextContent, - isElement: isElement, - isText: isText, - isComment: isComment, -}; -exports.default = exports.htmlDomApi; - -},{}],36:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.array = Array.isArray; -function primitive(s) { - return typeof s === 'string' || typeof s === 'number'; -} -exports.primitive = primitive; - -},{}],37:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var xlinkNS = 'http://www.w3.org/1999/xlink'; -var xmlNS = 'http://www.w3.org/XML/1998/namespace'; -var colonChar = 58; -var xChar = 120; -function updateAttrs(oldVnode, vnode) { - var key, elm = vnode.elm, oldAttrs = oldVnode.data.attrs, attrs = vnode.data.attrs; - if (!oldAttrs && !attrs) - return; - if (oldAttrs === attrs) - return; - oldAttrs = oldAttrs || {}; - attrs = attrs || {}; - // update modified attributes, add new attributes - for (key in attrs) { - var cur = attrs[key]; - var old = oldAttrs[key]; - if (old !== cur) { - if (cur === true) { - elm.setAttribute(key, ""); - } - else if (cur === false) { - elm.removeAttribute(key); - } - else { - if (key.charCodeAt(0) !== xChar) { - elm.setAttribute(key, cur); - } - else if (key.charCodeAt(3) === colonChar) { - // Assume xml namespace - elm.setAttributeNS(xmlNS, key, cur); - } - else if (key.charCodeAt(5) === colonChar) { - // Assume xlink namespace - elm.setAttributeNS(xlinkNS, key, cur); - } - else { - elm.setAttribute(key, cur); - } - } - } - } - // remove removed attributes - // use `in` operator since the previous `for` iteration uses it (.i.e. add even attributes with undefined value) - // the other option is to remove all attributes with value == undefined - for (key in oldAttrs) { - if (!(key in attrs)) { - elm.removeAttribute(key); - } - } + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this } -exports.attributesModule = { create: updateAttrs, update: updateAttrs }; -exports.default = exports.attributesModule; -},{}],38:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function updateClass(oldVnode, vnode) { - var cur, name, elm = vnode.elm, oldClass = oldVnode.data.class, klass = vnode.data.class; - if (!oldClass && !klass) - return; - if (oldClass === klass) - return; - oldClass = oldClass || {}; - klass = klass || {}; - for (name in oldClass) { - if (!klass[name]) { - elm.classList.remove(name); - } - } - for (name in klass) { - cur = klass[name]; - if (cur !== oldClass[name]) { - elm.classList[cur ? 'add' : 'remove'](name); - } - } +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) } -exports.classModule = { create: updateClass, update: updateClass }; -exports.default = exports.classModule; -},{}],39:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var CAPS_REGEX = /[A-Z]/g; -function updateDataset(oldVnode, vnode) { - var elm = vnode.elm, oldDataset = oldVnode.data.dataset, dataset = vnode.data.dataset, key; - if (!oldDataset && !dataset) - return; - if (oldDataset === dataset) - return; - oldDataset = oldDataset || {}; - dataset = dataset || {}; - var d = elm.dataset; - for (key in oldDataset) { - if (!dataset[key]) { - if (d) { - if (key in d) { - delete d[key]; - } - } - else { - elm.removeAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase()); - } - } - } - for (key in dataset) { - if (oldDataset[key] !== dataset[key]) { - if (d) { - d[key] = dataset[key]; - } - else { - elm.setAttribute('data-' + key.replace(CAPS_REGEX, '-$&').toLowerCase(), dataset[key]); - } - } - } +function maj (x, y, z) { + return (x & y) | (z & (x | y)) } -exports.datasetModule = { create: updateDataset, update: updateDataset }; -exports.default = exports.datasetModule; -},{}],40:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function updateProps(oldVnode, vnode) { - var key, cur, old, elm = vnode.elm, oldProps = oldVnode.data.props, props = vnode.data.props; - if (!oldProps && !props) - return; - if (oldProps === props) - return; - oldProps = oldProps || {}; - props = props || {}; - for (key in oldProps) { - if (!props[key]) { - delete elm[key]; - } - } - for (key in props) { - cur = props[key]; - old = oldProps[key]; - if (old !== cur && (key !== 'value' || elm[key] !== cur)) { - elm[key] = cur; - } - } +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) } -exports.propsModule = { create: updateProps, update: updateProps }; -exports.default = exports.propsModule; -},{}],41:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -// Bindig `requestAnimationFrame` like this fixes a bug in IE/Edge. See #360 and #409. -var raf = (typeof window !== 'undefined' && (window.requestAnimationFrame).bind(window)) || setTimeout; -var nextFrame = function (fn) { raf(function () { raf(fn); }); }; -var reflowForced = false; -function setNextFrame(obj, prop, val) { - nextFrame(function () { obj[prop] = val; }); +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) } -function updateStyle(oldVnode, vnode) { - var cur, name, elm = vnode.elm, oldStyle = oldVnode.data.style, style = vnode.data.style; - if (!oldStyle && !style) - return; - if (oldStyle === style) - return; - oldStyle = oldStyle || {}; - style = style || {}; - var oldHasDel = 'delayed' in oldStyle; - for (name in oldStyle) { - if (!style[name]) { - if (name[0] === '-' && name[1] === '-') { - elm.style.removeProperty(name); - } - else { - elm.style[name] = ''; - } - } - } - for (name in style) { - cur = style[name]; - if (name === 'delayed' && style.delayed) { - for (var name2 in style.delayed) { - cur = style.delayed[name2]; - if (!oldHasDel || cur !== oldStyle.delayed[name2]) { - setNextFrame(elm.style, name2, cur); - } - } - } - else if (name !== 'remove' && cur !== oldStyle[name]) { - if (name[0] === '-' && name[1] === '-') { - elm.style.setProperty(name, cur); - } - else { - elm.style[name] = cur; - } - } - } + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) } -function applyDestroyStyle(vnode) { - var style, name, elm = vnode.elm, s = vnode.data.style; - if (!s || !(style = s.destroy)) - return; - for (name in style) { - elm.style[name] = style[name]; - } + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) } -function applyRemoveStyle(vnode, rm) { - var s = vnode.data.style; - if (!s || !s.remove) { - rm(); - return; - } - if (!reflowForced) { - getComputedStyle(document.body).transform; - reflowForced = true; - } - var name, elm = vnode.elm, i = 0, compStyle, style = s.remove, amount = 0, applied = []; - for (name in style) { - applied.push(name); - elm.style[name] = style[name]; - } - compStyle = getComputedStyle(elm); - var props = compStyle['transition-property'].split(', '); - for (; i < props.length; ++i) { - if (applied.indexOf(props[i]) !== -1) - amount++; - } - elm.addEventListener('transitionend', function (ev) { - if (ev.target === elm) - --amount; - if (amount === 0) - rm(); - }); + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) } -function forceReflow() { - reflowForced = false; + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) } -exports.styleModule = { - pre: forceReflow, - create: updateStyle, - update: updateStyle, - destroy: applyDestroyStyle, - remove: applyRemoveStyle -}; -exports.default = exports.styleModule; -},{}],42:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var vnode_1 = require("./vnode"); -var is = require("./is"); -var htmldomapi_1 = require("./htmldomapi"); -function isUndef(s) { return s === undefined; } -function isDef(s) { return s !== undefined; } -var emptyNode = vnode_1.default('', {}, [], undefined, undefined); -function sameVnode(vnode1, vnode2) { - return vnode1.key === vnode2.key && vnode1.sel === vnode2.sel; -} -function isVnode(vnode) { - return vnode.sel !== undefined; -} -function createKeyToOldIdx(children, beginIdx, endIdx) { - var i, map = {}, key, ch; - for (i = beginIdx; i <= endIdx; ++i) { - ch = children[i]; - if (ch != null) { - key = ch.key; - if (key !== undefined) - map[key] = i; - } - } - return map; -} -var hooks = ['create', 'update', 'remove', 'destroy', 'pre', 'post']; -var h_1 = require("./h"); -exports.h = h_1.h; -var thunk_1 = require("./thunk"); -exports.thunk = thunk_1.thunk; -function init(modules, domApi) { - var i, j, cbs = {}; - var api = domApi !== undefined ? domApi : htmldomapi_1.default; - for (i = 0; i < hooks.length; ++i) { - cbs[hooks[i]] = []; - for (j = 0; j < modules.length; ++j) { - var hook = modules[j][hooks[i]]; - if (hook !== undefined) { - cbs[hooks[i]].push(hook); - } - } - } - function emptyNodeAt(elm) { - var id = elm.id ? '#' + elm.id : ''; - var c = elm.className ? '.' + elm.className.split(' ').join('.') : ''; - return vnode_1.default(api.tagName(elm).toLowerCase() + id + c, {}, [], undefined, elm); - } - function createRmCb(childElm, listeners) { - return function rmCb() { - if (--listeners === 0) { - var parent_1 = api.parentNode(childElm); - api.removeChild(parent_1, childElm); - } - }; - } - function createElm(vnode, insertedVnodeQueue) { - var i, data = vnode.data; - if (data !== undefined) { - if (isDef(i = data.hook) && isDef(i = i.init)) { - i(vnode); - data = vnode.data; - } - } - var children = vnode.children, sel = vnode.sel; - if (sel === '!') { - if (isUndef(vnode.text)) { - vnode.text = ''; - } - vnode.elm = api.createComment(vnode.text); - } - else if (sel !== undefined) { - // Parse selector - var hashIdx = sel.indexOf('#'); - var dotIdx = sel.indexOf('.', hashIdx); - var hash = hashIdx > 0 ? hashIdx : sel.length; - var dot = dotIdx > 0 ? dotIdx : sel.length; - var tag = hashIdx !== -1 || dotIdx !== -1 ? sel.slice(0, Math.min(hash, dot)) : sel; - var elm = vnode.elm = isDef(data) && isDef(i = data.ns) ? api.createElementNS(i, tag) - : api.createElement(tag); - if (hash < dot) - elm.setAttribute('id', sel.slice(hash + 1, dot)); - if (dotIdx > 0) - elm.setAttribute('class', sel.slice(dot + 1).replace(/\./g, ' ')); - for (i = 0; i < cbs.create.length; ++i) - cbs.create[i](emptyNode, vnode); - if (is.array(children)) { - for (i = 0; i < children.length; ++i) { - var ch = children[i]; - if (ch != null) { - api.appendChild(elm, createElm(ch, insertedVnodeQueue)); - } - } - } - else if (is.primitive(vnode.text)) { - api.appendChild(elm, api.createTextNode(vnode.text)); - } - i = vnode.data.hook; // Reuse variable - if (isDef(i)) { - if (i.create) - i.create(emptyNode, vnode); - if (i.insert) - insertedVnodeQueue.push(vnode); - } - } - else { - vnode.elm = api.createTextNode(vnode.text); - } - return vnode.elm; - } - function addVnodes(parentElm, before, vnodes, startIdx, endIdx, insertedVnodeQueue) { - for (; startIdx <= endIdx; ++startIdx) { - var ch = vnodes[startIdx]; - if (ch != null) { - api.insertBefore(parentElm, createElm(ch, insertedVnodeQueue), before); - } - } - } - function invokeDestroyHook(vnode) { - var i, j, data = vnode.data; - if (data !== undefined) { - if (isDef(i = data.hook) && isDef(i = i.destroy)) - i(vnode); - for (i = 0; i < cbs.destroy.length; ++i) - cbs.destroy[i](vnode); - if (vnode.children !== undefined) { - for (j = 0; j < vnode.children.length; ++j) { - i = vnode.children[j]; - if (i != null && typeof i !== "string") { - invokeDestroyHook(i); - } - } - } - } - } - function removeVnodes(parentElm, vnodes, startIdx, endIdx) { - for (; startIdx <= endIdx; ++startIdx) { - var i_1 = void 0, listeners = void 0, rm = void 0, ch = vnodes[startIdx]; - if (ch != null) { - if (isDef(ch.sel)) { - invokeDestroyHook(ch); - listeners = cbs.remove.length + 1; - rm = createRmCb(ch.elm, listeners); - for (i_1 = 0; i_1 < cbs.remove.length; ++i_1) - cbs.remove[i_1](ch, rm); - if (isDef(i_1 = ch.data) && isDef(i_1 = i_1.hook) && isDef(i_1 = i_1.remove)) { - i_1(ch, rm); - } - else { - rm(); - } - } - else { - api.removeChild(parentElm, ch.elm); - } - } - } - } - function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue) { - var oldStartIdx = 0, newStartIdx = 0; - var oldEndIdx = oldCh.length - 1; - var oldStartVnode = oldCh[0]; - var oldEndVnode = oldCh[oldEndIdx]; - var newEndIdx = newCh.length - 1; - var newStartVnode = newCh[0]; - var newEndVnode = newCh[newEndIdx]; - var oldKeyToIdx; - var idxInOld; - var elmToMove; - var before; - while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { - if (oldStartVnode == null) { - oldStartVnode = oldCh[++oldStartIdx]; // Vnode might have been moved left - } - else if (oldEndVnode == null) { - oldEndVnode = oldCh[--oldEndIdx]; - } - else if (newStartVnode == null) { - newStartVnode = newCh[++newStartIdx]; - } - else if (newEndVnode == null) { - newEndVnode = newCh[--newEndIdx]; - } - else if (sameVnode(oldStartVnode, newStartVnode)) { - patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); - oldStartVnode = oldCh[++oldStartIdx]; - newStartVnode = newCh[++newStartIdx]; - } - else if (sameVnode(oldEndVnode, newEndVnode)) { - patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); - oldEndVnode = oldCh[--oldEndIdx]; - newEndVnode = newCh[--newEndIdx]; - } - else if (sameVnode(oldStartVnode, newEndVnode)) { - patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); - api.insertBefore(parentElm, oldStartVnode.elm, api.nextSibling(oldEndVnode.elm)); - oldStartVnode = oldCh[++oldStartIdx]; - newEndVnode = newCh[--newEndIdx]; - } - else if (sameVnode(oldEndVnode, newStartVnode)) { - patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); - api.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); - oldEndVnode = oldCh[--oldEndIdx]; - newStartVnode = newCh[++newStartIdx]; - } - else { - if (oldKeyToIdx === undefined) { - oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); - } - idxInOld = oldKeyToIdx[newStartVnode.key]; - if (isUndef(idxInOld)) { - api.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm); - newStartVnode = newCh[++newStartIdx]; - } - else { - elmToMove = oldCh[idxInOld]; - if (elmToMove.sel !== newStartVnode.sel) { - api.insertBefore(parentElm, createElm(newStartVnode, insertedVnodeQueue), oldStartVnode.elm); - } - else { - patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); - oldCh[idxInOld] = undefined; - api.insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm); - } - newStartVnode = newCh[++newStartIdx]; - } - } - } - if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) { - if (oldStartIdx > oldEndIdx) { - before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm; - addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); - } - else { - removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); - } - } - } - function patchVnode(oldVnode, vnode, insertedVnodeQueue) { - var i, hook; - if (isDef(i = vnode.data) && isDef(hook = i.hook) && isDef(i = hook.prepatch)) { - i(oldVnode, vnode); - } - var elm = vnode.elm = oldVnode.elm; - var oldCh = oldVnode.children; - var ch = vnode.children; - if (oldVnode === vnode) - return; - if (vnode.data !== undefined) { - for (i = 0; i < cbs.update.length; ++i) - cbs.update[i](oldVnode, vnode); - i = vnode.data.hook; - if (isDef(i) && isDef(i = i.update)) - i(oldVnode, vnode); - } - if (isUndef(vnode.text)) { - if (isDef(oldCh) && isDef(ch)) { - if (oldCh !== ch) - updateChildren(elm, oldCh, ch, insertedVnodeQueue); - } - else if (isDef(ch)) { - if (isDef(oldVnode.text)) - api.setTextContent(elm, ''); - addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); - } - else if (isDef(oldCh)) { - removeVnodes(elm, oldCh, 0, oldCh.length - 1); - } - else if (isDef(oldVnode.text)) { - api.setTextContent(elm, ''); - } - } - else if (oldVnode.text !== vnode.text) { - if (isDef(oldCh)) { - removeVnodes(elm, oldCh, 0, oldCh.length - 1); - } - api.setTextContent(elm, vnode.text); - } - if (isDef(hook) && isDef(i = hook.postpatch)) { - i(oldVnode, vnode); - } - } - return function patch(oldVnode, vnode) { - var i, elm, parent; - var insertedVnodeQueue = []; - for (i = 0; i < cbs.pre.length; ++i) - cbs.pre[i](); - if (!isVnode(oldVnode)) { - oldVnode = emptyNodeAt(oldVnode); - } - if (sameVnode(oldVnode, vnode)) { - patchVnode(oldVnode, vnode, insertedVnodeQueue); - } - else { - elm = oldVnode.elm; - parent = api.parentNode(elm); - createElm(vnode, insertedVnodeQueue); - if (parent !== null) { - api.insertBefore(parent, vnode.elm, api.nextSibling(elm)); - removeVnodes(parent, [oldVnode], 0, 0); - } - } - for (i = 0; i < insertedVnodeQueue.length; ++i) { - insertedVnodeQueue[i].data.hook.insert(insertedVnodeQueue[i]); - } - for (i = 0; i < cbs.post.length; ++i) - cbs.post[i](); - return vnode; - }; +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 } -exports.init = init; - -},{"./h":34,"./htmldomapi":35,"./is":36,"./thunk":43,"./vnode":45}],43:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var h_1 = require("./h"); -function copyToThunk(vnode, thunk) { - thunk.elm = vnode.elm; - vnode.data.fn = thunk.data.fn; - vnode.data.args = thunk.data.args; - thunk.data = vnode.data; - thunk.children = vnode.children; - thunk.text = vnode.text; - thunk.elm = vnode.elm; -} -function init(thunk) { - var cur = thunk.data; - var vnode = cur.fn.apply(undefined, cur.args); - copyToThunk(vnode, thunk); -} -function prepatch(oldVnode, thunk) { - var i, old = oldVnode.data, cur = thunk.data; - var oldArgs = old.args, args = cur.args; - if (old.fn !== cur.fn || oldArgs.length !== args.length) { - copyToThunk(cur.fn.apply(undefined, args), thunk); - return; - } - for (i = 0; i < args.length; ++i) { - if (oldArgs[i] !== args[i]) { - copyToThunk(cur.fn.apply(undefined, args), thunk); - return; - } - } - copyToThunk(oldVnode, thunk); + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 } -exports.thunk = function thunk(sel, key, fn, args) { - if (args === undefined) { - args = fn; - fn = key; - key = undefined; - } - return h_1.h(sel, { - key: key, - hook: { init: init, prepatch: prepatch }, - fn: fn, - args: args - }); -}; -exports.default = exports.thunk; - -},{"./h":34}],44:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var vnode_1 = require("./vnode"); -var htmldomapi_1 = require("./htmldomapi"); -function toVNode(node, domApi) { - var api = domApi !== undefined ? domApi : htmldomapi_1.default; - var text; - if (api.isElement(node)) { - var id = node.id ? '#' + node.id : ''; - var cn = node.getAttribute('class'); - var c = cn ? '.' + cn.split(' ').join('.') : ''; - var sel = api.tagName(node).toLowerCase() + id + c; - var attrs = {}; - var children = []; - var name_1; - var i = void 0, n = void 0; - var elmAttrs = node.attributes; - var elmChildren = node.childNodes; - for (i = 0, n = elmAttrs.length; i < n; i++) { - name_1 = elmAttrs[i].nodeName; - if (name_1 !== 'id' && name_1 !== 'class') { - attrs[name_1] = elmAttrs[i].nodeValue; - } - } - for (i = 0, n = elmChildren.length; i < n; i++) { - children.push(toVNode(elmChildren[i], domApi)); - } - return vnode_1.default(sel, { attrs: attrs }, children, undefined, node); - } - else if (api.isText(node)) { - text = api.getTextContent(node); - return vnode_1.default(undefined, undefined, undefined, text, node); - } - else if (api.isComment(node)) { - text = api.getTextContent(node); - return vnode_1.default('!', {}, [], text, node); + +Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 + +},{"./hash":143,"inherits":101,"safe-buffer":142}],151:[function(require,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. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// 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(); + } } - else { - return vnode_1.default('', {}, [], undefined, node); + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); } -} -exports.toVNode = toVNode; -exports.default = toVNode; + } -},{"./htmldomapi":35,"./vnode":45}],45:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -function vnode(sel, data, children, text, elm) { - var key = data === undefined ? undefined : data.key; - return { sel: sel, data: data, children: children, - text: text, elm: elm, key: key }; -} -exports.vnode = vnode; -exports.default = vnode; + dest.on('drain', ondrain); -},{}],46:[function(require,module,exports){ -(function (global){ -'use strict'; + // 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); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; -var _ponyfill = require('./ponyfill.js'); + dest.end(); + } -var _ponyfill2 = _interopRequireDefault(_ponyfill); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + function onclose() { + if (didOnEnd) return; + didOnEnd = true; -var root; /* global window */ + 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. + } + } -if (typeof self !== 'undefined') { - root = self; -} else if (typeof window !== 'undefined') { - root = window; -} else if (typeof global !== 'undefined') { - root = global; -} else if (typeof module !== 'undefined') { - root = module; -} else { - root = Function('return this')(); -} + source.on('error', onerror); + dest.on('error', onerror); -var result = (0, _ponyfill2['default'])(root); -exports['default'] = result; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); -},{"./ponyfill.js":47}],47:[function(require,module,exports){ -'use strict'; + source.removeListener('end', onend); + source.removeListener('close', onclose); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports['default'] = symbolObservablePonyfill; -function symbolObservablePonyfill(root) { - var result; - var _Symbol = root.Symbol; - - if (typeof _Symbol === 'function') { - if (_Symbol.observable) { - result = _Symbol.observable; - } else { - result = _Symbol('observable'); - _Symbol.observable = result; - } - } else { - result = '@@observable'; - } - - return result; -}; -},{}],48:[function(require,module,exports){ -(function (setImmediate,clearImmediate){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; + source.removeListener('error', onerror); + dest.removeListener('error', onerror); -// DOM APIs, for completeness + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); -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(); }; + dest.removeListener('close', cleanup); + } -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); -}; + source.on('end', cleanup); + source.on('close', cleanup); -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; + dest.on('close', cleanup); -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; }; -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); +},{"events":82,"inherits":101,"readable-stream/duplex.js":128,"readable-stream/passthrough.js":137,"readable-stream/readable.js":138,"readable-stream/transform.js":139,"readable-stream/writable.js":140}],152:[function(require,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. - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + 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; } }; -// 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); +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; - immediateIds[id] = true; +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} - 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); - } - }); +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} - return id; +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; }; -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; }; -}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":25,"timers":48}],49:[function(require,module,exports){ -"use strict"; -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", { value: true }); -__export(require("./selectorParser")); -var matches_1 = require("./matches"); -exports.createMatches = matches_1.createMatches; -var querySelector_1 = require("./querySelector"); -exports.createQuerySelector = querySelector_1.createQuerySelector; - -},{"./matches":50,"./querySelector":51,"./selectorParser":52}],50:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var selectorParser_1 = require("./selectorParser"); -function createMatches(opts) { - return function matches(selector, node) { - var _a = typeof selector === 'object' ? selector : selectorParser_1.parseSelector(selector), tag = _a.tag, id = _a.id, classList = _a.classList, attributes = _a.attributes, nextSelector = _a.nextSelector, pseudos = _a.pseudos; - if (nextSelector !== undefined) { - throw new Error('matches can only process selectors that target a single element'); - } - if (!node) { - return false; - } - if (tag && tag.toLowerCase() !== opts.tag(node).toLowerCase()) { - return false; - } - if (id && id !== opts.id(node)) { - return false; - } - var classes = opts.className(node).split(' '); - for (var i = 0; i < classList.length; i++) { - if (classes.indexOf(classList[i]) === -1) { - return false; - } - } - for (var key in attributes) { - var attr = opts.attr(node, key); - var t = attributes[key][0]; - var v = attributes[key][1]; - if (attr === undefined) { - return false; - } - if (t === 'has') { - return true; - } - if (t === 'exact' && attr !== v) { - return false; - } - else if (t !== 'exact') { - if (typeof v !== 'string') { - throw new Error('All non-string values have to be an exact match'); - } - if (t === 'startsWith' && !attr.startsWith(v)) { - return false; - } - if (t === 'endsWith' && !attr.endsWith(v)) { - return false; - } - if (t === 'contains' && attr.indexOf(v) === -1) { - return false; - } - if (t === 'whitespace' && attr.split(' ').indexOf(v) === -1) { - return false; - } - if (t === 'dash' && attr.split('-').indexOf(v) === -1) { - return false; - } - } - } - for (var i = 0; i < pseudos.length; i++) { - var _b = pseudos[i], t = _b[0], data = _b[1]; - if (t === 'contains' && data !== opts.contents(node)) { - return false; - } - if (t === 'empty' && - (opts.contents(node) || opts.children(node).length !== 0)) { - return false; - } - if (t === 'root' && opts.parent(node) !== undefined) { - return false; - } - if (t.indexOf('child') !== -1) { - if (!opts.parent(node)) { - return false; - } - var siblings = opts.children(opts.parent(node)); - if (t === 'first-child' && siblings.indexOf(node) !== 0) { - return false; - } - if (t === 'last-child' && - siblings.indexOf(node) !== siblings.length - 1) { - return false; - } - if (t === 'nth-child') { - var regex = /([\+-]?)(\d*)(n?)(\+\d+)?/; - var parseResult = regex.exec(data).slice(1); - var index = siblings.indexOf(node); - if (!parseResult[0]) { - parseResult[0] = '+'; - } - var factor = parseResult[1] - ? parseInt(parseResult[0] + parseResult[1]) - : undefined; - var add = parseInt(parseResult[3] || '0'); - if (factor && - parseResult[2] === 'n' && - index % factor !== add) { - return false; - } - else if (!factor && - parseResult[2] && - ((parseResult[0] === '+' && index - add < 0) || - (parseResult[0] === '-' && index - add >= 0))) { - return false; - } - else if (!parseResult[2] && factor && - index !== factor - 1) { - return false; - } - } - } - } - return true; - }; +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; } -exports.createMatches = createMatches; - -},{"./selectorParser":52}],51:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var selectorParser_1 = require("./selectorParser"); -var matches_1 = require("./matches"); -function createQuerySelector(options, matches) { - var _matches = matches || matches_1.createMatches(options); - function findSubtree(selector, depth, node) { - if (!node) { - return []; - } - var n = _matches(selector, node); - var matched = n ? (typeof n === 'object' ? [n] : [node]) : []; - if (depth === 0) { - return matched; - } - var childMatched = options - .children(node) - .filter(function (c) { return typeof c !== 'string'; }) - .map(function (c) { return findSubtree(selector, depth - 1, c); }) - .reduce(function (acc, curr) { return acc.concat(curr); }, []); - return matched.concat(childMatched); - } - function findSibling(selector, next, node) { - if (!node || options.parent(node) === undefined) { - return []; - } - var results = []; - var siblings = options.children(options.parent(node)); - for (var i = siblings.indexOf(node) + 1; i < siblings.length; i++) { - if (typeof siblings[i] === 'string') { - continue; - } - var n = _matches(selector, siblings[i]); - if (n) { - if (typeof n === 'object') { - results.push(n); - } - else { - results.push(siblings[i]); - } - } - if (next) { - break; - } - } - return results; + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } - return function querySelector(selector, node) { - if (!node) { - return []; - } - var sel = typeof selector === 'object' ? selector : selectorParser_1.parseSelector(selector); - var results = [node]; - var currentSelector = sel; - var currentCombinator = 'subtree'; - var tail = undefined; - var _loop_1 = function () { - tail = currentSelector.nextSelector; - currentSelector.nextSelector = undefined; - if (currentCombinator === 'subtree' || - currentCombinator === 'child') { - var depth_1 = currentCombinator === 'subtree' ? Infinity : 1; - results = results - .map(function (n) { return findSubtree(currentSelector, depth_1, n); }) - .reduce(function (acc, curr) { return acc.concat(curr); }, []); - } - else { - var next_1 = currentCombinator === 'nextSibling'; - results = results - .map(function (n) { return findSibling(currentSelector, next_1, n); }) - .reduce(function (acc, curr) { return acc.concat(curr); }, []); - } - if (tail) { - currentSelector = tail[1]; - currentCombinator = tail[0]; - } - }; - do { - _loop_1(); - } while (tail !== undefined); - return results; - }; + return nb; + } + return 0; } -exports.createQuerySelector = createQuerySelector; -},{"./matches":50,"./selectorParser":52}],52:[function(require,module,exports){ -"use strict"; -var __assign = (this && this.__assign) || Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; } - return t; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -var IDENT = '[\\w-]+'; -var SPACE = '[ \t]*'; -var VALUE = "[^\\]]+"; -var CLASS = "(?:\\." + IDENT + ")"; -var ID = "(?:#" + IDENT + ")"; -var OP = "(?:=|\\$=|\\^=|\\*=|~=|\\|=)"; -var ATTR = "(?:\\[" + SPACE + IDENT + SPACE + "(?:" + OP + SPACE + VALUE + SPACE + ")?\\])"; -var SUBTREE = "(?:[ \t]+)"; -var CHILD = "(?:" + SPACE + "(>)" + SPACE + ")"; -var NEXT_SIBLING = "(?:" + SPACE + "(\\+)" + SPACE + ")"; -var SIBLING = "(?:" + SPACE + "(~)" + SPACE + ")"; -var COMBINATOR = "(?:" + SUBTREE + "|" + CHILD + "|" + NEXT_SIBLING + "|" + SIBLING + ")"; -var CONTAINS = "contains\\(\"[^\"]*\"\\)"; -var FORMULA = "(?:even|odd|\\d*(?:-?n(?:\\+\\d+)?)?)"; -var NTH_CHILD = "nth-child\\(" + FORMULA + "\\)"; -var PSEUDO = ":(?:first-child|last-child|" + NTH_CHILD + "|empty|root|" + CONTAINS + ")"; -var TAG = "(:?" + IDENT + ")?"; -var TOKENS = CLASS + "|" + ID + "|" + ATTR + "|" + PSEUDO + "|" + COMBINATOR; -var combinatorRegex = new RegExp("^" + COMBINATOR + "$"); -/** - * Parses a css selector into a normalized object. - * Expects a selector for a single element only, no `>` or the like! - */ -function parseSelector(selector) { - var sel = selector.trim(); - var tagRegex = new RegExp(TAG, 'y'); - var tag = tagRegex.exec(sel)[0]; - var regex = new RegExp(TOKENS, 'y'); - regex.lastIndex = tagRegex.lastIndex; - var matches = []; - var nextSelector = undefined; - var lastCombinator = undefined; - var index = -1; - while (regex.lastIndex < sel.length) { - var match = regex.exec(sel); - if (!match && lastCombinator === undefined) { - throw new Error('Parse error, invalid selector'); - } - else if (match && combinatorRegex.test(match[0])) { - var comb = combinatorRegex.exec(match[0])[0]; - lastCombinator = comb; - index = regex.lastIndex; - } - else { - if (lastCombinator !== undefined) { - nextSelector = [ - getCombinator(lastCombinator), - parseSelector(sel.substring(index)) - ]; - break; - } - matches.push(match[0]); - } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } } - var classList = matches - .filter(function (s) { return s.startsWith('.'); }) - .map(function (s) { return s.substring(1); }); - var ids = matches.filter(function (s) { return s.startsWith('#'); }).map(function (s) { return s.substring(1); }); - if (ids.length > 1) { - throw new Error('Invalid selector, only one id is allowed'); - } - var postprocessRegex = new RegExp("(" + IDENT + ")" + SPACE + "(" + OP + ")?" + SPACE + "(" + VALUE + ")?"); - var attrs = matches - .filter(function (s) { return s.startsWith('['); }) - .map(function (s) { return postprocessRegex.exec(s).slice(1, 4); }) - .map(function (_a) { - var attr = _a[0], op = _a[1], val = _a[2]; - var _b; - return (_b = {}, - _b[attr] = [getOp(op), val ? parseAttrValue(val) : val], - _b); - }) - .reduce(function (acc, curr) { return (__assign({}, acc, curr)); }, {}); - var pseudos = matches - .filter(function (s) { return s.startsWith(':'); }) - .map(function (s) { return postProcessPseudos(s.substring(1)); }); - return { - id: ids[0] || '', - tag: tag, - classList: classList, - attributes: attrs, - nextSelector: nextSelector, - pseudos: pseudos - }; + } } -exports.parseSelector = parseSelector; -function parseAttrValue(v) { - if (v.startsWith('"')) { - return v.slice(1, -1); - } - if (v === "true") { - return true; - } - if (v === "false") { - return false; - } - var f = parseFloat(v); - if (isNaN(f)) { - return v; - } - return f; -} -function postProcessPseudos(sel) { - if (sel === 'first-child' || - sel === 'last-child' || - sel === 'root' || - sel === 'empty') { - return [sel, undefined]; - } - if (sel.startsWith('contains')) { - var text = sel.slice(10, -2); - return ['contains', text]; - } - var content = sel.slice(10, -1); - if (content === 'even') { - content = '2n'; - } - if (content === 'odd') { - content = '2n+1'; - } - return ['nth-child', content]; -} -function getOp(op) { - switch (op) { - case '=': - return 'exact'; - case '^=': - return 'startsWith'; - case '$=': - return 'endsWith'; - case '*=': - return 'contains'; - case '~=': - return 'whitespace'; - case '|=': - return 'dash'; - default: - return 'has'; - } -} -function getCombinator(comb) { - switch (comb.trim()) { - case '>': - return 'child'; - case '+': - return 'nextSibling'; - case '~': - return 'sibling'; - default: - return 'subtree'; - } -} - -},{}],53:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var index_1 = require("../index"); -var ConcatProducer = /** @class */ (function () { - function ConcatProducer(streams) { - this.streams = streams; - this.type = 'concat'; - this.out = null; - this.i = 0; - } - ConcatProducer.prototype._start = function (out) { - this.out = out; - this.streams[this.i]._add(this); - }; - ConcatProducer.prototype._stop = function () { - var streams = this.streams; - if (this.i < streams.length) { - streams[this.i]._remove(this); - } - this.i = 0; - this.out = null; - }; - ConcatProducer.prototype._n = function (t) { - var u = this.out; - if (!u) - return; - u._n(t); - }; - ConcatProducer.prototype._e = function (err) { - var u = this.out; - if (!u) - return; - u._e(err); - }; - ConcatProducer.prototype._c = function () { - var u = this.out; - if (!u) - return; - var streams = this.streams; - streams[this.i]._remove(this); - if (++this.i < streams.length) { - streams[this.i]._add(this); - } - else { - u._c(); - } - }; - return ConcatProducer; -}()); -/** - * Puts one stream after the other. *concat* is a factory that takes multiple - * streams as arguments, and starts the `n+1`-th stream only when the `n`-th - * stream has completed. It concatenates those streams together. - * - * Marble diagram: - * - * ```text - * --1--2---3---4-| - * ...............--a-b-c--d-| - * concat - * --1--2---3---4---a-b-c--d-| - * ``` - * - * Example: - * - * ```js - * import concat from 'xstream/extra/concat' - * - * const streamA = xs.of('a', 'b', 'c') - * const streamB = xs.of(10, 20, 30) - * const streamC = xs.of('X', 'Y', 'Z') - * - * const outputStream = concat(streamA, streamB, streamC) - * - * outputStream.addListener({ - * next: (x) => console.log(x), - * error: (err) => console.error(err), - * complete: () => console.log('concat completed'), - * }) - * ``` - * - * @factory true - * @param {Stream} stream1 A stream to concatenate together with other streams. - * @param {Stream} stream2 A stream to concatenate together with other streams. Two - * or more streams may be given as arguments. - * @return {Stream} - */ -function concat() { - var streams = []; - for (var _i = 0; _i < arguments.length; _i++) { - streams[_i] = arguments[_i]; - } - return new index_1.Stream(new ConcatProducer(streams)); -} -exports.default = concat; - -},{"../index":55}],54:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var index_1 = require("../index"); -var NO = {}; -var SampleCombineListener = /** @class */ (function () { - function SampleCombineListener(i, p) { - this.i = i; - this.p = p; - p.ils[i] = this; - } - SampleCombineListener.prototype._n = function (t) { - var p = this.p; - if (p.out === NO) - return; - p.up(t, this.i); - }; - SampleCombineListener.prototype._e = function (err) { - this.p._e(err); - }; - SampleCombineListener.prototype._c = function () { - this.p.down(this.i, this); - }; - return SampleCombineListener; -}()); -exports.SampleCombineListener = SampleCombineListener; -var SampleCombineOperator = /** @class */ (function () { - function SampleCombineOperator(ins, streams) { - this.type = 'sampleCombine'; - this.ins = ins; - this.others = streams; - this.out = NO; - this.ils = []; - this.Nn = 0; - this.vals = []; - } - SampleCombineOperator.prototype._start = function (out) { - this.out = out; - var s = this.others; - var n = this.Nn = s.length; - var vals = this.vals = new Array(n); - for (var i = 0; i < n; i++) { - vals[i] = NO; - s[i]._add(new SampleCombineListener(i, this)); - } - this.ins._add(this); - }; - SampleCombineOperator.prototype._stop = function () { - var s = this.others; - var n = s.length; - var ils = this.ils; - this.ins._remove(this); - for (var i = 0; i < n; i++) { - s[i]._remove(ils[i]); - } - this.out = NO; - this.vals = []; - this.ils = []; - }; - SampleCombineOperator.prototype._n = function (t) { - var out = this.out; - if (out === NO) - return; - if (this.Nn > 0) - return; - out._n([t].concat(this.vals)); - }; - SampleCombineOperator.prototype._e = function (err) { - var out = this.out; - if (out === NO) - return; - out._e(err); - }; - SampleCombineOperator.prototype._c = function () { - var out = this.out; - if (out === NO) - return; - out._c(); - }; - SampleCombineOperator.prototype.up = function (t, i) { - var v = this.vals[i]; - if (this.Nn > 0 && v === NO) { - this.Nn--; - } - this.vals[i] = t; - }; - SampleCombineOperator.prototype.down = function (i, l) { - this.others[i]._remove(l); - }; - return SampleCombineOperator; -}()); -exports.SampleCombineOperator = SampleCombineOperator; -var sampleCombine; -/** - * - * Combines a source stream with multiple other streams. The result stream - * will emit the latest events from all input streams, but only when the - * source stream emits. - * - * If the source, or any input stream, throws an error, the result stream - * will propagate the error. If any input streams end, their final emitted - * value will remain in the array of any subsequent events from the result - * stream. - * - * The result stream will only complete upon completion of the source stream. - * - * Marble diagram: - * - * ```text - * --1----2-----3--------4--- (source) - * ----a-----b-----c--d------ (other) - * sampleCombine - * -------2a----3b-------4d-- - * ``` - * - * Examples: - * - * ```js - * import sampleCombine from 'xstream/extra/sampleCombine' - * import xs from 'xstream' - * - * const sampler = xs.periodic(1000).take(3) - * const other = xs.periodic(100) - * - * const stream = sampler.compose(sampleCombine(other)) - * - * stream.addListener({ - * next: i => console.log(i), - * error: err => console.error(err), - * complete: () => console.log('completed') - * }) - * ``` - * - * ```text - * > [0, 8] - * > [1, 18] - * > [2, 28] - * ``` - * - * ```js - * import sampleCombine from 'xstream/extra/sampleCombine' - * import xs from 'xstream' - * - * const sampler = xs.periodic(1000).take(3) - * const other = xs.periodic(100).take(2) - * - * const stream = sampler.compose(sampleCombine(other)) - * - * stream.addListener({ - * next: i => console.log(i), - * error: err => console.error(err), - * complete: () => console.log('completed') - * }) - * ``` - * - * ```text - * > [0, 1] - * > [1, 1] - * > [2, 1] - * ``` - * - * @param {...Stream} streams One or more streams to combine with the sampler - * stream. - * @return {Stream} - */ -sampleCombine = function sampleCombine() { - var streams = []; - for (var _i = 0; _i < arguments.length; _i++) { - streams[_i] = arguments[_i]; + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } } - return function sampleCombineOperator(sampler) { - return new index_1.Stream(new SampleCombineOperator(sampler, streams)); - }; -}; -exports.default = sampleCombine; + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} -},{"../index":55}],55:[function(require,module,exports){ -"use strict"; -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -var symbol_observable_1 = require("symbol-observable"); -var NO = {}; -exports.NO = NO; -function noop() { } -function cp(a) { - var l = a.length; - var b = Array(l); - for (var i = 0; i < l; ++i) - b[i] = a[i]; - return b; -} -function and(f1, f2) { - return function andFn(t) { - return f1(t) && f2(t); - }; +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; } -function _try(c, t, u) { - try { - return c.f(t); - } - catch (e) { - u._e(e); - return NO; - } -} -var NO_IL = { - _n: noop, - _e: noop, - _c: noop, -}; -exports.NO_IL = NO_IL; -// mutates the input -function internalizeProducer(producer) { - producer._start = function _start(il) { - il.next = il._n; - il.error = il._e; - il.complete = il._c; - this.start(il); - }; - producer._stop = producer.stop; + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); } -var StreamSub = /** @class */ (function () { - function StreamSub(_stream, _listener) { - this._stream = _stream; - this._listener = _listener; - } - StreamSub.prototype.unsubscribe = function () { - this._stream._remove(this._listener); - }; - return StreamSub; -}()); -var Observer = /** @class */ (function () { - function Observer(_listener) { - this._listener = _listener; - } - Observer.prototype.next = function (value) { - this._listener._n(value); - }; - Observer.prototype.error = function (err) { - this._listener._e(err); - }; - Observer.prototype.complete = function () { - this._listener._c(); - }; - return Observer; -}()); -var FromObservable = /** @class */ (function () { - function FromObservable(observable) { - this.type = 'fromObservable'; - this.ins = observable; - this.active = false; - } - FromObservable.prototype._start = function (out) { - this.out = out; - this.active = true; - this._sub = this.ins.subscribe(new Observer(out)); - if (!this.active) - this._sub.unsubscribe(); - }; - FromObservable.prototype._stop = function () { - if (this._sub) - this._sub.unsubscribe(); - this.active = false; - }; - return FromObservable; -}()); -var Merge = /** @class */ (function () { - function Merge(insArr) { - this.type = 'merge'; - this.insArr = insArr; - this.out = NO; - this.ac = 0; - } - Merge.prototype._start = function (out) { - this.out = out; - var s = this.insArr; - var L = s.length; - this.ac = L; - for (var i = 0; i < L; i++) - s[i]._add(this); - }; - Merge.prototype._stop = function () { - var s = this.insArr; - var L = s.length; - for (var i = 0; i < L; i++) - s[i]._remove(this); - this.out = NO; - }; - Merge.prototype._n = function (t) { - var u = this.out; - if (u === NO) - return; - u._n(t); - }; - Merge.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - Merge.prototype._c = function () { - if (--this.ac <= 0) { - var u = this.out; - if (u === NO) - return; - u._c(); - } - }; - return Merge; -}()); -var CombineListener = /** @class */ (function () { - function CombineListener(i, out, p) { - this.i = i; - this.out = out; - this.p = p; - p.ils.push(this); - } - CombineListener.prototype._n = function (t) { - var p = this.p, out = this.out; - if (out === NO) - return; - if (p.up(t, this.i)) { - var a = p.vals; - var l = a.length; - var b = Array(l); - for (var i = 0; i < l; ++i) - b[i] = a[i]; - out._n(b); - } - }; - CombineListener.prototype._e = function (err) { - var out = this.out; - if (out === NO) - return; - out._e(err); - }; - CombineListener.prototype._c = function () { - var p = this.p; - if (p.out === NO) - return; - if (--p.Nc === 0) - p.out._c(); - }; - return CombineListener; -}()); -var Combine = /** @class */ (function () { - function Combine(insArr) { - this.type = 'combine'; - this.insArr = insArr; - this.out = NO; - this.ils = []; - this.Nc = this.Nn = 0; - this.vals = []; - } - Combine.prototype.up = function (t, i) { - var v = this.vals[i]; - var Nn = !this.Nn ? 0 : v === NO ? --this.Nn : this.Nn; - this.vals[i] = t; - return Nn === 0; - }; - Combine.prototype._start = function (out) { - this.out = out; - var s = this.insArr; - var n = this.Nc = this.Nn = s.length; - var vals = this.vals = new Array(n); - if (n === 0) { - out._n([]); - out._c(); - } - else { - for (var i = 0; i < n; i++) { - vals[i] = NO; - s[i]._add(new CombineListener(i, out, this)); - } - } - }; - Combine.prototype._stop = function () { - var s = this.insArr; - var n = s.length; - var ils = this.ils; - for (var i = 0; i < n; i++) - s[i]._remove(ils[i]); - this.out = NO; - this.ils = []; - this.vals = []; - }; - return Combine; -}()); -var FromArray = /** @class */ (function () { - function FromArray(a) { - this.type = 'fromArray'; - this.a = a; - } - FromArray.prototype._start = function (out) { - var a = this.a; - for (var i = 0, n = a.length; i < n; i++) - out._n(a[i]); - out._c(); - }; - FromArray.prototype._stop = function () { - }; - return FromArray; -}()); -var FromPromise = /** @class */ (function () { - function FromPromise(p) { - this.type = 'fromPromise'; - this.on = false; - this.p = p; - } - FromPromise.prototype._start = function (out) { - var prod = this; - this.on = true; - this.p.then(function (v) { - if (prod.on) { - out._n(v); - out._c(); - } - }, function (e) { - out._e(e); - }).then(noop, function (err) { - setTimeout(function () { throw err; }); - }); - }; - FromPromise.prototype._stop = function () { - this.on = false; - }; - return FromPromise; -}()); -var Periodic = /** @class */ (function () { - function Periodic(period) { - this.type = 'periodic'; - this.period = period; - this.intervalID = -1; - this.i = 0; - } - Periodic.prototype._start = function (out) { - var self = this; - function intervalHandler() { out._n(self.i++); } - this.intervalID = setInterval(intervalHandler, this.period); - }; - Periodic.prototype._stop = function () { - if (this.intervalID !== -1) - clearInterval(this.intervalID); - this.intervalID = -1; - this.i = 0; - }; - return Periodic; -}()); -var Debug = /** @class */ (function () { - function Debug(ins, arg) { - this.type = 'debug'; - this.ins = ins; - this.out = NO; - this.s = noop; - this.l = ''; - if (typeof arg === 'string') - this.l = arg; - else if (typeof arg === 'function') - this.s = arg; - } - Debug.prototype._start = function (out) { - this.out = out; - this.ins._add(this); - }; - Debug.prototype._stop = function () { - this.ins._remove(this); - this.out = NO; - }; - Debug.prototype._n = function (t) { - var u = this.out; - if (u === NO) - return; - var s = this.s, l = this.l; - if (s !== noop) { - try { - s(t); - } - catch (e) { - u._e(e); - } - } - else if (l) - console.log(l + ':', t); - else - console.log(t); - u._n(t); - }; - Debug.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - Debug.prototype._c = function () { - var u = this.out; - if (u === NO) - return; - u._c(); - }; - return Debug; -}()); -var Drop = /** @class */ (function () { - function Drop(max, ins) { - this.type = 'drop'; - this.ins = ins; - this.out = NO; - this.max = max; - this.dropped = 0; - } - Drop.prototype._start = function (out) { - this.out = out; - this.dropped = 0; - this.ins._add(this); - }; - Drop.prototype._stop = function () { - this.ins._remove(this); - this.out = NO; - }; - Drop.prototype._n = function (t) { - var u = this.out; - if (u === NO) - return; - if (this.dropped++ >= this.max) - u._n(t); - }; - Drop.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - Drop.prototype._c = function () { - var u = this.out; - if (u === NO) - return; - u._c(); - }; - return Drop; -}()); -var EndWhenListener = /** @class */ (function () { - function EndWhenListener(out, op) { - this.out = out; - this.op = op; - } - EndWhenListener.prototype._n = function () { - this.op.end(); - }; - EndWhenListener.prototype._e = function (err) { - this.out._e(err); - }; - EndWhenListener.prototype._c = function () { - this.op.end(); - }; - return EndWhenListener; -}()); -var EndWhen = /** @class */ (function () { - function EndWhen(o, ins) { - this.type = 'endWhen'; - this.ins = ins; - this.out = NO; - this.o = o; - this.oil = NO_IL; - } - EndWhen.prototype._start = function (out) { - this.out = out; - this.o._add(this.oil = new EndWhenListener(out, this)); - this.ins._add(this); - }; - EndWhen.prototype._stop = function () { - this.ins._remove(this); - this.o._remove(this.oil); - this.out = NO; - this.oil = NO_IL; - }; - EndWhen.prototype.end = function () { - var u = this.out; - if (u === NO) - return; - u._c(); - }; - EndWhen.prototype._n = function (t) { - var u = this.out; - if (u === NO) - return; - u._n(t); - }; - EndWhen.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - EndWhen.prototype._c = function () { - this.end(); - }; - return EndWhen; -}()); -var Filter = /** @class */ (function () { - function Filter(passes, ins) { - this.type = 'filter'; - this.ins = ins; - this.out = NO; - this.f = passes; - } - Filter.prototype._start = function (out) { - this.out = out; - this.ins._add(this); - }; - Filter.prototype._stop = function () { - this.ins._remove(this); - this.out = NO; - }; - Filter.prototype._n = function (t) { - var u = this.out; - if (u === NO) - return; - var r = _try(this, t, u); - if (r === NO || !r) - return; - u._n(t); - }; - Filter.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - Filter.prototype._c = function () { - var u = this.out; - if (u === NO) - return; - u._c(); - }; - return Filter; -}()); -var FlattenListener = /** @class */ (function () { - function FlattenListener(out, op) { - this.out = out; - this.op = op; + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} +},{"safe-buffer":142}],153:[function(require,module,exports){ +(function (setImmediate,clearImmediate){ +var nextTick = require('process/browser.js').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]; +}; +}).call(this,require("timers").setImmediate,require("timers").clearImmediate) +},{"process/browser.js":119,"timers":153}],154:[function(require,module,exports){ +(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'; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],155:[function(require,module,exports){ +var indexOf = function (xs, item) { + if (xs.indexOf) return xs.indexOf(item); + else for (var i = 0; i < xs.length; i++) { + if (xs[i] === item) return i; + } + return -1; +}; +var Object_keys = function (obj) { + if (Object.keys) return Object.keys(obj) + else { + var res = []; + for (var key in obj) res.push(key) + return res; + } +}; + +var forEach = function (xs, fn) { + if (xs.forEach) return xs.forEach(fn) + else for (var i = 0; i < xs.length; i++) { + fn(xs[i], i, xs); + } +}; + +var defineProp = (function() { + try { + Object.defineProperty({}, '_', {}); + return function(obj, name, value) { + Object.defineProperty(obj, name, { + writable: true, + enumerable: false, + configurable: true, + value: value + }) + }; + } catch(e) { + return function(obj, name, value) { + obj[name] = value; + }; } - FlattenListener.prototype._n = function (t) { - this.out._n(t); - }; - FlattenListener.prototype._e = function (err) { - this.out._e(err); - }; - FlattenListener.prototype._c = function () { - this.op.inner = NO; - this.op.less(); - }; - return FlattenListener; -}()); -var Flatten = /** @class */ (function () { - function Flatten(ins) { - this.type = 'flatten'; - this.ins = ins; - this.out = NO; - this.open = true; - this.inner = NO; - this.il = NO_IL; - } - Flatten.prototype._start = function (out) { - this.out = out; - this.open = true; - this.inner = NO; - this.il = NO_IL; - this.ins._add(this); - }; - Flatten.prototype._stop = function () { - this.ins._remove(this); - if (this.inner !== NO) - this.inner._remove(this.il); - this.out = NO; - this.open = true; - this.inner = NO; - this.il = NO_IL; - }; - Flatten.prototype.less = function () { - var u = this.out; - if (u === NO) - return; - if (!this.open && this.inner === NO) - u._c(); - }; - Flatten.prototype._n = function (s) { - var u = this.out; - if (u === NO) - return; - var _a = this, inner = _a.inner, il = _a.il; - if (inner !== NO && il !== NO_IL) - inner._remove(il); - (this.inner = s)._add(this.il = new FlattenListener(u, this)); - }; - Flatten.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - Flatten.prototype._c = function () { - this.open = false; - this.less(); - }; - return Flatten; -}()); -var Fold = /** @class */ (function () { - function Fold(f, seed, ins) { - var _this = this; - this.type = 'fold'; - this.ins = ins; - this.out = NO; - this.f = function (t) { return f(_this.acc, t); }; - this.acc = this.seed = seed; - } - Fold.prototype._start = function (out) { - this.out = out; - this.acc = this.seed; - out._n(this.acc); - this.ins._add(this); - }; - Fold.prototype._stop = function () { - this.ins._remove(this); - this.out = NO; - this.acc = this.seed; - }; - Fold.prototype._n = function (t) { - var u = this.out; - if (u === NO) - return; - var r = _try(this, t, u); - if (r === NO) - return; - u._n(this.acc = r); - }; - Fold.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - Fold.prototype._c = function () { - var u = this.out; - if (u === NO) - return; - u._c(); - }; - return Fold; -}()); -var Last = /** @class */ (function () { - function Last(ins) { - this.type = 'last'; - this.ins = ins; - this.out = NO; - this.has = false; - this.val = NO; - } - Last.prototype._start = function (out) { - this.out = out; - this.has = false; - this.ins._add(this); - }; - Last.prototype._stop = function () { - this.ins._remove(this); - this.out = NO; - this.val = NO; - }; - Last.prototype._n = function (t) { - this.has = true; - this.val = t; - }; - Last.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - Last.prototype._c = function () { - var u = this.out; - if (u === NO) - return; - if (this.has) { - u._n(this.val); - u._c(); - } - else - u._e(new Error('last() failed because input stream completed')); - }; - return Last; -}()); -var MapOp = /** @class */ (function () { - function MapOp(project, ins) { - this.type = 'map'; - this.ins = ins; - this.out = NO; - this.f = project; - } - MapOp.prototype._start = function (out) { - this.out = out; - this.ins._add(this); - }; - MapOp.prototype._stop = function () { - this.ins._remove(this); - this.out = NO; - }; - MapOp.prototype._n = function (t) { - var u = this.out; - if (u === NO) - return; - var r = _try(this, t, u); - if (r === NO) - return; - u._n(r); - }; - MapOp.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - MapOp.prototype._c = function () { - var u = this.out; - if (u === NO) - return; - u._c(); - }; - return MapOp; -}()); -var Remember = /** @class */ (function () { - function Remember(ins) { - this.type = 'remember'; - this.ins = ins; - this.out = NO; - } - Remember.prototype._start = function (out) { - this.out = out; - this.ins._add(out); - }; - Remember.prototype._stop = function () { - this.ins._remove(this.out); - this.out = NO; - }; - return Remember; -}()); -var ReplaceError = /** @class */ (function () { - function ReplaceError(replacer, ins) { - this.type = 'replaceError'; - this.ins = ins; - this.out = NO; - this.f = replacer; - } - ReplaceError.prototype._start = function (out) { - this.out = out; - this.ins._add(this); - }; - ReplaceError.prototype._stop = function () { - this.ins._remove(this); - this.out = NO; - }; - ReplaceError.prototype._n = function (t) { - var u = this.out; - if (u === NO) - return; - u._n(t); - }; - ReplaceError.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - try { - this.ins._remove(this); - (this.ins = this.f(err))._add(this); - } - catch (e) { - u._e(e); - } - }; - ReplaceError.prototype._c = function () { - var u = this.out; - if (u === NO) - return; - u._c(); - }; - return ReplaceError; -}()); -var StartWith = /** @class */ (function () { - function StartWith(ins, val) { - this.type = 'startWith'; - this.ins = ins; - this.out = NO; - this.val = val; - } - StartWith.prototype._start = function (out) { - this.out = out; - this.out._n(this.val); - this.ins._add(out); - }; - StartWith.prototype._stop = function () { - this.ins._remove(this.out); - this.out = NO; - }; - return StartWith; -}()); -var Take = /** @class */ (function () { - function Take(max, ins) { - this.type = 'take'; - this.ins = ins; - this.out = NO; - this.max = max; - this.taken = 0; - } - Take.prototype._start = function (out) { - this.out = out; - this.taken = 0; - if (this.max <= 0) - out._c(); - else - this.ins._add(this); - }; - Take.prototype._stop = function () { - this.ins._remove(this); - this.out = NO; - }; - Take.prototype._n = function (t) { - var u = this.out; - if (u === NO) - return; - var m = ++this.taken; - if (m < this.max) - u._n(t); - else if (m === this.max) { - u._n(t); - u._c(); - } - }; - Take.prototype._e = function (err) { - var u = this.out; - if (u === NO) - return; - u._e(err); - }; - Take.prototype._c = function () { - var u = this.out; - if (u === NO) - return; - u._c(); - }; - return Take; }()); -var Stream = /** @class */ (function () { - function Stream(producer) { - this._prod = producer || NO; - this._ils = []; - this._stopID = NO; - this._dl = NO; - this._d = false; - this._target = NO; - this._err = NO; - } - Stream.prototype._n = function (t) { - var a = this._ils; - var L = a.length; - if (this._d) - this._dl._n(t); - if (L == 1) - a[0]._n(t); - else if (L == 0) - return; - else { - var b = cp(a); - for (var i = 0; i < L; i++) - b[i]._n(t); - } - }; - Stream.prototype._e = function (err) { - if (this._err !== NO) - return; - this._err = err; - var a = this._ils; - var L = a.length; - this._x(); - if (this._d) - this._dl._e(err); - if (L == 1) - a[0]._e(err); - else if (L == 0) - return; - else { - var b = cp(a); - for (var i = 0; i < L; i++) - b[i]._e(err); - } - if (!this._d && L == 0) - throw this._err; - }; - Stream.prototype._c = function () { - var a = this._ils; - var L = a.length; - this._x(); - if (this._d) - this._dl._c(); - if (L == 1) - a[0]._c(); - else if (L == 0) - return; - else { - var b = cp(a); - for (var i = 0; i < L; i++) - b[i]._c(); - } - }; - Stream.prototype._x = function () { - if (this._ils.length === 0) - return; - if (this._prod !== NO) - this._prod._stop(); - this._err = NO; - this._ils = []; - }; - Stream.prototype._stopNow = function () { - // WARNING: code that calls this method should - // first check if this._prod is valid (not `NO`) - this._prod._stop(); - this._err = NO; - this._stopID = NO; - }; - Stream.prototype._add = function (il) { - var ta = this._target; - if (ta !== NO) - return ta._add(il); - var a = this._ils; - a.push(il); - if (a.length > 1) - return; - if (this._stopID !== NO) { - clearTimeout(this._stopID); - this._stopID = NO; - } - else { - var p = this._prod; - if (p !== NO) - p._start(this); - } - }; - Stream.prototype._remove = function (il) { - var _this = this; - var ta = this._target; - if (ta !== NO) - return ta._remove(il); - var a = this._ils; - var i = a.indexOf(il); - if (i > -1) { - a.splice(i, 1); - if (this._prod !== NO && a.length <= 0) { - this._err = NO; - this._stopID = setTimeout(function () { return _this._stopNow(); }); - } - else if (a.length === 1) { - this._pruneCycles(); - } + +var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', +'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', +'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', +'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', +'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; + +function Context() {} +Context.prototype = {}; + +var Script = exports.Script = function NodeScript (code) { + if (!(this instanceof Script)) return new Script(code); + this.code = code; +}; + +Script.prototype.runInContext = function (context) { + if (!(context instanceof Context)) { + throw new TypeError("needs a 'context' argument."); + } + + var iframe = document.createElement('iframe'); + if (!iframe.style) iframe.style = {}; + iframe.style.display = 'none'; + + document.body.appendChild(iframe); + + var win = iframe.contentWindow; + var wEval = win.eval, wExecScript = win.execScript; + + if (!wEval && wExecScript) { + // win.eval() magically appears when this is called in IE: + wExecScript.call(win, 'null'); + wEval = win.eval; + } + + forEach(Object_keys(context), function (key) { + win[key] = context[key]; + }); + forEach(globals, function (key) { + if (context[key]) { + win[key] = context[key]; } - }; - // If all paths stemming from `this` stream eventually end at `this` - // stream, then we remove the single listener of `this` stream, to - // force it to end its execution and dispose resources. This method - // assumes as a precondition that this._ils has just one listener. - Stream.prototype._pruneCycles = function () { - if (this._hasNoSinks(this, [])) - this._remove(this._ils[0]); - }; - // Checks whether *there is no* path starting from `x` that leads to an end - // listener (sink) in the stream graph, following edges A->B where B is a - // listener of A. This means these paths constitute a cycle somehow. Is given - // a trace of all visited nodes so far. - Stream.prototype._hasNoSinks = function (x, trace) { - if (trace.indexOf(x) !== -1) - return true; - else if (x.out === this) - return true; - else if (x.out && x.out !== NO) - return this._hasNoSinks(x.out, trace.concat(x)); - else if (x._ils) { - for (var i = 0, N = x._ils.length; i < N; i++) - if (!this._hasNoSinks(x._ils[i], trace.concat(x))) - return false; - return true; + }); + + var winKeys = Object_keys(win); + + var res = wEval.call(win, this.code); + + forEach(Object_keys(win), function (key) { + // Avoid copying circular objects like `top` and `window` by only + // updating existing context properties or new properties in the `win` + // that was only introduced after the eval. + if (key in context || indexOf(winKeys, key) === -1) { + context[key] = win[key]; } - else - return false; - }; - Stream.prototype.ctor = function () { - return this instanceof MemoryStream ? MemoryStream : Stream; - }; - /** - * Adds a Listener to the Stream. - * - * @param {Listener} listener - */ - Stream.prototype.addListener = function (listener) { - listener._n = listener.next || noop; - listener._e = listener.error || noop; - listener._c = listener.complete || noop; - this._add(listener); - }; - /** - * Removes a Listener from the Stream, assuming the Listener was added to it. - * - * @param {Listener} listener - */ - Stream.prototype.removeListener = function (listener) { - this._remove(listener); - }; - /** - * Adds a Listener to the Stream returning a Subscription to remove that - * listener. - * - * @param {Listener} listener - * @returns {Subscription} - */ - Stream.prototype.subscribe = function (listener) { - this.addListener(listener); - return new StreamSub(this, listener); - }; - /** - * Add interop between most.js and RxJS 5 - * - * @returns {Stream} - */ - Stream.prototype[symbol_observable_1.default] = function () { - return this; - }; - /** - * Creates a new Stream given a Producer. - * - * @factory true - * @param {Producer} producer An optional Producer that dictates how to - * start, generate events, and stop the Stream. - * @return {Stream} - */ - Stream.create = function (producer) { - if (producer) { - if (typeof producer.start !== 'function' - || typeof producer.stop !== 'function') - throw new Error('producer requires both start and stop functions'); - internalizeProducer(producer); // mutates the input + }); + + forEach(globals, function (key) { + if (!(key in context)) { + defineProp(context, key, win[key]); } - return new Stream(producer); - }; - /** - * Creates a new MemoryStream given a Producer. - * - * @factory true - * @param {Producer} producer An optional Producer that dictates how to - * start, generate events, and stop the Stream. - * @return {MemoryStream} - */ - Stream.createWithMemory = function (producer) { - if (producer) - internalizeProducer(producer); // mutates the input - return new MemoryStream(producer); - }; - /** - * Creates a Stream that does nothing when started. It never emits any event. - * - * Marble diagram: - * - * ```text - * never - * ----------------------- - * ``` - * - * @factory true - * @return {Stream} - */ - Stream.never = function () { - return new Stream({ _start: noop, _stop: noop }); - }; - /** - * Creates a Stream that immediately emits the "complete" notification when - * started, and that's it. - * - * Marble diagram: - * - * ```text - * empty - * -| - * ``` - * - * @factory true - * @return {Stream} - */ - Stream.empty = function () { - return new Stream({ - _start: function (il) { il._c(); }, - _stop: noop, + }); + + document.body.removeChild(iframe); + + return res; +}; + +Script.prototype.runInThisContext = function () { + return eval(this.code); // maybe... +}; + +Script.prototype.runInNewContext = function (context) { + var ctx = Script.createContext(context); + var res = this.runInContext(ctx); + + if (context) { + forEach(Object_keys(ctx), function (key) { + context[key] = ctx[key]; }); + } + + return res; +}; + +forEach(Object_keys(Script.prototype), function (name) { + exports[name] = Script[name] = function (code) { + var s = Script(code); + return s[name].apply(s, [].slice.call(arguments, 1)); }; - /** - * Creates a Stream that immediately emits an "error" notification with the - * value you passed as the `error` argument when the stream starts, and that's - * it. - * - * Marble diagram: - * - * ```text - * throw(X) - * -X - * ``` - * - * @factory true - * @param error The error event to emit on the created stream. - * @return {Stream} - */ - Stream.throw = function (error) { - return new Stream({ - _start: function (il) { il._e(error); }, - _stop: noop, +}); + +exports.isContext = function (context) { + return context instanceof Context; +}; + +exports.createScript = function (code) { + return exports.Script(code); +}; + +exports.createContext = Script.createContext = function (context) { + var copy = new Context(); + if(typeof context === 'object') { + forEach(Object_keys(context), function (key) { + copy[key] = context[key]; }); - }; - /** - * Creates a stream from an Array, Promise, or an Observable. - * - * @factory true - * @param {Array|PromiseLike|Observable} input The input to make a stream from. - * @return {Stream} - */ - Stream.from = function (input) { - if (typeof input[symbol_observable_1.default] === 'function') - return Stream.fromObservable(input); - else if (typeof input.then === 'function') - return Stream.fromPromise(input); - else if (Array.isArray(input)) - return Stream.fromArray(input); - throw new TypeError("Type of input to from() must be an Array, Promise, or Observable"); - }; - /** - * Creates a Stream that immediately emits the arguments that you give to - * *of*, then completes. - * - * Marble diagram: - * - * ```text - * of(1,2,3) - * 123| - * ``` - * - * @factory true - * @param a The first value you want to emit as an event on the stream. - * @param b The second value you want to emit as an event on the stream. One - * or more of these values may be given as arguments. - * @return {Stream} - */ - Stream.of = function () { - var items = []; - for (var _i = 0; _i < arguments.length; _i++) { - items[_i] = arguments[_i]; - } - return Stream.fromArray(items); - }; - /** - * Converts an array to a stream. The returned stream will emit synchronously - * all the items in the array, and then complete. - * - * Marble diagram: - * - * ```text - * fromArray([1,2,3]) - * 123| - * ``` - * - * @factory true - * @param {Array} array The array to be converted as a stream. - * @return {Stream} - */ - Stream.fromArray = function (array) { - return new Stream(new FromArray(array)); - }; - /** - * Converts a promise to a stream. The returned stream will emit the resolved - * value of the promise, and then complete. However, if the promise is - * rejected, the stream will emit the corresponding error. - * - * Marble diagram: - * - * ```text - * fromPromise( ----42 ) - * -----------------42| - * ``` - * - * @factory true - * @param {PromiseLike} promise The promise to be converted as a stream. - * @return {Stream} - */ - Stream.fromPromise = function (promise) { - return new Stream(new FromPromise(promise)); - }; - /** - * Converts an Observable into a Stream. - * - * @factory true - * @param {any} observable The observable to be converted as a stream. - * @return {Stream} - */ - Stream.fromObservable = function (obs) { - if (obs.endWhen) - return obs; - var o = typeof obs[symbol_observable_1.default] === 'function' ? obs[symbol_observable_1.default]() : obs; - return new Stream(new FromObservable(o)); - }; - /** - * Creates a stream that periodically emits incremental numbers, every - * `period` milliseconds. - * - * Marble diagram: - * - * ```text - * periodic(1000) - * ---0---1---2---3---4---... - * ``` - * - * @factory true - * @param {number} period The interval in milliseconds to use as a rate of - * emission. - * @return {Stream} - */ - Stream.periodic = function (period) { - return new Stream(new Periodic(period)); - }; - Stream.prototype._map = function (project) { - return new (this.ctor())(new MapOp(project, this)); - }; - /** - * Transforms each event from the input Stream through a `project` function, - * to get a Stream that emits those transformed events. - * - * Marble diagram: - * - * ```text - * --1---3--5-----7------ - * map(i => i * 10) - * --10--30-50----70----- - * ``` - * - * @param {Function} project A function of type `(t: T) => U` that takes event - * `t` of type `T` from the input Stream and produces an event of type `U`, to - * be emitted on the output Stream. - * @return {Stream} - */ - Stream.prototype.map = function (project) { - return this._map(project); - }; - /** - * It's like `map`, but transforms each input event to always the same - * constant value on the output Stream. - * - * Marble diagram: - * - * ```text - * --1---3--5-----7----- - * mapTo(10) - * --10--10-10----10---- - * ``` - * - * @param projectedValue A value to emit on the output Stream whenever the - * input Stream emits any value. - * @return {Stream} - */ - Stream.prototype.mapTo = function (projectedValue) { - var s = this.map(function () { return projectedValue; }); - var op = s._prod; - op.type = 'mapTo'; - return s; - }; - /** - * Only allows events that pass the test given by the `passes` argument. - * - * Each event from the input stream is given to the `passes` function. If the - * function returns `true`, the event is forwarded to the output stream, - * otherwise it is ignored and not forwarded. - * - * Marble diagram: - * - * ```text - * --1---2--3-----4-----5---6--7-8-- - * filter(i => i % 2 === 0) - * ------2--------4---------6----8-- - * ``` - * - * @param {Function} passes A function of type `(t: T) => boolean` that takes - * an event from the input stream and checks if it passes, by returning a - * boolean. - * @return {Stream} - */ - Stream.prototype.filter = function (passes) { - var p = this._prod; - if (p instanceof Filter) - return new Stream(new Filter(and(p.f, passes), p.ins)); - return new Stream(new Filter(passes, this)); - }; - /** - * Lets the first `amount` many events from the input stream pass to the - * output stream, then makes the output stream complete. - * - * Marble diagram: - * - * ```text - * --a---b--c----d---e-- - * take(3) - * --a---b--c| - * ``` - * - * @param {number} amount How many events to allow from the input stream - * before completing the output stream. - * @return {Stream} - */ - Stream.prototype.take = function (amount) { - return new (this.ctor())(new Take(amount, this)); - }; - /** - * Ignores the first `amount` many events from the input stream, and then - * after that starts forwarding events from the input stream to the output - * stream. - * - * Marble diagram: - * - * ```text - * --a---b--c----d---e-- - * drop(3) - * --------------d---e-- - * ``` - * - * @param {number} amount How many events to ignore from the input stream - * before forwarding all events from the input stream to the output stream. - * @return {Stream} - */ - Stream.prototype.drop = function (amount) { - return new Stream(new Drop(amount, this)); - }; - /** - * When the input stream completes, the output stream will emit the last event - * emitted by the input stream, and then will also complete. - * - * Marble diagram: - * - * ```text - * --a---b--c--d----| - * last() - * -----------------d| - * ``` - * - * @return {Stream} - */ - Stream.prototype.last = function () { - return new Stream(new Last(this)); - }; - /** - * Prepends the given `initial` value to the sequence of events emitted by the - * input stream. The returned stream is a MemoryStream, which means it is - * already `remember()`'d. - * - * Marble diagram: - * - * ```text - * ---1---2-----3--- - * startWith(0) - * 0--1---2-----3--- - * ``` - * - * @param initial The value or event to prepend. - * @return {MemoryStream} - */ - Stream.prototype.startWith = function (initial) { - return new MemoryStream(new StartWith(this, initial)); - }; - /** - * Uses another stream to determine when to complete the current stream. - * - * When the given `other` stream emits an event or completes, the output - * stream will complete. Before that happens, the output stream will behaves - * like the input stream. - * - * Marble diagram: - * - * ```text - * ---1---2-----3--4----5----6--- - * endWhen( --------a--b--| ) - * ---1---2-----3--4--| - * ``` - * - * @param other Some other stream that is used to know when should the output - * stream of this operator complete. - * @return {Stream} - */ - Stream.prototype.endWhen = function (other) { - return new (this.ctor())(new EndWhen(other, this)); - }; - /** - * "Folds" the stream onto itself. - * - * Combines events from the past throughout - * the entire execution of the input stream, allowing you to accumulate them - * together. It's essentially like `Array.prototype.reduce`. The returned - * stream is a MemoryStream, which means it is already `remember()`'d. - * - * The output stream starts by emitting the `seed` which you give as argument. - * Then, when an event happens on the input stream, it is combined with that - * seed value through the `accumulate` function, and the output value is - * emitted on the output stream. `fold` remembers that output value as `acc` - * ("accumulator"), and then when a new input event `t` happens, `acc` will be - * combined with that to produce the new `acc` and so forth. - * - * Marble diagram: - * - * ```text - * ------1-----1--2----1----1------ - * fold((acc, x) => acc + x, 3) - * 3-----4-----5--7----8----9------ - * ``` - * - * @param {Function} accumulate A function of type `(acc: R, t: T) => R` that - * takes the previous accumulated value `acc` and the incoming event from the - * input stream and produces the new accumulated value. - * @param seed The initial accumulated value, of type `R`. - * @return {MemoryStream} - */ - Stream.prototype.fold = function (accumulate, seed) { - return new MemoryStream(new Fold(accumulate, seed, this)); - }; - /** - * Replaces an error with another stream. - * - * When (and if) an error happens on the input stream, instead of forwarding - * that error to the output stream, *replaceError* will call the `replace` - * function which returns the stream that the output stream will replicate. - * And, in case that new stream also emits an error, `replace` will be called - * again to get another stream to start replicating. - * - * Marble diagram: - * - * ```text - * --1---2-----3--4-----X - * replaceError( () => --10--| ) - * --1---2-----3--4--------10--| - * ``` - * - * @param {Function} replace A function of type `(err) => Stream` that takes - * the error that occurred on the input stream or on the previous replacement - * stream and returns a new stream. The output stream will behave like the - * stream that this function returns. - * @return {Stream} - */ - Stream.prototype.replaceError = function (replace) { - return new (this.ctor())(new ReplaceError(replace, this)); - }; - /** - * Flattens a "stream of streams", handling only one nested stream at a time - * (no concurrency). - * - * If the input stream is a stream that emits streams, then this operator will - * return an output stream which is a flat stream: emits regular events. The - * flattening happens without concurrency. It works like this: when the input - * stream emits a nested stream, *flatten* will start imitating that nested - * one. However, as soon as the next nested stream is emitted on the input - * stream, *flatten* will forget the previous nested one it was imitating, and - * will start imitating the new nested one. - * - * Marble diagram: - * - * ```text - * --+--------+--------------- - * \ \ - * \ ----1----2---3-- - * --a--b----c----d-------- - * flatten - * -----a--b------1----2---3-- - * ``` - * - * @return {Stream} - */ - Stream.prototype.flatten = function () { - return new Stream(new Flatten(this)); - }; - /** - * Passes the input stream to a custom operator, to produce an output stream. - * - * *compose* is a handy way of using an existing function in a chained style. - * Instead of writing `outStream = f(inStream)` you can write - * `outStream = inStream.compose(f)`. - * - * @param {function} operator A function that takes a stream as input and - * returns a stream as well. - * @return {Stream} - */ - Stream.prototype.compose = function (operator) { - return operator(this); - }; - /** - * Returns an output stream that behaves like the input stream, but also - * remembers the most recent event that happens on the input stream, so that a - * newly added listener will immediately receive that memorised event. - * - * @return {MemoryStream} - */ - Stream.prototype.remember = function () { - return new MemoryStream(new Remember(this)); - }; - /** - * Returns an output stream that identically behaves like the input stream, - * but also runs a `spy` function for each event, to help you debug your app. - * - * *debug* takes a `spy` function as argument, and runs that for each event - * happening on the input stream. If you don't provide the `spy` argument, - * then *debug* will just `console.log` each event. This helps you to - * understand the flow of events through some operator chain. - * - * Please note that if the output stream has no listeners, then it will not - * start, which means `spy` will never run because no actual event happens in - * that case. - * - * Marble diagram: - * - * ```text - * --1----2-----3-----4-- - * debug - * --1----2-----3-----4-- - * ``` - * - * @param {function} labelOrSpy A string to use as the label when printing - * debug information on the console, or a 'spy' function that takes an event - * as argument, and does not need to return anything. - * @return {Stream} - */ - Stream.prototype.debug = function (labelOrSpy) { - return new (this.ctor())(new Debug(this, labelOrSpy)); - }; - /** - * *imitate* changes this current Stream to emit the same events that the - * `other` given Stream does. This method returns nothing. - * - * This method exists to allow one thing: **circular dependency of streams**. - * For instance, let's imagine that for some reason you need to create a - * circular dependency where stream `first$` depends on stream `second$` - * which in turn depends on `first$`: - * - * - * ```js - * import delay from 'xstream/extra/delay' - * - * var first$ = second$.map(x => x * 10).take(3); - * var second$ = first$.map(x => x + 1).startWith(1).compose(delay(100)); - * ``` - * - * However, that is invalid JavaScript, because `second$` is undefined - * on the first line. This is how *imitate* can help solve it: - * - * ```js - * import delay from 'xstream/extra/delay' - * - * var secondProxy$ = xs.create(); - * var first$ = secondProxy$.map(x => x * 10).take(3); - * var second$ = first$.map(x => x + 1).startWith(1).compose(delay(100)); - * secondProxy$.imitate(second$); - * ``` - * - * We create `secondProxy$` before the others, so it can be used in the - * declaration of `first$`. Then, after both `first$` and `second$` are - * defined, we hook `secondProxy$` with `second$` with `imitate()` to tell - * that they are "the same". `imitate` will not trigger the start of any - * stream, it just binds `secondProxy$` and `second$` together. - * - * The following is an example where `imitate()` is important in Cycle.js - * applications. A parent component contains some child components. A child - * has an action stream which is given to the parent to define its state: - * - * - * ```js - * const childActionProxy$ = xs.create(); - * const parent = Parent({...sources, childAction$: childActionProxy$}); - * const childAction$ = parent.state$.map(s => s.child.action$).flatten(); - * childActionProxy$.imitate(childAction$); - * ``` - * - * Note, though, that **`imitate()` does not support MemoryStreams**. If we - * would attempt to imitate a MemoryStream in a circular dependency, we would - * either get a race condition (where the symptom would be "nothing happens") - * or an infinite cyclic emission of values. It's useful to think about - * MemoryStreams as cells in a spreadsheet. It doesn't make any sense to - * define a spreadsheet cell `A1` with a formula that depends on `B1` and - * cell `B1` defined with a formula that depends on `A1`. - * - * If you find yourself wanting to use `imitate()` with a - * MemoryStream, you should rework your code around `imitate()` to use a - * Stream instead. Look for the stream in the circular dependency that - * represents an event stream, and that would be a candidate for creating a - * proxy Stream which then imitates the target Stream. - * - * @param {Stream} target The other stream to imitate on the current one. Must - * not be a MemoryStream. - */ - Stream.prototype.imitate = function (target) { - if (target instanceof MemoryStream) - throw new Error('A MemoryStream was given to imitate(), but it only ' + - 'supports a Stream. Read more about this restriction here: ' + - 'https://github.com/staltz/xstream#faq'); - this._target = target; - for (var ils = this._ils, N = ils.length, i = 0; i < N; i++) - target._add(ils[i]); - this._ils = []; - }; - /** - * Forces the Stream to emit the given value to its listeners. - * - * As the name indicates, if you use this, you are most likely doing something - * The Wrong Way. Please try to understand the reactive way before using this - * method. Use it only when you know what you are doing. - * - * @param value The "next" value you want to broadcast to all listeners of - * this Stream. - */ - Stream.prototype.shamefullySendNext = function (value) { - this._n(value); - }; - /** - * Forces the Stream to emit the given error to its listeners. - * - * As the name indicates, if you use this, you are most likely doing something - * The Wrong Way. Please try to understand the reactive way before using this - * method. Use it only when you know what you are doing. - * - * @param {any} error The error you want to broadcast to all the listeners of - * this Stream. - */ - Stream.prototype.shamefullySendError = function (error) { - this._e(error); - }; - /** - * Forces the Stream to emit the "completed" event to its listeners. - * - * As the name indicates, if you use this, you are most likely doing something - * The Wrong Way. Please try to understand the reactive way before using this - * method. Use it only when you know what you are doing. - */ - Stream.prototype.shamefullySendComplete = function () { - this._c(); - }; - /** - * Adds a "debug" listener to the stream. There can only be one debug - * listener, that's why this is 'setDebugListener'. To remove the debug - * listener, just call setDebugListener(null). - * - * A debug listener is like any other listener. The only difference is that a - * debug listener is "stealthy": its presence/absence does not trigger the - * start/stop of the stream (or the producer inside the stream). This is - * useful so you can inspect what is going on without changing the behavior - * of the program. If you have an idle stream and you add a normal listener to - * it, the stream will start executing. But if you set a debug listener on an - * idle stream, it won't start executing (not until the first normal listener - * is added). - * - * As the name indicates, we don't recommend using this method to build app - * logic. In fact, in most cases the debug operator works just fine. Only use - * this one if you know what you're doing. - * - * @param {Listener} listener - */ - Stream.prototype.setDebugListener = function (listener) { - if (!listener) { - this._d = false; - this._dl = NO; - } - else { - this._d = true; - listener._n = listener.next || noop; - listener._e = listener.error || noop; - listener._c = listener.complete || noop; - this._dl = listener; - } - }; - /** - * Blends multiple streams together, emitting events from all of them - * concurrently. - * - * *merge* takes multiple streams as arguments, and creates a stream that - * behaves like each of the argument streams, in parallel. - * - * Marble diagram: - * - * ```text - * --1----2-----3--------4--- - * ----a-----b----c---d------ - * merge - * --1-a--2--b--3-c---d--4--- - * ``` - * - * @factory true - * @param {Stream} stream1 A stream to merge together with other streams. - * @param {Stream} stream2 A stream to merge together with other streams. Two - * or more streams may be given as arguments. - * @return {Stream} - */ - Stream.merge = function merge() { - var streams = []; - for (var _i = 0; _i < arguments.length; _i++) { - streams[_i] = arguments[_i]; - } - return new Stream(new Merge(streams)); - }; - /** - * Combines multiple input streams together to return a stream whose events - * are arrays that collect the latest events from each input stream. - * - * *combine* internally remembers the most recent event from each of the input - * streams. When any of the input streams emits an event, that event together - * with all the other saved events are combined into an array. That array will - * be emitted on the output stream. It's essentially a way of joining together - * the events from multiple streams. - * - * Marble diagram: - * - * ```text - * --1----2-----3--------4--- - * ----a-----b-----c--d------ - * combine - * ----1a-2a-2b-3b-3c-3d-4d-- - * ``` - * - * @factory true - * @param {Stream} stream1 A stream to combine together with other streams. - * @param {Stream} stream2 A stream to combine together with other streams. - * Multiple streams, not just two, may be given as arguments. - * @return {Stream} - */ - Stream.combine = function combine() { - var streams = []; - for (var _i = 0; _i < arguments.length; _i++) { - streams[_i] = arguments[_i]; - } - return new Stream(new Combine(streams)); - }; - return Stream; -}()); -exports.Stream = Stream; -var MemoryStream = /** @class */ (function (_super) { - __extends(MemoryStream, _super); - function MemoryStream(producer) { - var _this = _super.call(this, producer) || this; - _this._has = false; - return _this; - } - MemoryStream.prototype._n = function (x) { - this._v = x; - this._has = true; - _super.prototype._n.call(this, x); - }; - MemoryStream.prototype._add = function (il) { - var ta = this._target; - if (ta !== NO) - return ta._add(il); - var a = this._ils; - a.push(il); - if (a.length > 1) { - if (this._has) - il._n(this._v); - return; - } - if (this._stopID !== NO) { - if (this._has) - il._n(this._v); - clearTimeout(this._stopID); - this._stopID = NO; - } - else if (this._has) - il._n(this._v); - else { - var p = this._prod; - if (p !== NO) - p._start(this); - } - }; - MemoryStream.prototype._stopNow = function () { - this._has = false; - _super.prototype._stopNow.call(this); - }; - MemoryStream.prototype._x = function () { - this._has = false; - _super.prototype._x.call(this); - }; - MemoryStream.prototype.map = function (project) { - return this._map(project); - }; - MemoryStream.prototype.mapTo = function (projectedValue) { - return _super.prototype.mapTo.call(this, projectedValue); - }; - MemoryStream.prototype.take = function (amount) { - return _super.prototype.take.call(this, amount); - }; - MemoryStream.prototype.endWhen = function (other) { - return _super.prototype.endWhen.call(this, other); - }; - MemoryStream.prototype.replaceError = function (replace) { - return _super.prototype.replaceError.call(this, replace); - }; - MemoryStream.prototype.remember = function () { - return this; - }; - MemoryStream.prototype.debug = function (labelOrSpy) { - return _super.prototype.debug.call(this, labelOrSpy); - }; - return MemoryStream; -}(Stream)); -exports.MemoryStream = MemoryStream; -var xs = Stream; -exports.default = xs; + } + return copy; +}; -},{"symbol-observable":46}],56:[function(require,module,exports){ +},{}],156:[function(require,module,exports){ 'use strict'; -var _run = require('@cycle/run'); - -var _dom = require('@cycle/dom'); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = TimeTravel; +console.log('hello world!'); +console.log(require('hammerjs')); +console.log(require('../node_modules/handtrackjs/dist/handtrack.min.js')); +// import * as handTrack from 'handtrackjs'; +// console.log(handTrack); -function main(sources) { - var vdom$ = sources.DOM.select('.myinput').events('input').map(function (ev) { - return ev.target.value; - }).startWith('').map(function (name) { - return (0, _dom.div)([(0, _dom.label)('Name:'), (0, _dom.input)('.myinput', { attrs: { type: 'text' } }), (0, _dom.hr)(), (0, _dom.h1)('Hello ' + name)]); - }); - return { - DOM: vdom$ - }; +function TimeTravel() { + return 'TimeTravel'; } -(0, _run.run)(main, { - DOM: (0, _dom.makeDOMDriver)('#app') +},{"../node_modules/handtrackjs/dist/handtrack.min.js":85,"hammerjs":84}]},{},[156])(156) }); - -},{"@cycle/dom":14,"@cycle/run":23}]},{},[56]) -//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJub2RlX21vZHVsZXMvQGN5Y2xlL2RvbS9saWIvY2pzL0JvZHlET01Tb3VyY2UuanMiLCJub2RlX21vZHVsZXMvQGN5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MudmlydHVhbE5vbkJ1YmJsaW5nTGlzdGVuZXIgPSBbXTtcbiAgICAgICAgdGhpcy5pc29sYXRlTW9kdWxlLnNldEV2ZW50RGVsZWdhdG9yKHRoaXMpO1xuICAgICAgICB0aGlzLmRvbUxpc3RlbmVycyA9IG5ldyBNYXAoKTtcbiAgICAgICAgdGhpcy5kb21MaXN0ZW5lcnNUb0FkZCA9IG5ldyBNYXAoKTtcbiAgICAgICAgdGhpcy5ub25CdWJibGluZ0xpc3RlbmVycyA9IG5ldyBNYXAoKTtcbiAgICAgICAgcm9vdEVsZW1lbnQkLmFkZExpc3RlbmVyKHtcbiAgICAgICAgICAgIG5leHQ6IGZ1bmN0aW9uIChlbCkge1xuICAgICAgICAgICAgICAgIGlmIChfdGhpcy5vcmlnaW4gIT09IGVsKSB7XG4gICAgICAgICAgICAgICAgICAgIF90aGlzLm9yaWdpbiA9IGVsO1xuICAgICAgICAgICAgICAgICAgICBfdGhpcy5yZXNldEV2ZW50TGlzdGVuZXJzKCk7XG4gICAgICAgICAgICAgICAgICAgIF90aGlzLmRvbUxpc3RlbmVyc1RvQWRkLmZvckVhY2goZnVuY3Rpb24gKHBhc3NpdmUsIHR5cGUpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBfdGhpcy5zZXR1cERPTUxpc3RlbmVyKHR5cGUsIHBhc3NpdmUpO1xuICAgICAgICAgICAgICAgICAgICB9KTtcbiAgICAgICAgICAgICAgICAgICAgX3RoaXMuZG9tTGlzdGVuZXJzVG9BZGQuY2xlYXIoKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgX3RoaXMucmVzZXROb25CdWJibGluZ0xpc3RlbmVycygpO1xuICAgICAgICAgICAgICAgIF90aGlzLm5vbkJ1YmJsaW5nTGlzdGVuZXJzVG9BZGQuZm9yRWFjaChmdW5jdGlvbiAoYXJyKSB7XG4gICAgICAgICAgICAgICAgICAgIF90aGlzLnNldHVwTm9uQnViYmxpbmdMaXN0Z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Lm1ha2VJbnNlcnQobmV3TWFwKTtcbiAgICAgICAgdGhpcy5ub25CdWJibGluZ0xpc3RlbmVycy5mb3JFYWNoKGZ1bmN0aW9uIChtYXAsIHR5cGUpIHtcbiAgICAgICAgICAgIG1hcC5mb3JFYWNoKGZ1bmN0aW9uICh2YWx1ZSwgZWxtKSB7XG4gICAgICAgICAgICAgICAgaWYgKCFkb2N1bWVudC5ib2R5LmNvbnRhaW5zKGVsbSkpIHtcbiAgICAgICAgICAgICAgICAgICAgdmFyIHN1YiA9IHZhbHVlLnN1YiwgZGVzdGluYXRpb25fMSA9IHZhbHVlLmRlc3RpbmF0aW9uO1xuICAgICAgICAgICAgICAgICAgICBpZiAoc3ViKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICBzdWIudW5zdWJzY3JpYmUoKTtcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICB2YXIgZWxlbWVudEZpbmRlciA9IG5ldyBFbGVtZW50RmluZGVyXzEuRWxlbWVudEZpbmRlcihkZXN0aW5hdGlvbl8xLnNjb3BlQ2hlY2tlci5uYW1lc3BhY2UsIF90aGlzLmlzb2xhdGVNb2R1bGUpO1xuICAgICAgICAgICAgICAgICAgICB2YXIgbmV3RWxtID0gZWxlbWVudEZpbmRlci5jYWxsKClbMF07XG4gICAgICAgICAgICAgICAgICAgIHZhciBuZXdTdWIgPSBmcm9tRXZlbnRfMS5mcm9tRXZlbnQobmV3RWxtLCB0eXBlLCBmYWxzZSwgZmFsc2UsIGRlc3RpbmF0aW9uXzEucGFzc2l2ZSkuc3Vic2NyaWJlKHtcbiAgICAgICAgICAgICAgICAgICAgICAgIG5leHQ6IGZ1bmN0aW9uIChldmVudCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBfdGhpcy5vbkV2ZW50KHR5cGUsIGV2ZW50LCAhIWRlc3RpbmF0aW9uXzEucGFzc2l2ZSwgZmFsc2UpO1xuICAgICAgICAgICAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgICAgICAgICAgICAgIGVycm9yOiBmdW5jdGlvbiAoKSB7IH0sXG4gICAgICAgICAgICAgICAgICAgICAgICBjb21wbGV0ZTogZnVuY3Rpb24gKCkgeyB9LFxuICAgICAgICAgICAgICAgICAgICB9KTtcbiAgICAgICAgICAgICAgICAgICAgaW5zZXJ0KHR5cGUsIG5ld0VsbSwgeyBzdWI6IG5ld1N1YiwgZGVzdGluYXRpb246IGRlc3RpbmF0aW9uXzEgfSk7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgICAgICBpbnNlcnQodHlwZSwgZWxtLCB2YWx1ZSk7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICBfdGhpcy5ub25CdWJibGluZ0xpc3RlbmVycyA9IG5ld01hcDtcbiAgICAgICAgfSk7XG4gICAgfTtcbiAgICBFdmVudERlbGVnYXRvci5wcm90b3R5cGUucHV0Tm9uQnViYmxpbmdMaXN0ZW5lciA9IGZ1bmN0aW9uIChldmVudFR5cGUsIGVsbSwgdXNlQ2FwdHVyZSwgcGFzc2l2ZSkge1xuICAgICAgICB2YXIgbWFwID0gdGhpcy5ub25CdWJibGluZ0xpc3RlbmVycy5nZXQoZXZlbnRUeXBlKTtcbiAgICAgICAgaWYgKCFtYXApIHtcbiAgICAgICAgICAgIHJldHVybjtcbiAgICAgICAgfVxuICAgICAgICB2YXIgbGlzdGVuZXIgPSBtYXAuZ2V0KGVsbSk7XG4gICAgICAgIGlmIChsaXN0ZW5lciAmJlxuICAgICAgICAgICAgbGlzdGVuZXIuZGVzdGluYXRpb24ucGFzc2l2ZSA9PT0gcGFzc2l2ZSAmJlxuICAgICAgICAgICAgbGlzdGVuZXIuZGVzdGluYXRpb24udXNlQ2FwdHVyZSA9PT0gdXNlQ2FwdHVyZSkge1xuICAgICAgICAgICAgdGhpcy52aXJ0dWFsTm9uQnViYmxpbmdM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QnViYmxlU3RlcChldmVudFR5cGUsIGVsbSwgcm9vdEVsZW1lbnQsIGV2ZW50LCBsaXN0ZW5lcnMsIHVzZUNhcHR1cmUsIHBhc3NpdmUpO1xuICAgICAgICB9XG4gICAgICAgIHZhciBuZXdSb290ID0gcm9vdEVsZW1lbnQ7XG4gICAgICAgIHZhciBuZXdJbmRleCA9IGluZGV4O1xuICAgICAgICBpZiAoZWxtID09PSByb290RWxlbWVudCkge1xuICAgICAgICAgICAgaWYgKGluZGV4ID49IDAgJiYgbmFtZXNwYWNlW2luZGV4XS50eXBlID09PSAnc2libGluZycpIHtcbiAgICAgICAgICAgICAgICBuZXdSb290ID0gdGhpcy5pc29sYXRlTW9kdWxlLmdldEVsZW1lbnQobmFtZXNwYWNlLCBpbmRleCk7XG4gICAgICAgICAgICAgICAgbmV3SW5kZXgtLTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgIHJldHVybjtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBpZiAoZWxtLnBhcmVudE5vZGUgJiYgbmV3Um9vdCkge1xuICAgICAgICAgICAgdGhpcy5idWJibGUoZXZlbnRUeXBlLCBlbG0ucGFyZW50Tm9kZSwgbmV3Um9vdCwgZXZlbnQsIGxpc3RlbmVycywgbmFtZXNwYWNlLCBuZXdJbmRleCwgdXNlQ2FwdHVyZSwgcGFzc2l2ZSk7XG4gICAgICAgIH1cbiAgICAgICAgaWYgKHVzZUNhcHR1cmUgJiYgIWV2ZW50LnByb3BhZ2F0aW9uSGFzQmVlblN0b3BwZWQpIHtcbiAgICAgICAgICAgIHRoaXMuZG9CdWJibGVTdGVwKGV2ZW50VHlwZSwgZWxtLCByb290RWxlbWVudCwgZXZlbnQsIGxpc3RlbmVycywgdXNlQ2FwdHVyZSwgcGFzc2l2ZSk7XG4gICAgICAgIH1cbiAgICB9O1xuICAgIEV2ZW50RGVsZWdhdG9yLnByb3RvdHlwZS5kb0J1YmJsZVN0ZXAgPSBmdW5jdGlvbiAoZXZlbnRUeXBlLCBlbG0sIHJvb3RFbGVtZW50LCBldmVudCwgbGlzdGVuZXJzLCB1c2VDYXB0dXJlLCBwYXNzaXZlKSB7XG4gICAgICAgIGlmICghcm9vdEVsZW1lbnQpIHtcbiAgICAgICAgICAgIHJldHVybjtcbiAgICAgICAgfVxuICAgICAgICB0aGlzLm11dGF0ZUV2ZW50Q3VycmVudFRhcmdldChldmVudCwgZWxtKTtcbiAgICAgICAgbGlzdGVuZXJzLmZvckVhY2goZnVuY3Rpb24gKGRlc3QpIHtcbiAgICAgICAgICAgIGlmIChkZXN0LnBhc3NpdmUgPT09IHBhc3NpdmUgJiYgZGVzdC51c2VDYXB0dXJlID09PSB1c2VDYXB0dXJlKSB7XG4gICAgICAgICAgICAgICAgdmFyIHNlbCA9IHV0aWxzXzEuZ2V0U2VsZWN0b3JzKGRlc3Quc2NvcGVDaGVja2VyLm5hbWVzcGFjZSk7XG4gICAgICAgICAgICAgICAgaWYgKCFldmVudC5wcm9wYWdhdGlvbkhhc0JlZW5TdG9wcGVkICYmXG4gICAgICAgICAgICAgICAgICAgIGRlc3Quc2NvcGVDaGVja2VyLmlzRGlyZWN0bHlJblNjb3BlKGVsbSkgJiZcbiAgICAgICAgICAgICAgICAgICAgKChzZWwgIT09ICcnICYmIGVsbS5tYXRjaGVzKHNlbCkpIHx8XG4gICAgICAgICAgICAgICAgICAgICAgICAoc2VsID09PSAnJyAmJiBlbG0gPT09IHJvb3RFbGVtZW50KSkpIHtcbiAgICAgICAgICAgICAgICAgICAgZnJvbUV2ZW50XzEucHJldmVudERlZmF1bHRDb25kaXRpb25hbChldmVudCwgZGVzdC5wcmV2ZW50RGVmYXVsdCk7XG4gICAgICAgICAgICAgICAgICAgIGRlc3Quc3ViamVjdC5zaGFtZWZ1bGx5U2VuZE5leHQoZXZlbnQpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgfSk7XG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R1cm4gdW5kZWZpbmVkO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgZWxzZSBpZiAoY3Vyci50YWdOYW1lID09PSAnSFRNTCcpIHtcbiAgICAgICAgICAgICAgICB0aHJvdyBuZXcgRXJyb3IoJ05vIHJvb3QgZWxlbWVudCBmb3VuZCwgdGhpcyBzaG91bGQgbm90IGhhcHBlbiBhdCBhbGwnKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICByZXR1cm4gY3VycjtcbiAgICB9O1xuICAgIElzb2xhdGVNb2R1bGUucHJvdG90eXBlLmdldE5hbWVzcGFjZSA9IGZ1bmN0aW9uIChlbG0pIHtcbiAgICAgICAgdmFyIHJvb3RFbGVtZW50ID0gdGhpcy5nZXRSb290RWxlbWVudChlbG0pO1xuICAgICAgICBpZiAoIXJvb3RFbGVtZW50KSB7XG4gICAgICAgICAgICByZXR1cm4gdW5kZWZpbmVkO1xuICAgICAgICB9XG4gICAgICAgIHJldHVybiB0aGlzLm5hbWVzcGFjZUJ5RWxlbWVudC5nZXQocm9vdEVsZW1lbnQpO1xuICAgIH07XG4gICAgSXNvbGF0ZU1vZHVsZS5wcm90b3R5cGUuY3JlYXRlTW9kdWxlID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgc2VsZiA9IHRoaXM7XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBjcmVhdGU6IGZ1bmN0aW9uIChlbXB0eVZOb2RlLCB2Tm9kZSkge1xuICAgICAgICAgICAgICAgIHZhciBlbG0gPSB2Tm9kZS5lbG0sIF9hID0gdk5vZGUuZGF0YSwgZGF0YSA9IF9hID09PSB2b2lkIDAgPyB7fSA6IF9hO1xuICAgICAgICAgICAgICAgIHZhciBuYW1lc3BhY2UgPSBkYXRhLmlzb2xhdGU7XG4gICAgICAgICAgICAgICAgaWYgKEFycmF5LmlzQXJyYXkobmFtZXNwYWNlKSkge1xuICAgICAgICAgICAgICAgICAgICBzZWxmLmluc2VydEVsZW1lbnQobmFtZXNwYWNlLCBlbG0pO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0sXG4gICAgICAgICAgICB1cGRhdGU6IGZ1bmN0aW9uIChvbGRWTm9kZSwgdk5vZGUpIHtcbiAgICAgICAgICAgICAgICB2YXIgb2xkRWxtID0gb2xkVk5vZGUuZWxtLCBfYSA9IG9sZFZOb2RlLmRhdGEsIG9sZERhdGEgPSBfYSA9PT0gdm9pZCAwID8ge30gOiBfYTtcbiAgICAgICAgICAgICAgICB2YXIgZWxtID0gdk5vZGUuZWxtLCBfYiA9IHZOb2RlLmRhdGEsIGRhdGEgPSBfYiA9PT0gdm9pZCAwID8ge30gOiBfYjtcbiAgICAgICAgICAgICAgICB2YXIgb2xkTmFtZXNwYWNlID0gb2xkRGF0YS5pc29sYXRlO1xuICAgICAgICAgICAgICAgIHZhciBuYW1lc3BhY2UgPSBkYXRhLmlzb2xhdGU7XG4gICAgICAgICAgICAgICAgaWYgKCF1dGlsc18xLmlzRXF1YWxOYW1lc3BhY2Uob2xkTmFtZXNwYWNlLCBuYW1lc3BhY2UpKSB7XG4gICAgICAgICAgICAgICAgICAgIGlmIChBcnJheS5pc0FycmF5KG9sZE5hbWVzcGFjZSkpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIHNlbGYucmVtb3ZlRWxlbWVudChvbGRFbG0pO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGlmIChBcnJheS5pc0FycmF5KG5hbWVzcGFjZSkpIHtcbiAgICAgICAgICAgICAgICAgICAgc2VsZi5pbnNlcnRFbGVtZW50KG5hbWVzcGFjZSwgZWxtKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgZGVzdHJveTogZnVuY3Rpb24gKHZOb2RlKSB7XG4gICAgICAgICAgICAgICAgc2VsZi52bm9kZXNCZWluZ1JlbW92ZWQucHVzaCh2Tm9kZSk7XG4gICAgICAgICAgICB9LFxuICAgICAgICAgICAgcmVtb3ZlOiBmdW5jdGlvbiAodk5vZGUsIGNiKSB7XG4gICAgICAgICAgICAgICAgc2VsZi52bm9kZXNCZWluZ1JlbW92ZWQucHVzaCh2Tm9kZSk7XG4gICAgICAgICAgICAgICAgY2IoKTtcbiAgICAgICAgICAgIH0sXG4gICAgICAgICAgICBwb3N0OiBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAgICAgdmFyIHZub2Rlc0JlaW5nUmVtb3ZlZCA9IHNlbGYudm5vZGVzQmVpbmdSZW1vdmVkO1xuICAgICAgICAgICAgICAgIGZvciAodmFyIGkgPSB2bm9kZXNCZWluZ1JlbW92ZWQubGVuZ3RoIC0gMTsgaSA+PSAwOyBpLS0pIHtcbiAgICAgICAgICAgICAgICAgICAgdmFyIHZub2RlID0gdm5vZGVzQmVpbmdSZW1vdmVkW2ldO1xuICAgICAgICAgICAgICAgICAgICB2YXIgbmFtZXNwYWNlID0gdm5vZGUuZGF0YSAhPT0gdW5kZWZpbmVkXG4gICAgICAgICAgICAgICAgICAgICAgICA/IHZub2RlLmRhdGEuaXNvbGF0aW9uXG4gICAgICAgICAgICAgICAgICAgICAgICA6IHVuZGVmaW5lZDtcbiAgICAgICAgICAgICAgICAgICAgaWYgKG5hbWVzcGFjZSAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICBzZWxmLnJlbW92ZUVsZW1lbnQobmFtZXNwYWNlKTtcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICBzZWxmLmV2ZW50RGVsZWdhdG9yLnJlbW92ZUVsZW1lbnQodm5vZGUuZWxtLCBuYW1lc3BhY2UpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICBzZWxmLnZub2Rlc0JlaW5nUmVtb3ZlZCA9IFtdO1xuICAgICAgICAgICAgfSxcbiAgICAgICAgfTtcbiAgICB9O1xuICAgIHJldHVybi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0gLyoqIEBjbGFzcyAqLyAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIFByaW9yaXR5UXVldWUoKSB7XG4gICAgICAgIHRoaXMuYXJyID0gW107XG4gICAgICAgIHRoaXMucHJpb3MgPSBbXTtcbiAgICB9XG4gICAgUHJpb3JpdHlRdWV1ZS5wcm90b3R5cGUuYWRkID0gZnVuY3Rpb24gKHQsIHByaW8pIHtcbiAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCB0aGlzLmFyci5sZW5ndGg7IGkrKykge1xuICAgICAgICAgICAgaWYgKHRoaXMucHJpb3NbaV0gPCBwcmlvKSB7XG4gICAgICAgICAgICAgICAgdGhpcy5hcnIuc3BsaWNlKGksIDAsIHQpO1xuICAgICAgICAgICAgICAgIHRoaXMucHJpb3Muc3BsaWNlKGksIDAsIHByaW8pO1xuICAgICAgICAgICAgICAgIHJldHVybjtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICB0aGlzLmFyci5wdXNoKHQpO1xuICAgICAgICB0aGlzLnByaW9zLnB1c2gocHJpbyk7XG4gICAgfTtcbiAgICBQcmlvcml0eVF1ZXVlLnByb3RvdHlwZS5mb3JFYWNoID0gZnVuY3Rpb24gKGYpIHtcbiAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCB0aGlzLmFyci5sZW5ndGg7IGkrKykge1xuICAgICAgICAgICAgZih0aGlzLmFycltpXSwgaSwgdGhpcy5hcnIpO1xuICAgICAgICB9XG4gICAgfTtcbiAgICBQcmlvcml0eVF1ZXVlLnByb3RvdHlwZS5kZWxldGUgPSBmdW5jdGlvbiAodCkge1xuICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IHRoaXMuYXJyLmxlbmd0aDsgaSsrKSB7XG4gICAgICAgICAgICBpZiAodGhpcy5hcnJbaV0gPT09IHQpIHtcbiAgICAgICAgICAgICAgICB0aGlzLmFyci5zcGxpY2UoaSwgMSk7XG4gICAgICAgICAgICAgICAgdGh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25dO1xuICAgICAgICAgICAgaWYgKCFjaGlsZCkge1xuICAgICAgICAgICAgICAgIGNoaWxkID0gW3VuZGVmaW5lZCwge31dO1xuICAgICAgICAgICAgICAgIGN1cnJbMV1bbl0gPSBjaGlsZDtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGN1cnIgPSBjaGlsZDtcbiAgICAgICAgfVxuICAgICAgICBjdXJyWzBdID0gZWxlbWVudDtcbiAgICB9O1xuICAgIFN5bWJvbFRyZWUucHJvdG90eXBlLmdldERlZmF1bHQgPSBmdW5jdGlvbiAocGF0aCwgbWtEZWZhdWx0RWxlbWVudCwgbWF4KSB7XG4gICAgICAgIHJldHVybiB0aGlzLmdldChwYXRoLCBta0RlZmF1bHRFbGVtZW50LCBtYXgpO1xuICAgIH07XG4gICAgLyoqXG4gICAgICogUmV0dXJucyB0aGUgcGF5bG9hZCBvZiB0aGUgcGF0aFxuICAgICAqIElmIGEgZGVmYXVsdCBlbGVtZW50IGNyZWF0b3IgaXMgZ2l2ZW4sIGl0IHdpbGwgaW5zZXJ0IGl0IGF0IHRoZSBwYXRoXG4gICAgICovXG4gICAgU3ltYm9sVHJlZS5wcm90b3R5cGUuZ2V0ID0gZnVuY3Rpb24gKHBhdGgsIG1rRGVmYXVsdEVsZW1lbnQsIG1heCkge1xuICAgICAgICB2YXIgY3VyciA9IHRoaXMudHJlZTtcbiAgICAgICAgdmFyIF9tYXggPSBtYXggIT09IHVuZGVmaW5lZCA/IG1heCA6IHBhdGgubGVuZ3RoO1xuICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IF9tYXg7IGkrKykge1xuICAgICAgICAgICAgdmFyIG4gPSB0aGlzLm1hcHBlcihwYXRoW2ldKTtcbiAgICAgICAgICAgIHZhciBjaGlsZCA9IGN1cnJbMV1bbl07XG4gICAgICAgICAgICBpZiAoIWNoaWxkKSB7XG4gICAgICAgICAgICAgICAgaWYgKG1rRGVmYXVsdEVsZW1lbnQpIHtcbiAgICAgICAgICAgICAgICAgICAgY2hpbGQgPSBbdW5kZWZpbmVkLCB7fV07XG4gICAgICAgICAgICAgICAgICAgIGN1cnJbMV1bbl0gPSBjaGlsZDtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgZWxzZSB7XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiB1bmRlZmluZWQ7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuICAgICAgICAgICAgY3VyciA9IGNoaWxkO1xuICAgICAgICB9XG4gICAgICAgIGlmIChta0RlZmF1bHRFbGVtZW50ICYmICFjdXJyWzBdKSB7XG4gICAgICAgICAgICBjdXJyWzBdID0gbWtEZWZhdWx0RWxlbWVudCgpO1xuICAgICAgICB9XG4gICAgICAgIHJldHVybiBjdXJyWzBdO1xuICAgIH07XG4gICAgU3ltYm9sVHJlZS5wcm90b3R5cGUuZGVsZXRlID0gZnVuY3Rpb24gKHBhdGgpIHtcbiAgICAgICAgdmFyIGN1cnIgPSB0aGlzLnRyZWU7XG4gICAgICAgIGZvciAodmFyIGkgPSAwOyBpIDwgcGF0aC5sZW5ndGggLSAxOyBpKyspIHtcbiAgICAgICAgICAgIHZhciBjaGlsZCA9IGN1cnJbMV1bdGhpcy5tYXBwZXIocGF0aFtpXSldO1xuICAgICAgICAgICAgaWYgKCFjaGlsZCkge1xuICAgICAgICAgICAgICAgIHJldHVybjtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGN1cnIgPSBjaGlsZDtcbiAgICAgICAgfVxuICAgICAgICBkZWxldGUgY3VyclsxXVt0aGlzLm1hcHBlcihwYXRoW3BhdGgubGVuZ3RoIC0gMV0pXTtcbiAgICB9O1xuICAgIHJldHVybiBTeW1ib2xUcmVlO1xufSgpKTtcbmV4cG9ydHMuZGVmYXVsdCA9IFN5bWJvbFRyZWU7XG4vLyMgc291cmNlTWFwcGluZ1VSTD1TeW1ib2xUcmVlLmpzLm1hcCIsIlwidXNlIHN0cmljdFwiO1xuT2JqZWN0LmRlZ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gICBpZiAocHJldmVudERlZmF1bHQgPT09IHZvaWQgMCkgeyBwcmV2ZW50RGVmYXVsdCA9IGZhbHNlOyB9XG4gICAgaWYgKHBhc3NpdmUgPT09IHZvaWQgMCkgeyBwYXNzaXZlID0gZmFsc2U7IH1cbiAgICB2YXIgbmV4dCA9IG51bGw7XG4gICAgcmV0dXJuIHhzdHJlYW1fMS5TdHJlYW0uY3JlYXRlKHtcbiAgICAgICAgc3RhcnQ6IGZ1bmN0aW9uIHN0YXJ0KGxpc3RlbmVyKSB7XG4gICAgICAgICAgICBpZiAocHJldmVudERlZmF1bHQpIHtcbiAgICAgICAgICAgICAgICBuZXh0ID0gZnVuY3Rpb24gX25leHQoZXZlbnQpIHtcbiAgICAgICAgICAgICAgICAgICAgcHJldmVudERlZmF1bHRDb25kaXRpb25hbChldmVudCwgcHJldmVudERlZmF1bHQpO1xuICAgICAgICAgICAgICAgICAgICBsaXN0ZW5lci5uZXh0KGV2ZW50KTtcbiAgICAgICAgICAgICAgICB9O1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgZWxzZSB7XG4gICAgICAgICAgICAgICAgbmV4dCA9IGZ1bmN0aW9uIF9uZXh0KGV2ZW50KSB7XG4gICAgICAgICAgICAgICAgICAgIGxpc3RlbmVyLm5leHQoZXZlbnQpO1xuICAgICAgICAgICAgICAgIH07XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbGVtZW50LmFkZEV2ZW50TGlzdGVuZXIoZXZlbnROYW1lLCBuZXh0LCB7XG4gICAgICAgICAgICAgICAgY2FwdHVyZTogdXNlQ2FwdHVyZSxcbiAgICAgICAgICAgICAgICBwYXNzaXZlOiBwYXNzaXZlLFxuICAgICAgICAgICAgfSk7XG4gICAgICAgIH0sXG4gICAgICAgIHN0b3A6IGZ1bmN0aW9uIHN0b3AoKSB7XG4gICAgICAgICAgICBlbGVtZW50LnJlbW92ZUV2ZW50TGlzdGVuZXIoZXZlbnROYW1lLCBuZXh0LCB1c2VDYXB0dXJlKTtcbiAgICAgICAgICAgIG5leHQgPSBudWxsO1xuICAgICAgICB9LFxuICAgIH0pO1xufVxuZXhwb3J0cy5mcm9tRXZlbnQgPSBmcm9tRXZlbnQ7XG5mdW5jdGlvbiBtYXRjaE9iamVjdChtYXRjaGVyLCBvYmopIHtcbiAgICB2YXIga2V5cyA9IE9iamVjdC5rZXlzKG1hdGNoZXIpO1xuICAgIHZhciBuID0ga2V5cy5sZW5ndGg7XG4gICAgZm9yICh2YXIgaSA9IDA7IGkgPCBuOyBpKyspIHtcbiAgICAgICAgdmFyIGsgPSBrZXlzW2ldO1xuICAgICAgICBpZiAodHlwZW9mIG1hdGNoZXJba10gPT09ICdvYmplY3QnICYmIHR5cGVvZiBvYmpba10gPT09ICdvYmplY3QnKSB7XG4gICAgICAgICAgICBpZiAoIW1hdGNoT2JqZWN0KG1hdGNoZXJba10sIG9ialtrXSkpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSBpZiAobWF0Y2hlcltrXSAhPT0gb2JqW2tdKSB7XG4gICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgIH1cbiAgICB9XG4gICAgcmV0dXJuIHRydWU7XG59XG5mdW5jdGlvbiBwcmV2ZW50RGVmYXVsdENvbmRpdGlvbmFsKGV2ZW50LCBwcmV2ZW50RGVmYXVsdCkge1xuICAgIGlmIChwcmV2ZW50RGVmYXVsdCkge1xuICAgICAgICBpZiAodHlwZW9mIHByZXZlbnREZWZhdWx0ID09PSAnYm9vbGVhbicpIHtcbiAgICAgICAgICAgIGV2ZW50LnByZXZlbnREZWZhdWx0KCk7XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSBpZiAoaXNQcmVkaWNhdGUocHJldmVudERlZmF1bHQpKSB7XG4gICAgICAgICAgICBpZiAocHJldmVudERlZmF1bHQoZXZlbnQpKSB7XG4gICAgICAgICAgICAgICAgZXZlbnQucHJldm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GlzVmFsaWRTdHJpbmcocGFyYW0pICYmIChwYXJhbVswXSA9PT0gJy4nIHx8IHBhcmFtWzBdID09PSAnIycpO1xufVxuZnVuY3Rpb24gY3JlYXRlVGFnRnVuY3Rpb24odGFnTmFtZSkge1xuICAgIHJldHVybiBmdW5jdGlvbiBoeXBlcnNjcmlwdChhLCBiLCBjKSB7XG4gICAgICAgIHZhciBoYXNBID0gdHlwZW9mIGEgIT09ICd1bmRlZmluZWQnO1xuICAgICAgICB2YXIgaGFzQiA9IHR5cGVvZiBiICE9PSAndW5kZWZpbmVkJztcbiAgICAgICAgdmFyIGhhc0MgPSB0eXBlb2YgYyAhPT0gJ3VuZGVmaW5lZCc7XG4gICAgICAgIGlmIChpc1NlbGVjdG9yKGEpKSB7XG4gICAgICAgICAgICBpZiAoaGFzQiAmJiBoYXNDKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIGhfMS5oKHRhZ05hbWUgKyBhLCBiLCBjKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2UgaWYgKGhhc0IpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gaF8xLmgodGFnTmFtZSArIGEsIGIpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgZWxzZSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIGhfMS5oKHRhZ05hbWUgKyBhLCB7fSk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSBpZiAoaGFzQykge1xuICAgICAgICAgICAgcmV0dXJuIGhfMS5oKHRhZ05hbWUgKyBhLCBiLCBjKTtcbiAgICAgICAgfVxuICAgICAgICBlbHNlIGlmIChoYXNCKSB7XG4gICAgICAgICAgICByZXR1cm4gaF8xLmgodGFnTmFtZSwgYSwgYik7XG4gICAgICAgIH1cbiAgICAgICAgZWxzZSBpZiAoaGFzQSkge1xuICAgICAgICAgICAgcmV0dXJuIGhfMS5oKHRhZ05hbWUsIGEpO1xuICAgICAgICB9XG4gICAgICAg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Blci5jYWxsKHZub2RlKTsgfSlcbiAgICAgICAgICAgICAgICAuc3RhcnRXaXRoKGFkZFJvb3RTY29wZSh0b3Zub2RlXzEudG9WTm9kZShmaXJzdFJvb3QpKSlcbiAgICAgICAgICAgICAgICAuZm9sZChwYXRjaCwgdG92bm9kZV8xLnRvVk5vZGUoZmlyc3RSb290KSlcbiAgICAgICAgICAgICAgICAuZHJvcCgxKVxuICAgICAgICAgICAgICAgIC5tYXAodW53cmFwRWxlbWVudEZyb21WTm9kZSlcbiAgICAgICAgICAgICAgICAuc3RhcnRXaXRoKGZpcnN0Um9vdClcbiAgICAgICAgICAgICAgICAubWFwKGZ1bmN0aW9uIChlbCkge1xuICAgICAgICAgICAgICAgIG11dGF0aW9uT2JzZXJ2ZXIub2JzZXJ2ZShlbCwge1xuICAgICAgICAgICAgICAgICAgICBjaGlsZExpc3Q6IHRydWUsXG4gICAgICAgICAgICAgICAgICAgIGF0dHJpYnV0ZXM6IHRydWUsXG4gICAgICAgICAgICAgICAgICAgIGNoYXJhY3RlckRhdGE6IHRydWUsXG4gICAgICAgICAgICAgICAgICAgIHN1YnRyZWU6IHRydWUsXG4gICAgICAgICAgICAgICAgICAgIGF0dHJpYnV0ZU9sZFZhbHVlOiB0cnVlLFxuICAgICAgICAgICAgICAgICAgICBjaGFyYWN0ZXJEYXRhT2xkVmFsdWU6IHRydWUsXG4gICAgICAgICAgICAgICAgfSk7XG4gICAgICAgICAgICAgICAgcmV0dXJuIGVsO1xuICAgICAgICAgICAgfSlcbiAgICAgICAgICAgICAgICAuY29tcG9zZShkcm9wQ29tcGxldGlvbik7XG4gICAgICAgIH0gLy8gZG9uJ3QgY29tcGxldGUgdGhpcyBzdHJlYW1cbiAgICAgICAgKVxuICAgICAgICAgICAgLmZsYXR0ZW4oKTtcbiAgICAgICAgdmFyIHJvb3RFbGVtZW50JCA9IGNvbmNhdF8xLmRlZmF1bHQoZG9tUmVhZHkkLCBtdXRhdGlvbkNvbmZpcm1lZCQpXG4g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W5JZHgsIGVuZElkeCkge1xuICAgIHZhciBpLCBtYXAgPSB7fSwga2V5LCBjaDtcbiAgICBmb3IgKGkgPSBiZWdpbklkeDsgaSA8PSBlbmRJZHg7ICsraSkge1xuICAgICAgICBjaCA9IGNoaWxkcmVuW2ldO1xuICAgICAgICBpZiAoY2ggIT0gbnVsbCkge1xuICAgICAgICAgICAga2V5ID0gY2gua2V5O1xuICAgICAgICAgICAgaWYgKGtleSAhPT0gdW5kZWZpbmVkKVxuICAgICAgICAgICAgICAgIG1hcFtrZXldID0gaTtcbiAgICAgICAgfVxuICAgIH1cbiAgICByZXR1cm4gbWFwO1xufVxudmFyIGhvb2tzID0gWydjcmVhdGUnLCAndXBkYXRlJywgJ3JlbW92ZScsICdkZXN0cm95JywgJ3ByZScsICdwb3N0J107XG52YXIgaF8xID0gcmVxdWlyZShcIi4vaFwiKTtcbmV4cG9ydHMuaCA9IGhfMS5oO1xudmFyIHRodW5rXzEgPSByZXF1aXJlKFwiLi90aHVua1wiKTtcbmV4cG9ydHMudGh1bmsgPSB0aHVua18xLnRodW5rO1xuZnVuY3Rpb24gaW5pdChtb2R1bGVzLCBkb21BcGkpIHtcbiAgICB2YXIgaSwgaiwgY2JzID0ge307XG4gICAgdmFyIGFwaSA9IGRvbUFwaSAhPT0gdW5kZWZpbmVkID8gZG9tQXBpIDogaHRtbGRvbWFwaV8xLmRlZmF1bHQ7XG4gICAgZm9yIChpID0gMDsgaSA8IGhvb2tzLmxlbmd0aDsgKytpKSB7XG4gICAgICAgIGNic1tob29rc1tpXV0gPSBbXTtcbiAgICAgICAgZm9yIChqID0gMDsgaiA8IG1vZHVsZXMubGVuZ3RoOyArK2opIHtcbiAgICAgICAgICAgIHZhciBob29rID0gbW9kdWxlc1tqXVtob29rc1tpXV07XG4gICAgICAgICAgICBpZiAoaG9vayAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICAgICAgY2JzW2hvb2tzW2ldXS5wdXNoKGhvb2spO1xuICAgICAgICA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AxLCBkb3QpKTtcbiAgICAgICAgICAgIGlmIChkb3RJZHggPiAwKVxuICAgICAgICAgICAgICAgIGVsbS5zZXRBdHRyaWJ1dGUoJ2NsYXNzJywgc2VsLnNsaWNlKGRvdCArIDEpLnJlcGxhY2UoL1xcLi9nLCAnICcpKTtcbiAgICAgICAgICAgIGZvciAoaSA9IDA7IGkgPCBjYnMuY3JlYXRlLmxlbmd0aDsgKytpKVxuICAgICAgICAgICAgICAgIGNicy5jcmVhdGVbaV0oZW1wdHlOb2RlLCB2bm9kZSk7XG4gICAgICAgICAgICBpZiAoaXMuYXJyYXkoY2hpbGRyZW4pKSB7XG4gICAgICAgICAgICAgICAgZm9yIChpID0gMDsgaSA8IGNoaWxkcmVuLmxlbmd0aDsgKytpKSB7XG4gICAgICAgICAgICAgICAgICAgIHZhciBjaCA9IGNoaWxkcmVuW2ldO1xuICAgICAgICAgICAgICAgICAgICBpZiAoY2ggIT0gbnVsbCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgYXBpLmFwcGVuZENoaWxkKGVsbSwgY3JlYXRlRWxtKGNoLCBpbnNlcnRlZFZub2RlUXVldWUpKTtcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2UgaWYgKGlzLnByaW1pdGl2ZSh2bm9kZS50ZXh0KSkge1xuICAgICAgICAgICAgICAgIGFwaS5hcHBlbmRDaGlsZChlbG0sIGFwaS5jcmVhdGVUZXh0Tm9kZSh2bm9kZS50ZXh0KSk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBpID0gdm5vZGUuZGF0YS5ob29rOyAvLyBSZXVzZSB2YXJpYWJsZVxuICAgICAgICAgICAgaWYgKGlzRGVmKGkpKSB7XG4gICAgICAgICAgICAgICAgaWYgKGkuY3JlYXRlKVxuICAgICAgICAgICAgICAgICAgICBpLmNyZWF0ZShlbXB0eU5vZGUsIHZub2RlKTtcbiAgICAgICAgICA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aV0odm5vZGUpO1xuICAgICAgICAgICAgaWYgKHZub2RlLmNoaWxkcmVuICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgICAgICAgICBmb3IgKGogPSAwOyBqIDwgdm5vZGUuY2hpbGRyZW4ubGVuZ3RoOyArK2opIHtcbiAgICAgICAgICAgICAgICAgICAgaSA9IHZub2RlLmNoaWxkcmVuW2pdO1xuICAgICAgICAgICAgICAgICAgICBpZiAoaSAhPSBudWxsICYmIHR5cGVvZiBpICE9PSBcInN0cmluZ1wiKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICBpbnZva2VEZXN0cm95SG9vayhpKTtcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cbiAgICBmdW5jdGlvbiByZW1vdmVWbm9kZXMocGFyZW50RWxtLCB2bm9kZXMsIHN0YXJ0SWR4LCBlbmRJZHgpIHtcbiAgICAgICAgZm9yICg7IHN0YXJ0SWR4IDw9IGVuZElkeDsgKytzdGFydElkeCkge1xuICAgICAgICAgICAgdmFyIGlfMSA9IHZvaWQgMCwgbGlzdGVuZXJzID0gdm9pZCAwLCBybSA9IHZvaWQgMCwgY2ggPSB2bm9kZXNbc3RhcnRJZHhdO1xuICAgICAgICAgICAgaWYgKGNoICE9IG51bGwpIHtcbiAgICAgICAgICAgICAgICBpZiAoaXNEZWYoY2guc2VsKSkge1xuICAgICAgICAgICAgICAgICAgICBpbnZva2VEZXN0cm95SG9vayhjaCk7XG4gICAgICAgICAgICAgICAgICAgIGxpc3RlbmVycyA9IGNicy5yZW1vdmUubGVuZ3RoICsgMTtcbiAgICAgICAgICAgICAgICAgICAgcm0gPSBjcmVhdGVSbUNiKGNoLmVsbSwgbGlzdGVuZXJzKTtcbiAgICAgICAgICAgICAgICAgICAgZm9yIChpXzEgPSAwOyBpXzEgPCBjYnMucmVtb3ZlLmxlbmd0aDsgKytpXzEpXG4gICAgICAgICAgICAgICAgICAgICAgICBjYnMucmVtb3ZlW2lfMV0oY2gsIHJtKTtcbiAgICAgICAgICAgICAgICAgICAgaWYgKGlzRGVmKGlfMSA9IGNoLmRhdGEpICYmIGlzRGVmKGlfMSA9IGlfMS5ob29rKSAmJiBpc0RlZihpXzEgPSBpXzEucmVtb3ZlKSkge1xuICAgICAgICAgICAgICAgICAgICAgICAgaV8xKGNoLCBybSk7XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgZWxzZSB7XG4gICAgICAgICAgICAgICAgICAgICAgICBybSgpO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgICAgICBhcGkucmVtb3ZlQ2hpbGQocGFyZW50RWxtLCBjaC5lbG0pO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgIH1cbiAgICBmdW5jdGlvbiB1cGRhdGVDaGlsZHJlbihwYXJlbnRFbG0sIG9sZENoLCBuZXdDaCwgaW5zZXJ0ZWRWbm9kZVF1ZXVlKSB7XG4gICAgICAgIHZhciBvbGRTdGFydElkeCA9IDAsIG5ld1N0YXJ0SWR4ID0gMDtcbiAgICAgICAgdmFyIG9sZEVuZElkeCA9IG9sZENoLmxlbmd0aCAtIDE7XG4gICAgICAgIHZhciBvbGRTdGFydFZub2RlID0gb2xkQ2hbMF07XG4gICAgICAgIHZhciBvbGRFbmRWbm9kZSA9IG9sZENoW29sZEVuZElkeF07XG4gICAgICAgIHZhciBuZXdFbmRJZHggPSBuZXdDaC5sZW5ndGggLSAxO1xuICAgICAgICB2YXIgbmV3U3RhcnRWbm9kZSA9IG5ld0NoWzBdO1xuICAgICAgICB2YXIgbmV3RW5kVm5vZGUgPSBuZXdDaFtuZXdFbmRJZHhdO1xuICAgICAgICB2YXIgb2xkS2V5VG9JZHg7XG4gICAgICAgIHZhciBpZHhJbk9sZDtcbiAgICAgICAgdmFyIGVsbVRvTW92ZTtcbiAgICAgICAgdmFyIGJlZm9yZTtcbiAgICAgICAgd2hpbGUgKG9sZFN0YXJ0SWR4IDw9IG9sZEVuZElkeCAmJiBuZXdTdGFydElkeCA8PSBuZXdFbmRJZHgpIHtcbiAgICAgICAgICAgIGlmIChvbGRTdGFydFZub2RlID09IG51bGwpIHtcbiAgICAgICAgICAgICAgICBvbGRTdGFydFZub2RlID0gb2xkQ2hbKytvbGRTdGFydElkeF07IC8vIFZub2RlIG1pZ2h0IGhhdmUgYmVlbiBtb3ZlZCBsZWZ0XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIGlmIChvbGRFbmRWbm9kZSA9PSBudWxsKSB7XG4gICAgICAgICAgICAgICAgb2xkRW5kVm5vZGUgPSBvbGRDaFstLW9sZEVuZElkeF07XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIGlmIChuZXdTdGFydFZub2RlID09IG51bGwpIHtcbiAgICAgICAgICAgICAgICBuZXdTdGFydFZub2RlID0gbmV3Q2hbKytuZXdTdGFydElkeF07XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIGlmIChuZXdFbmRWbm9kZSA9PSBudWxsKSB7XG4gICAgICAgICAgICAgICAgbmV3RW5kVm5vZGUgPSBuZXdDaFstLW5ld0VuZElkeF07XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIGlmIChzYW1lVm5vZGUob2xkU3RhcnRWbm9kZSwgbmV3U3RhcnRWbm9kZSkpIHtcbiAgICAgICAgICAgICAgICBwYXRjaFZub2RlKG9sZFN0YXJ0Vm5vZGUsIG5ld1N0YXJ0Vm5vZGUsIGluc2VydGVkVm5vZGVRdWV1ZSk7XG4gICAgICAgICAgICAgICAgb2xkU3RhcnRWbm9kZSA9IG9sZENoWysrb2xkU3RhcnRJZHhdO1xuICAgICAgICAgICAgICAgIG5ld1N0YXJ0Vm5vZGUgPSBuZXdDaFsrK25ld1N0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ZGUuZWxtLCBvbGRTdGFydFZub2RlLmVsbSk7XG4gICAgICAgICAgICAgICAgb2xkRW5kVm5vZGUgPSBvbGRDaFstLW9sZEVuZElkeF07XG4gICAgICAgICAgICAgICAgbmV3U3RhcnRWbm9kZSA9IG5ld0NoWysrbmV3U3RhcnRJZHhdO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgZWxzZSB7XG4gICAgICAgICAgICAgICAgaWYgKG9sZEtleVRvSWR4ID09PSB1bmRlZmluZWQpIHtcbiAgICAgICAgICAgICAgICAgICAgb2xkS2V5VG9JZHggPSBjcmVhdGVLZXlUb09sZElkeChvbGRDaCwgb2xkU3RhcnRJZHgsIG9sZEVuZElkeCk7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGlkeEluT2xkID0gb2xkS2V5VG9JZHhbbmV3U3RhcnRWbm9kZS5rZXldO1xuICAgICAgICAgICAgICAgIGlmIChpc1VuZGVmKGlkeEluT2xkKSkge1xuICAgICAgICAgICAgICAgICAgICBhcGkuaW5zZXJ0QmVmb3JlKHBhcmVudEVsbSwgY3JlYXRlRWxtKG5ld1N0YXJ0Vm5vZGUsIGluc2VydGVkVm5vZGVRdWV1ZSksIG9sZFN0YXJ0Vm5vZGUuZWxtKTtcbiAgICAgICAgICAgICAgICAgICAgbmV3U3RhcnRWbm9kZSA9IG5ld0NoWysrbmV3U3RhcnRJZHhdO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgICAgICAgICAgZWxtVG9Nb3ZlID0gb2xkQ2hbaWR4SW5PbGRdO1xuICAgICAgICAgICAgICAgICAgICBpZiAoZWxtVG9Nb3ZlLnNlbCAhPT0gbmV3U3RhcnRWbm9kZS5zZWwpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIGFwaS5pbnNlcnRCZWZvcmUocGFyZW50RWxtLCBjcmVhdGVFbG0obmV3U3RhcnRWbm9kZSwgaW5zZXJ0ZWRWbm9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ICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICB9XG4gICAgZnVuY3Rpb24gcGF0Y2hWbm9kZShvbGRWbm9kZSwgdm5vZGUsIGluc2VydGVkVm5vZGVRdWV1ZSkge1xuICAgICAgICB2YXIgaSwgaG9vaztcbiAgICAgICAgaWYgKGlzRGVmKGkgPSB2bm9kZS5kYXRhKSAmJiBpc0RlZihob29rID0gaS5ob29rKSAmJiBpc0RlZihpID0gaG9vay5wcmVwYXRjaCkpIHtcbiAgICAgICAgICAgIGkob2xkVm5vZGUsIHZub2RlKTtcbiAgICAgICAgfVxuICAgICAgICB2YXIgZWxtID0gdm5vZGUuZWxtID0gb2xkVm5vZGUuZWxtO1xuICAgICAgICB2YXIgb2xkQ2ggPSBvbGRWbm9kZS5jaGlsZHJlbjtcbiAgICAgICAgdmFyIGNoID0gdm5vZGUuY2hpbGRyZW47XG4gICAgICAgIGlmIChvbGRWbm9kZSA9PT0gdm5vZGUpXG4gICAgICAgICAgICByZXR1cm47XG4gICAgICAgIGlmICh2bm9kZS5kYXRhICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgICAgIGZvciAoaSA9IDA7IGkgPCBjYnMudXBkYXRlLmxlbmd0aDsgKytpKVxuICAgICAgICAgICAgICAgIGNicy51cGRhdGVbaV0ob2xkVm5vZGUsIHZub2RlKTtcbiAgICAgICAgICAgIGkgPSB2bm9kZS5kYXRhLmhvb2s7XG4gICAgICAgICAgICBpZiAoaXNEZWYoaSkgJiYgaXNEZWYoaSA9IGkudXBkYXRlKSlcbiAgICAgICAgICAgICAgICBpKG9sZFZub2RlLCB2bm9kZSk7XG4gICAgICAgIH1cbiAgICAgICAgaWYgKGlzVW5kZWYodm5vZGUudGV4dCkpIHtcbiAgICAgICAgICAgIGlmIChpc0RlZihvbGRDaCkgJiYgaXNEZWYoY2gpKSB7XG4gICAgICAgICAgICAgICAgaWYgKG9sZENoICE9PSBjaClcbiAgICAgICAgICAgICAgICAgICAgdXBkYXRlQ2hpbGRyZW4oZWxtLCBvbGRDaCwgY2gsIGluc2VydGVkVm5vZGVRdWV1ZSk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIGlmIChpc0RlZihjaCkpIHtcbiAgICAgICAgICAgICAgICBpZiAoaXNEZWYob2xkVm5vZGUudGV4dCkpXG4gICAgICAgICAgICAgICAgICAgIGFwaS5zZXRUZXh0Q29udGVudChlbG0sICcnKTtcbiAgICAgICAgICAgICAgICBhZGRWbm9kZXMoZWxtLCBudWxsLCBjaCwgMCwgY2gubGVuZ3RoIC0gMSwgaW5zZXJ0ZWRWbm9kZVF1ZXVlKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2UgaWYgKGlzRGVmKG9sZENoKSkge1xuICAgICAgICAgICAgICAgIHJlbW92ZVZub2RlcyhlbG0sIG9sZENoLCAwLCBvbGRDaC5sZW5ndGggLSAxKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2UgaWYgKGlzRGVmKG9sZFZub2RlLnRleHQpKSB7XG4gICAgICAgICAgICAgICAgYXBpLnNldFRleHRDb250ZW50KGVsbSwgJycpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgICAgIGVsc2UgaWYgKG9sZFZub2RlLnRleHQgIT09IHZub2RlLnRleHQpIHtcbiAgICAgICAgICAgIGlmIChpc0RlZihvbGRDaCkpIHtcbiAgICAgICAgICAgICAgICByZW1vdmVWbm9kZXMoZWxtLCBvbGRDaCwgMCwgb2xkQ2gubGVuZ3RoIC0gMSk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBhcGkuc2V0VGV4dENvbnRlbnQoZWxtLCB2bm9kZS50ZXh0KTtcbiAgICAgICAgfVxuICAgICAgICBpZiAoaXNEZWYoaG9vaykgJiYgaXNEZWYoaSA9IGhvb2sucG9zdHBhdGNoKSkge1xuICAgICAgICAgICAgaShvbGRWbm9kZSwgdm5vZGUpO1xuICAgICAgICB9XG4gICAgfVxuICAgIHJldHVybi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cbiAgICAgICAgaWYgKHRhZyAmJiB0YWcudG9Mb3dlckNhc2UoKSAhPT0gb3B0cy50YWcobm9kZSkudG9Mb3dlckNhc2UoKSkge1xuICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgICAgICB9XG4gICAgICAgIGlmIChpZCAmJiBpZCAhPT0gb3B0cy5pZChub2RlKSkge1xuICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgICAgICB9XG4gICAgICAgIHZhciBjbGFzc2VzID0gb3B0cy5jbGFzc05hbWUobm9kZSkuc3BsaXQoJyAnKTtcbiAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCBjbGFzc0xpc3QubGVuZ3RoOyBpKyspIHtcbiAgICAgICAgICAgIGlmIChjbGFzc2VzLmluZGV4T2YoY2xhc3NMaXN0W2ldKSA9PT0gLTEpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgICAgZm9yICh2YXIga2V5IGluIGF0dHJpYnV0ZXMpIHtcbiAgICAgICAgICAgIHZhciBhdHRyID0gb3B0cy5hdHRyKG5vZGUsIGtleSk7XG4gICAgICAgICAgICB2YXIgdCA9IGF0dHJpYnV0ZXNba2V5XVswXTtcbiAgICAgICAgICAgIHZhciB2ID0gYXR0cmlidXRlc1trZXldWzFdO1xuICAgICAgICAgICAgaWYgKGF0dHIgPT09IHVuZGVmaW5lZCkge1xuICAgICAgICAgICAgICAgIHJldHVybiBmYWxzZTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGlmICh0ID09PSAnaGFzJykge1xuICAgICAgICAgICAgICAgIHJldHVybiB0cnVlO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgaWYgKHQgPT09ICdleGFjdCcgJiYgYXR0ciAhPT0gdikge1xuICAgICAgICAgICAgICAgIHJldHVybiBmYWxzZTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2UgaWYgKHQgIT09ICdleGFjdCcpIHtcbiAgICAgICAgICAgICAgICBpZiAodHlwZW9mIHYgIT09ICdzdHJpbmcnKSB7XG4gICAgICAgICAgICAgICAgICAgIHRocm93IG5ldyBFcnJvcignQWxsIG5vbi1zdHJpbmcgdmFsdWVzIGhhdmUgdG8gYmUgYW4gZXhhY3QgbWF0Y2gnKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgaWYgKHQgPT09ICdzdGFydHNXaXRoJyAmJiAhYXR0ci5zdGFydHNXaXRoKHYpKSB7XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiBmYWxzZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgaWYgKHQgPT09ICdlbmRzV2l0aCcgJiYgIWF0dHIuZW5kc1dpdGgodikpIHtcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICBpZiAodCA9PT0gJ2NvbnRhaW5zJyAmJiBhdHRyLmluZGV4T2YodikgPT09IC0xKSB7XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiBmYWxzZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgaWYgKHQgPT09ICd3aGl0ZXNwYWNlJyAmJiBhdHRyLnNwbGl0KCcgJykuaW5kZXhPZih2KSA9PT0gLTEpIHtcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICBpZiAodCA9PT0gJ2Rhc2gnICYmIGF0dHIuc3BsaXQoJy0nKS5pbmRleE9mKHYpID09PSAtMSkge1xuICAgICAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgICAgIGZvciAodmFyIGkgPSAwOyBpIDwgcHNldWRvcy5sZW5ndGg7IGkrKykge1xuICAgICAgICAgICAgdmFyIF9iID0gcHNldWRvc1tpXSwgdCA9IF9iWzBdLCBkYXRhID0gX2JbMV07XG4gICAgICAgICAgICBpZiAodCA9PT0gJ2NvbnRhaW5zJyAmJiBkYXRhICE9PSBvcHRzLmNvbnRlbnRzKG5vZGUpKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgaWYgKHQgPT09ICdlbXB0eScgJiZcbiAgICAgICAgICAgICAgICAob3B0cy5jb250ZW50cyhub2RlKSB8fCBvcHRzLmNoaWxkcmVuKG5vZGUpLmxlbmd0aCAhPT0gMCkpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBpZiAodCA9PT0gJ3Jvb3QnICYmIG9wdHMucGFyZW50KG5vZGUpICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBpZiAodC5pbmRleE9mKCdjaGlsZCcpICE9PSAtMSkge1xuICAgICAgICAgICAgICAgIGlmICghb3B0cy5wYXJlbnQobm9kZSkpIHtcbiAgICAgICAgICAgICAgICAgICAgcmV0dXJuIGZhbHNlO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICB2YXIgc2libGluZ3MgPSBvcHRzLmNoaWxkcmVuKG9wdHMucGFyZW50KG5vZGUpKTtcbiAgICAgICAgICAgICAgICBpZiAodCA9PT0gJ2ZpcnN0LWNoaWxkJyAmJiBzaWJsaW5ncy5pbmRleE9mKG5vZGUpICE9PSAwKSB7XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiBmYWxzZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgaWYgKHQgPT09ICdsYXN0LWNoaWxkJyAmJlxuICAgICAgICAgICAgICAgICAgICBzaWJsaW5ncy5pbmRleE9mKG5vZGUpICE9PSBzaWJsaW5ncy5sZW5ndGggLSAxKSB7XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiBmYWxzZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgaWYgKHQgPT09ICdudGgtY2hpbGQnKSB7XG4gICAgICAgICAgICAgICAgICAgIHZhciByZWdleCA9IC8oW1xcKy1dPykoXFxkKikobj8pKFxcK1xcZCspPy87XG4gICAgICAgICAgICAgICAgICAgIHZhciBwYXJzZVJlc3VsdCA9IHJlZ2V4LmV4ZWMoZGF0YSkuc2xpY2UoMSk7XG4gICAgICAgICAgICAgICAgICAgIHZhciBpbmRleCA9IHNpYmxpbmdzLmluZGV4T2Yobm9kZSk7XG4gICAgICAgICAgICAgICAgICAgIGlmICghcGFyc2VSZXN1bHRbMF0pIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIHBhcnNlUmVzdWx0WzBdID0gJysnO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgIHZhciBmYWN0b3IgPSBwYXJzZVJlc3VsdFsxXVxuICAgICAgICAgICAgICAgICAgICAgICAgPyBwYXJzZUludChwYXJzZVJlc3VsdFswXSArIHBhcnNlUmVzdWx0WzFdKVxuICAgICAgICAgICAgICAgICAgICAgICAgOiB1bmRlZmluZWQ7XG4gICAgICAgICAgICAgICAgICAgIHZhciBhZGQgPSBwYXJzZUludChwYXJzZVJlc3VsdFszXSB8fCAnMCcpO1xuICAgICAgICAgICAgICAgICAgICBpZiAoZmFjdG9yICYmXG4gICAgICAgICAgICAgICAgICAgICAgICBwYXJzZVJlc3VsdFsyXSA9PT0gJ24nICYmXG4gICAgICAgICAgICAgICAgICAgICAgICBpbmRleCAlIGZhY3RvciAhPT0gYWRkKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgZWxzZSBpZiAoIWZhY3RvciAmJlxuICAgICAgICAgICAgICAgICAgICAgICAgcGFyc2VSZXN1bHRbMl0gJiZcbiAgICAgICAgICAgICAgICAgICAgICAgICgocGFyc2VSZXN1bHRbMF0gPT09ICcrJyAmJiBpbmRleCAtIGFkZCA8IDApIHx8XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgKHBhcnNlUmVzdWx0WzBdID09PSAnLScgJiYgaW5kZXggLSBhZGQgPj0gMCkpKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gZmFsc2U7XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgZWxzZSBpZiAoIXBhcnNlUmVzdWx0WzJdICYmIGZhY3RvciAmJlxuICAgICAgICAgICAgICAgICAgICAgICAgaW5kZXggIT09IGZhY3RvciAtIDEpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIHJldHVybiBmYWxzZTtcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICByZXR1cm4gdHJ1ZTtcbiAgICB9O1xufVxuZXhwb3J0cy5jcmVhdGVNYXRjaGVzID0gY3JlYXRlTWF0Y2hlcztcbi8vIyBzb3VyY2VNYXBwaW5nVVJMPW1hdGNoZXMuanMubWFwIiwiXCJ1c2Ugc3RyaWN0XCI7XG5PYmplY3QuZGVmaW5lUHJvcGVydHkoZXhwb3J0cywgXCJfX2VzTW9kdWxlXCIsIHsgdmFsdWU6IHRydWUgfSk7XG52YXIgc2VsZWN0b3JQYXJzZXJfMSA9IHJlcXVpcmUoXCIuL3NlbGVjdG9yUGFyc2VyXCIpO1xudmFyIG1hdGNoZXNfMSA9IHJlcXVpcmUoXCIuL21hdGNoZXNcIik7XG5mdW5jdGlvbiBjcmVhdGVRdWVyeVNlbGVjdG9yKG9wdGlvbnMsIG1hdGNoZXMpIHtcbiAgICB2YXIgX21hdGNoZXMgPSBtYXRjaGVzIHx8IG1hdGNoZXNfMS5jcmVh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YXIgc2libGluZ3MgPSBvcHRpb25zLmNoaWxkcmVuKG9wdGlvbnMucGFyZW50KG5vZGUpKTtcbiAgICAgICAgZm9yICh2YXIgaSA9IHNpYmxpbmdzLmluZGV4T2Yobm9kZSkgKyAxOyBpIDwgc2libGluZ3MubGVuZ3RoOyBpKyspIHtcbiAgICAgICAgICAgIGlmICh0eXBlb2Ygc2libGluZ3NbaV0gPT09ICdzdHJpbmcnKSB7XG4gICAgICAgICAgICAgICAgY29udGludWU7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICB2YXIgbiA9IF9tYXRjaGVzKHNlbGVjdG9yLCBzaWJsaW5nc1tpXSk7XG4gICAgICAgICAgICBpZiAobikge1xuICAgICAgICAgICAgICAgIGlmICh0eXBlb2YgbiA9PT0gJ29iamVjdCcpIHtcbiAgICAgICAgICAgICAgICAgICAgcmVzdWx0cy5wdXNoKG4pO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgICAgICAgICAgcmVzdWx0cy5wdXNoKHNpYmxpbmdzW2ldKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBpZiAobmV4dCkge1xuICAgICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgICAgIHJldHVybiByZXN1bHRzO1xuICAgIH1cbiAgICByZXR1cm4gZnVuY3Rpb24gcXVlcnlTZWxlY3RvcihzZWxlY3Rvciwgbm9kZSkge1xuICAgICAgICBpZiAoIW5vZGUpIHtcbiAgICAgICAgICAgIHJldHVybiBbXTtcbiAgICAgICAgfVxuICAgICAgICB2YXIgc2VsID0gdHlwZW9mIHNlbGVjdG9yID09PSAnb2JqZWN0JyA/IHNlbGVjdG9yIDogc2VsZWN0b3JQYXJzZXJfMS5wYXJzZVNlbGVjdG9yKHNlbGVjdG9yKTtcbiAgICAgICAgdmFyIHJlc3VsdHMgPSBbbm9kZV07XG4gICAgICAgIHZhciBjdXJyZW50U2VsZWN0b3IgPSBzZWw7XG4gICAgICAgIHZhciBjdXJyZW50Q29tYmluYXRvciA9ICdzdWJ0cmVlJztcbiAgICAgICAgdmFyIHRhaWwgPSB1bmRlZmluZWQ7XG4gICAgICAgIHZhciBfbG9vcF8xID0gZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgdGFpbCA9IGN1cnJlbnRTZWxlY3Rvci5uZXh0U2VsZWN0b3I7XG4gICAgICAgICAgICBjdXJyZW50U2VsZWN0b3IubmV4dFNlbGVjdG9yID0gdW5kZWZpbmVkO1xuICAgICAgICAgICAgaWYgKGN1cnJlbnRDb21iaW5hdG9yID09PSAnc3VidHJlZScgfHxcbiAgICAgICAgICAgICAgICBjdXJyZW50Q29tYmluYXRvciA9PT0gJ2NoaWxkJykge1xuICAgICAgICAgICAgICAgIHZhciBkZXB0aF8xID0gY3VycmVudENvbWJpbmF0b3IgPT09ICdzdWJ0cmVlJyA/IEluZmluaXR5IDogMTtcbiAgICAgICAgICAgICAgICByZXN1bHRzID0gcmVzdWx0c1xuICAgICAgICAgICAgICAgICAgICAubWFwKGZ1bmN0aW9uIChuKSB7IHJldHVybiBmaW5kU3VidHJlZShjdXJyZW50U2VsZWN0b3IsIGRlcHRoXzEsIG4pOyB9KVxuICAgICAgICAgICAgICAgICAgICAucmVkdWNlKGZ1bmN0aW9uIChhY2MsIGN1cnIpIHsgcmV0dXJuIGFjYy5jb25jYXQoY3Vycik7IH0sIFtdKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgIHZhciBuZXh0XzEgPSBjdXJyZW50Q29tYmluYXRvciA9PT0gJ25leHRTaWJsaW5nJztcbiAgICAgICAgICAgICAgICByZXN1bHRzID0gcmVzdWx0c1xuICAgICAgICAgICAgICAgICAgICAubWFwKGZ1bmN0aW9uIChuKSB7IHJldHVybiBmaW5kU2libGluZyhjdXJyZW50U2VsZWN0b3IsIG5leHRf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5leGVjKHNlbCk7XG4gICAgICAgIGlmICghbWF0Y2ggJiYgbGFzdENvbWJpbmF0b3IgPT09IHVuZGVmaW5lZCkge1xuICAgICAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdQYXJzZSBlcnJvciwgaW52YWxpZCBzZWxlY3RvcicpO1xuICAgICAgICB9XG4gICAgICAgIGVsc2UgaWYgKG1hdGNoICYmIGNvbWJpbmF0b3JSZWdleC50ZXN0KG1hdGNoWzBdKSkge1xuICAgICAgICAgICAgdmFyIGNvbWIgPSBjb21iaW5hdG9yUmVnZXguZXhlYyhtYXRjaFswXSlbMF07XG4gICAgICAgICAgICBsYXN0Q29tYmluYXRvciA9IGNvbWI7XG4gICAgICAgICAgICBpbmRleCA9IHJlZ2V4Lmxhc3RJbmRleDtcbiAgICAgICAgfVxuICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgIGlmIChsYXN0Q29tYmluYXRvciAhPT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICAgICAgbmV4dFNlbGVjdG9yID0gW1xuICAgICAgICAgICAgICAgICAgICBnZXRDb21iaW5hdG9yKGxhc3RDb21iaW5hdG9yKSxcbiAgICAgICAgICAgICAgICAgICAgcGFyc2VTZWxlY3RvcihzZWwuc3Vic3RyaW5nKGluZGV4KSlcbiAgICAgICAgICAgICAgICBdO1xuICAgICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgbWF0Y2hlcy5wdXNoKG1hdGNoWzBdKTtcbiAgICAgICAgfVxuICAgIH1cbiAgICB2YXIgY2xhc3NMaXN0ID0gbWF0Y2hlc1xuICAgICAgICAuZmlsdGVyKGZ1bmN0aW9uIChzKSB7IHJldHVybiBzLnN0YXJ0c1dpdGgoJy4nKTsgfSlcbiAgICAgICAgLm1hcChmdW5jdGlvbiAocykgeyByZXR1cm4gcy5zdWJzdHJpbmcoMSk7IH0pO1xuICAgIHZhciBpZHMgPSBtYXRjaGVzLmZpbHRlcihmdW5jdG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0dXJuIFtzZWwsIHVuZGVmaW5lZF07XG4gICAgfVxuICAgIGlmIChzZWwuc3RhcnRzV2l0aCgnY29udGFpbnMnKSkge1xuICAgICAgICB2YXIgdGV4dCA9IHNlbC5zbGljZSgxMCwgLTIpO1xuICAgICAgICByZXR1cm4gWydjb250YWlucycsIHRleHRdO1xuICAgIH1cbiAgICB2YXIgY29udGVudCA9IHNlbC5zbGljZSgxMCwgLTEpO1xuICAgIGlmIChjb250ZW50ID09PSAnZXZlbicpIHtcbiAgICAgICAgY29udGVudCA9ICcybic7XG4gICAgfVxuICAgIGlmIChjb250ZW50ID09PSAnb2RkJykge1xuICAgICAgICBjb250ZW50ID0gJzJuKzEnO1xuICAgIH1cbiAgICByZXR1cm4gWydudGgtY2hpbGQnLCBjb250ZW50XTtcbn1cbmZ1bmN0aW9uIGdldE9wKG9wKSB7XG4gICAgc3dpdGNoIChvcCkge1xuICAgICAgICBjYXNlICc9JzpcbiAgICAgICAgICAgIHJldHVybiAnZXhhY3QnO1xuICAgICAgICBjYXNlICdePSc6XG4gICAgICAgICAgICByZXR1cm4gJ3N0YXJ0c1dpdGgnO1xuICAgICAgICBjYXNlICckPSc6XG4gICAgICAgICAgICByZXR1cm4gJ2VuZHNXaXRoJztcbiAgICAgICAgY2FzZSAnKj0nOlxuICAgICAgICAgICAgcmV0dXJuICdjb250YWlucyc7XG4gICAgICAgIGNhc2UgJ349JzpcbiAgICAgICAgICAgIHJldHVybiAnd2hpdGVzcGFjZSc7XG4gICAgICAgIGNhc2UgJ3w9JzpcbiAgICAgICAgICAgIHJldHVybiAnZGFzaCc7XG4gICAgICAgIGRlZmF1bHQ6XG4gICAgICAgICAgICByZXR1cm4gJ2hhcyc7XG4gICAgfVxufVxuZnVuY3Rpb24gZ2V0Q29tYmluYXRvcihjb21iKSB7XG4gICAgc3dpdGNoIChjb21iLnRyaW0oKSkge1xuICAgICAgICBjYXNlICc+JzpcbiAgICAgICAgICAgIHJldHVybiAnY2hpbGQnO1xuICAg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Ttcbn1cblxucnVuKG1haW4sIHtcbiAgRE9NOiBtYWtlRE9NRHJpdmVyKCcjYXBwJylcbn0pO1xuIl19 diff --git a/examples/visual.html b/examples/visual.html index e85d0e6..81e4151 100644 --- a/examples/visual.html +++ b/examples/visual.html @@ -45,6 +45,7 @@ + - - diff --git a/package-lock.json b/package-lock.json index 82266a3..ae300b5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,58 +1,33 @@ { - "name": "example", + "name": "jammerjs", "version": "0.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { - "@cycle/dom": { - "version": "22.3.0", - "resolved": "https://registry.npmjs.org/@cycle/dom/-/dom-22.3.0.tgz", - "integrity": "sha512-7VMGsiQsHp8cHD+o3HcuOrvHkTlS7TY1aNyLoEJD0p5cWmxzaiotapFH+6rDpNq4FzuiIeZLR5SPHVNEt9pBQA==", - "requires": { - "@cycle/run": "5.2.0", - "snabbdom": "0.7.3", - "snabbdom-selector": "4.1.0", - "xstream": "11.10.0" - } - }, - "@cycle/run": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@cycle/run/-/run-5.2.0.tgz", - "integrity": "sha512-FTXtJ13I8MkBo7BGBH6S41/vt/Z/s23ZjyhmyTrFGCFxBH5rtIJGcuVPwbSVRlpjFq7G2Vjxd585u+0kANhNvA==", - "requires": { - "quicktask": "1.1.0", - "xstream": "11.10.0" - } - }, "@protobufjs/aspromise": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", - "integrity": "sha1-m4sMxmPWaafY9vXQiToU00jzD78=", - "dev": true + "integrity": "sha1-m4sMxmPWaafY9vXQiToU00jzD78=" }, "@protobufjs/base64": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", - "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", - "dev": true + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==" }, "@protobufjs/codegen": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", - "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==", - "dev": true + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==" }, "@protobufjs/eventemitter": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", - "integrity": "sha1-NVy8mLr61ZePntCV85diHx0Ga3A=", - "dev": true + "integrity": "sha1-NVy8mLr61ZePntCV85diHx0Ga3A=" }, "@protobufjs/fetch": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", "integrity": "sha1-upn7WYYUr2VwDBYZ/wbUVLDYTEU=", - "dev": true, "requires": { "@protobufjs/aspromise": "1.1.2", "@protobufjs/inquire": "1.1.0" @@ -61,38 +36,32 @@ "@protobufjs/float": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", - "integrity": "sha1-Xp4avctz/Ap8uLKR33jIy9l7h9E=", - "dev": true + "integrity": "sha1-Xp4avctz/Ap8uLKR33jIy9l7h9E=" }, "@protobufjs/inquire": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", - "integrity": "sha1-/yAOPnzyQp4tyvwRQIKOjMY48Ik=", - "dev": true + "integrity": "sha1-/yAOPnzyQp4tyvwRQIKOjMY48Ik=" }, "@protobufjs/path": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", - "integrity": "sha1-bMKyDFya1q0NzP0hynZz2Nf79o0=", - "dev": true + "integrity": "sha1-bMKyDFya1q0NzP0hynZz2Nf79o0=" }, "@protobufjs/pool": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", - "integrity": "sha1-Cf0V8tbTq/qbZbw2ZQbWrXhG/1Q=", - "dev": true + "integrity": "sha1-Cf0V8tbTq/qbZbw2ZQbWrXhG/1Q=" }, "@protobufjs/utf8": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", - "integrity": "sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA=", - "dev": true + "integrity": "sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA=" }, "@tensorflow/tfjs": { "version": "0.13.5", "resolved": "https://registry.npmjs.org/@tensorflow/tfjs/-/tfjs-0.13.5.tgz", "integrity": "sha512-a0sbY2IShg+hAD+Es8fy1Ey/afoks4fxSi+PVSZc1st51brCnO3qBbqwDDctRNwx/EOfAroS8IWIKgaWTpsflg==", - "dev": true, "requires": { "@tensorflow/tfjs-converter": "0.6.7", "@tensorflow/tfjs-core": "0.13.11", @@ -103,7 +72,6 @@ "version": "0.6.7", "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-converter/-/tfjs-converter-0.6.7.tgz", "integrity": "sha512-7hsbLbx0KM1Bew00kVoslrnNMOUTyP9NZLDl03cEkrCbEYsaG7jouLxHVz+B0A6/ZPE1N40xmD2JRnu54VKT8g==", - "dev": true, "requires": { "@types/long": "3.0.32", "protobufjs": "6.8.8" @@ -113,7 +81,6 @@ "version": "0.13.11", "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-core/-/tfjs-core-0.13.11.tgz", "integrity": "sha512-jHTD7LbpC3JpsP2mBVD3ZiYV+Xr/l91zpA5HpQVnbdNat5J/IJHabeYwYtukiVyN4amHqyFvGFtX/gjLD82rXg==", - "dev": true, "requires": { "@types/seedrandom": "2.4.27", "@types/webgl-ext": "0.0.30", @@ -124,38 +91,32 @@ "@tensorflow/tfjs-layers": { "version": "0.8.5", "resolved": "https://registry.npmjs.org/@tensorflow/tfjs-layers/-/tfjs-layers-0.8.5.tgz", - "integrity": "sha512-yQoVyh5q3Hh3YmLXGvKAkgsLVFe0VQBRmgVxJkxzzWhCB+NrjUXU/IzHzCRoBcgcXKZTY9/XE5IcvPmJw9cIXw==", - "dev": true + "integrity": "sha512-yQoVyh5q3Hh3YmLXGvKAkgsLVFe0VQBRmgVxJkxzzWhCB+NrjUXU/IzHzCRoBcgcXKZTY9/XE5IcvPmJw9cIXw==" }, "@types/long": { "version": "3.0.32", "resolved": "https://registry.npmjs.org/@types/long/-/long-3.0.32.tgz", - "integrity": "sha512-ZXyOOm83p7X8p3s0IYM3VeueNmHpkk/yMlP8CLeOnEcu6hIwPH7YjZBvhQkR0ZFS2DqZAxKtJ/M5fcuv3OU5BA==", - "dev": true + "integrity": "sha512-ZXyOOm83p7X8p3s0IYM3VeueNmHpkk/yMlP8CLeOnEcu6hIwPH7YjZBvhQkR0ZFS2DqZAxKtJ/M5fcuv3OU5BA==" }, "@types/node": { "version": "10.14.6", "resolved": "https://registry.npmjs.org/@types/node/-/node-10.14.6.tgz", - "integrity": "sha512-Fvm24+u85lGmV4hT5G++aht2C5I4Z4dYlWZIh62FAfFO/TfzXtPpoLI6I7AuBWkIFqZCnhFOoTT7RjjaIL5Fjg==", - "dev": true + "integrity": "sha512-Fvm24+u85lGmV4hT5G++aht2C5I4Z4dYlWZIh62FAfFO/TfzXtPpoLI6I7AuBWkIFqZCnhFOoTT7RjjaIL5Fjg==" }, "@types/seedrandom": { "version": "2.4.27", "resolved": "https://registry.npmjs.org/@types/seedrandom/-/seedrandom-2.4.27.tgz", - "integrity": "sha1-nbVjk33YaRX2kJK8QyWdL0hXjkE=", - "dev": true + "integrity": "sha1-nbVjk33YaRX2kJK8QyWdL0hXjkE=" }, "@types/webgl-ext": { "version": "0.0.30", "resolved": "https://registry.npmjs.org/@types/webgl-ext/-/webgl-ext-0.0.30.tgz", - "integrity": "sha512-LKVgNmBxN0BbljJrVUwkxwRYqzsAEPcZOe6S2T6ZaBDIrFp0qu4FNlpc5sM1tGbXUYFgdVQIoeLk1Y1UoblyEg==", - "dev": true + "integrity": "sha512-LKVgNmBxN0BbljJrVUwkxwRYqzsAEPcZOe6S2T6ZaBDIrFp0qu4FNlpc5sM1tGbXUYFgdVQIoeLk1Y1UoblyEg==" }, "@types/webgl2": { "version": "0.0.4", "resolved": "https://registry.npmjs.org/@types/webgl2/-/webgl2-0.0.4.tgz", - "integrity": "sha512-PACt1xdErJbMUOUweSrbVM7gSIYm1vTncW2hF6Os/EeWi6TXYAYMPp+8v6rzHmypE5gHrxaxZNXgMkJVIdZpHw==", - "dev": true + "integrity": "sha512-PACt1xdErJbMUOUweSrbVM7gSIYm1vTncW2hF6Os/EeWi6TXYAYMPp+8v6rzHmypE5gHrxaxZNXgMkJVIdZpHw==" }, "JSONStream": { "version": "1.3.5", @@ -168,13 +129,13 @@ } }, "accepts": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz", - "integrity": "sha1-63d99gEXI6OxTopywIBcjoZ0a9I=", + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", + "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", "dev": true, "requires": { "mime-types": "2.1.24", - "negotiator": "0.6.1" + "negotiator": "0.6.2" } }, "acorn": { @@ -220,24 +181,14 @@ "dev": true }, "anymatch": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", - "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-1.3.2.tgz", + "integrity": "sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA==", "dev": true, + "optional": true, "requires": { - "micromatch": "3.1.10", + "micromatch": "2.3.11", "normalize-path": "2.1.1" - }, - "dependencies": { - "normalize-path": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", - "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", - "dev": true, - "requires": { - "remove-trailing-separator": "1.1.0" - } - } } }, "apache-crypt": { @@ -256,10 +207,14 @@ "dev": true }, "arr-diff": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", - "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", - "dev": true + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-2.0.0.tgz", + "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", + "dev": true, + "optional": true, + "requires": { + "arr-flatten": "1.1.0" + } }, "arr-flatten": { "version": "1.1.0", @@ -292,10 +247,11 @@ "dev": true }, "array-unique": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", - "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", - "dev": true + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.2.1.tgz", + "integrity": "sha1-odl8yvy8JiXMcPrc6zalDFiwGlM=", + "dev": true, + "optional": true }, "asn1.js": { "version": "4.10.1", @@ -352,6 +308,29 @@ "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", "dev": true }, + "babel-cli": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-cli/-/babel-cli-6.26.0.tgz", + "integrity": "sha1-UCq1SHTX24itALiHoGODzgPQAvE=", + "dev": true, + "requires": { + "babel-core": "6.26.3", + "babel-polyfill": "6.26.0", + "babel-register": "6.26.0", + "babel-runtime": "6.26.0", + "chokidar": "1.7.0", + "commander": "2.20.0", + "convert-source-map": "1.6.0", + "fs-readdir-recursive": "1.1.0", + "glob": "7.1.3", + "lodash": "4.17.11", + "output-file-sync": "1.1.2", + "path-is-absolute": "1.0.1", + "slash": "1.0.0", + "source-map": "0.5.7", + "v8flags": "2.1.1" + } + }, "babel-code-frame": { "version": "6.26.0", "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", @@ -795,6 +774,25 @@ "babel-types": "6.26.0" } }, + "babel-polyfill": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-polyfill/-/babel-polyfill-6.26.0.tgz", + "integrity": "sha1-N5k3q8Z9eJWXCtxiHyhM2WbPIVM=", + "dev": true, + "requires": { + "babel-runtime": "6.26.0", + "core-js": "2.6.5", + "regenerator-runtime": "0.10.5" + }, + "dependencies": { + "regenerator-runtime": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.10.5.tgz", + "integrity": "sha1-M2w+/BIgrc7dosn6tntaeVWjNlg=", + "dev": true + } + } + }, "babel-preset-es2015": { "version": "6.24.1", "resolved": "https://registry.npmjs.org/babel-preset-es2015/-/babel-preset-es2015-6.24.1.tgz", @@ -964,6 +962,18 @@ "is-data-descriptor": "1.0.0", "kind-of": "6.0.2" } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true } } }, @@ -1017,32 +1027,15 @@ } }, "braces": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", - "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/braces/-/braces-1.8.5.tgz", + "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", "dev": true, + "optional": true, "requires": { - "arr-flatten": "1.1.0", - "array-unique": "0.3.2", - "extend-shallow": "2.0.1", - "fill-range": "4.0.0", - "isobject": "3.0.1", - "repeat-element": "1.1.3", - "snapdragon": "0.8.2", - "snapdragon-node": "2.1.1", - "split-string": "3.1.0", - "to-regex": "3.0.2" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - } + "expand-range": "1.8.2", + "preserve": "0.2.0", + "repeat-element": "1.1.3" } }, "brorand": { @@ -1121,12 +1114,12 @@ "querystring-es3": "0.2.1", "read-only-stream": "2.0.0", "readable-stream": "2.3.6", - "resolve": "1.10.0", + "resolve": "1.10.1", "shasum": "1.0.2", "shell-quote": "1.6.1", "stream-browserify": "2.0.2", "stream-http": "2.8.3", - "string_decoder": "1.2.0", + "string_decoder": "1.1.1", "subarg": "1.0.0", "syntax-error": "1.4.0", "through2": "2.0.5", @@ -1252,6 +1245,14 @@ "to-object-path": "0.3.0", "union-value": "1.0.0", "unset-value": "1.0.0" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } } }, "cached-path-relative": { @@ -1274,23 +1275,21 @@ } }, "chokidar": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.5.tgz", - "integrity": "sha512-i0TprVWp+Kj4WRPtInjexJ8Q+BqTE909VpH8xVhXrJkoc5QC8VO9TryGOqTr+2hljzc1sC62t22h5tZePodM/A==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-1.7.0.tgz", + "integrity": "sha1-eY5ol3gVHIB2tLNg5e3SjNortGg=", "dev": true, + "optional": true, "requires": { - "anymatch": "2.0.0", + "anymatch": "1.3.2", "async-each": "1.0.3", - "braces": "2.3.2", - "fsevents": "1.2.8", - "glob-parent": "3.1.0", + "fsevents": "1.2.9", + "glob-parent": "2.0.0", "inherits": "2.0.3", "is-binary-path": "1.0.1", - "is-glob": "4.0.1", - "normalize-path": "3.0.0", + "is-glob": "2.0.1", "path-is-absolute": "1.0.1", - "readdirp": "2.2.1", - "upath": "1.1.2" + "readdirp": "2.2.1" } }, "cipher-base": { @@ -1323,6 +1322,12 @@ "requires": { "is-descriptor": "0.1.6" } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true } } }, @@ -1336,21 +1341,6 @@ "object-visit": "1.0.1" } }, - "color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "requires": { - "color-name": "1.1.3" - } - }, - "color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", - "dev": true - }, "colors": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/colors/-/colors-1.3.3.tgz", @@ -1377,6 +1367,12 @@ } } }, + "commander": { + "version": "2.20.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.0.tgz", + "integrity": "sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ==", + "dev": true + }, "component-emitter": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", @@ -1502,19 +1498,6 @@ "sha.js": "2.4.11" } }, - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "dev": true, - "requires": { - "nice-try": "1.0.5", - "path-key": "2.0.1", - "semver": "5.7.0", - "shebang-command": "1.2.0", - "which": "1.3.1" - } - }, "crypto-browserify": { "version": "3.12.0", "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", @@ -1561,15 +1544,6 @@ "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", "dev": true }, - "define-properties": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", - "dev": true, - "requires": { - "object-keys": "1.1.1" - } - }, "define-property": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", @@ -1608,6 +1582,18 @@ "is-data-descriptor": "1.0.0", "kind-of": "6.0.2" } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true } } }, @@ -1738,40 +1724,6 @@ "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", "dev": true }, - "error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", - "dev": true, - "requires": { - "is-arrayish": "0.2.1" - } - }, - "es-abstract": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.13.0.tgz", - "integrity": "sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg==", - "dev": true, - "requires": { - "es-to-primitive": "1.2.0", - "function-bind": "1.1.1", - "has": "1.0.3", - "is-callable": "1.1.4", - "is-regex": "1.0.4", - "object-keys": "1.1.1" - } - }, - "es-to-primitive": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", - "integrity": "sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==", - "dev": true, - "requires": { - "is-callable": "1.1.4", - "is-date-object": "1.0.1", - "is-symbol": "1.0.2" - } - }, "escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", @@ -1828,38 +1780,23 @@ } }, "expand-brackets": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", - "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-0.1.5.tgz", + "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", "dev": true, + "optional": true, "requires": { - "debug": "2.6.9", - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "posix-character-classes": "0.1.1", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" - }, - "dependencies": { - "define-property": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", - "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", - "dev": true, - "requires": { - "is-descriptor": "0.1.6" - } - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - } + "is-posix-bracket": "0.1.1" + } + }, + "expand-range": { + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/expand-range/-/expand-range-1.8.2.tgz", + "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", + "dev": true, + "optional": true, + "requires": { + "fill-range": "2.2.4" } }, "extend-shallow": { @@ -1884,68 +1821,13 @@ } }, "extglob": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", - "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", + "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", "dev": true, + "optional": true, "requires": { - "array-unique": "0.3.2", - "define-property": "1.0.0", - "expand-brackets": "2.1.4", - "extend-shallow": "2.0.1", - "fragment-cache": "0.2.1", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" - }, - "dependencies": { - "define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", - "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", - "dev": true, - "requires": { - "is-descriptor": "1.0.2" - } - }, - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - }, - "is-accessor-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", - "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", - "dev": true, - "requires": { - "kind-of": "6.0.2" - } - }, - "is-data-descriptor": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", - "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", - "dev": true, - "requires": { - "kind-of": "6.0.2" - } - }, - "is-descriptor": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", - "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", - "dev": true, - "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" - } - } + "is-extglob": "1.0.0" } }, "faye-websocket": { @@ -1957,27 +1839,25 @@ "websocket-driver": "0.7.0" } }, + "filename-regex": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/filename-regex/-/filename-regex-2.0.1.tgz", + "integrity": "sha1-wcS5vuPglyXdsQa3XB4wH+LxiyY=", + "dev": true, + "optional": true + }, "fill-range": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", - "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-2.2.4.tgz", + "integrity": "sha512-cnrcCbj01+j2gTG921VZPnHbjmdAf8oQV/iGeV2kZxGSyfYjjTyY79ErsK1WJWMpw6DaApEX72binqJE+/d+5Q==", "dev": true, + "optional": true, "requires": { - "extend-shallow": "2.0.1", - "is-number": "3.0.0", - "repeat-string": "1.6.1", - "to-regex-range": "2.1.1" - }, - "dependencies": { - "extend-shallow": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", - "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", - "dev": true, - "requires": { - "is-extendable": "0.1.1" - } - } + "is-number": "2.1.0", + "isobject": "2.1.0", + "randomatic": "3.1.1", + "repeat-element": "1.1.3", + "repeat-string": "1.6.1" } }, "finalhandler": { @@ -2001,6 +1881,16 @@ "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", "dev": true }, + "for-own": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/for-own/-/for-own-0.1.5.tgz", + "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", + "dev": true, + "optional": true, + "requires": { + "for-in": "1.0.2" + } + }, "fragment-cache": { "version": "0.2.1", "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", @@ -2022,6 +1912,12 @@ "integrity": "sha1-g8YK/Fi5xWmXAH7Rp2izqzA6RP4=", "dev": true }, + "fs-readdir-recursive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fs-readdir-recursive/-/fs-readdir-recursive-1.1.0.tgz", + "integrity": "sha512-GNanXlVr2pf02+sPN40XN8HG+ePaNcvM0q5mZBd668Obwb0yD5GiUbZOFgwn8kGMY6I3mdyDJzieUy3PTYyTRA==", + "dev": true + }, "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -2029,9 +1925,9 @@ "dev": true }, "fsevents": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.8.tgz", - "integrity": "sha512-tPvHgPGB7m40CZ68xqFGkKuzN+RnpGmSV+hgeKxhRpbxdqKXUFJGC3yonBOLzQBcJyGpdZFDfCsdOC2KFsXzeA==", + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.9.tgz", + "integrity": "sha512-oeyj2H3EjjonWcFjD5NvZNE9Rqe4UW+nQBU2HNeKw0koVLEFIhtyETyAakeAM3de7Z/SW5kcA+fZUait9EApnw==", "dev": true, "optional": true, "requires": { @@ -2589,25 +2485,24 @@ "path-is-absolute": "1.0.1" } }, + "glob-base": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/glob-base/-/glob-base-0.3.0.tgz", + "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", + "dev": true, + "optional": true, + "requires": { + "glob-parent": "2.0.0", + "is-glob": "2.0.1" + } + }, "glob-parent": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", - "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-2.0.0.tgz", + "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", "dev": true, "requires": { - "is-glob": "3.1.0", - "path-dirname": "1.0.2" - }, - "dependencies": { - "is-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", - "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", - "dev": true, - "requires": { - "is-extglob": "2.1.1" - } - } + "is-glob": "2.0.1" } }, "globals": { @@ -2625,20 +2520,17 @@ "hammer-simulator": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/hammer-simulator/-/hammer-simulator-0.0.1.tgz", - "integrity": "sha1-7tO85CtDMgF1o/T4NP4gjl+iSho=", - "dev": true + "integrity": "sha1-7tO85CtDMgF1o/T4NP4gjl+iSho=" }, "hammerjs": { "version": "2.0.8", "resolved": "https://registry.npmjs.org/hammerjs/-/hammerjs-2.0.8.tgz", - "integrity": "sha1-BO93hiz/K7edMPdpIJWTAiK/YPE=", - "dev": true + "integrity": "sha1-BO93hiz/K7edMPdpIJWTAiK/YPE=" }, "handtrackjs": { "version": "0.0.13", "resolved": "https://registry.npmjs.org/handtrackjs/-/handtrackjs-0.0.13.tgz", "integrity": "sha512-wu929ddK5YG+IDscjW7bEeeb4OPHhXx+CL5ddl2cmiTUsF4JwbG3LXPooo0k6ARUAQAPaGk/Xg7OzmzI1izqAA==", - "dev": true, "requires": { "@tensorflow/tfjs": "0.13.5" } @@ -2661,18 +2553,6 @@ "ansi-regex": "2.1.1" } }, - "has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", - "dev": true - }, - "has-symbols": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", - "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", - "dev": true - }, "has-value": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", @@ -2682,6 +2562,14 @@ "get-value": "2.0.6", "has-values": "1.0.0", "isobject": "3.0.1" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } } }, "has-values": { @@ -2694,6 +2582,26 @@ "kind-of": "4.0.0" }, "dependencies": { + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, "kind-of": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", @@ -2746,12 +2654,6 @@ "os-tmpdir": "1.0.2" } }, - "hosted-git-info": { - "version": "2.7.1", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.7.1.tgz", - "integrity": "sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==", - "dev": true - }, "htmlescape": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/htmlescape/-/htmlescape-1.1.1.tgz", @@ -2867,25 +2769,8 @@ "dev": true, "requires": { "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } } }, - "is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", - "dev": true - }, "is-binary-path": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", @@ -2901,12 +2786,6 @@ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", "dev": true }, - "is-callable": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", - "integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==", - "dev": true - }, "is-data-descriptor": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", @@ -2914,25 +2793,8 @@ "dev": true, "requires": { "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } } }, - "is-date-object": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", - "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=", - "dev": true - }, "is-descriptor": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", @@ -2952,6 +2814,23 @@ } } }, + "is-dotfile": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/is-dotfile/-/is-dotfile-1.0.3.tgz", + "integrity": "sha1-pqLzL/0t+wT1yiXs0Pa4PPeYoeE=", + "dev": true, + "optional": true + }, + "is-equal-shallow": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/is-equal-shallow/-/is-equal-shallow-0.1.3.tgz", + "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", + "dev": true, + "optional": true, + "requires": { + "is-primitive": "2.0.0" + } + }, "is-extendable": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", @@ -2959,9 +2838,9 @@ "dev": true }, "is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-1.0.0.tgz", + "integrity": "sha1-rEaBd8SUNAWgkvyPKXYMb/xiBsA=", "dev": true }, "is-finite": { @@ -2974,32 +2853,22 @@ } }, "is-glob": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", - "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-2.0.1.tgz", + "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", "dev": true, "requires": { - "is-extglob": "2.1.1" + "is-extglob": "1.0.0" } }, "is-number": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", - "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-2.1.0.tgz", + "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", "dev": true, + "optional": true, "requires": { "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } } }, "is-plain-object": { @@ -3009,25 +2878,29 @@ "dev": true, "requires": { "isobject": "3.0.1" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } } }, - "is-regex": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", - "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", + "is-posix-bracket": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-posix-bracket/-/is-posix-bracket-0.1.1.tgz", + "integrity": "sha1-MzTceXdDaOkvAW5vvAqI9c1ua8Q=", "dev": true, - "requires": { - "has": "1.0.3" - } + "optional": true }, - "is-symbol": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.2.tgz", - "integrity": "sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==", + "is-primitive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-primitive/-/is-primitive-2.0.0.tgz", + "integrity": "sha1-IHurkWOEmcB7Kt8kCkGochADRXU=", "dev": true, - "requires": { - "has-symbols": "1.0.0" - } + "optional": true }, "is-windows": { "version": "1.0.2", @@ -3047,17 +2920,15 @@ "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", "dev": true }, - "isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", - "dev": true - }, "isobject": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", - "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", - "dev": true + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "optional": true, + "requires": { + "isarray": "1.0.0" + } }, "js-tokens": { "version": "3.0.2", @@ -3071,12 +2942,6 @@ "integrity": "sha1-RsP+yMGJKxKwgz25vHYiF226s0s=", "dev": true }, - "json-parse-better-errors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", - "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", - "dev": true - }, "json-stable-stringify": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-0.0.1.tgz", @@ -3105,10 +2970,13 @@ "dev": true }, "kind-of": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", - "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", - "dev": true + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } }, "labeled-stream-splicer": { "version": "2.0.1", @@ -3148,139 +3016,493 @@ "proxy-middleware": "0.15.0", "send": "0.16.2", "serve-index": "1.9.1" - } - }, - "load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", - "dev": true, - "requires": { - "graceful-fs": "4.1.15", - "parse-json": "4.0.0", - "pify": "3.0.0", - "strip-bom": "3.0.0" - } - }, - "lodash": { - "version": "4.17.11", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", - "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==", - "dev": true - }, - "lodash.memoize": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-3.0.4.tgz", - "integrity": "sha1-LcvSwofLwKVcxCMovQxzYVDVPj8=", - "dev": true - }, - "long": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", - "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==", - "dev": true - }, - "loose-envify": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", - "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", - "dev": true, - "requires": { - "js-tokens": "3.0.2" - } - }, - "map-cache": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", - "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", - "dev": true - }, - "map-stream": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.1.0.tgz", - "integrity": "sha1-5WqpTEyAVaFkBKBnS3jyFffI4ZQ=", - "dev": true - }, - "map-visit": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", - "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", - "dev": true, - "requires": { - "object-visit": "1.0.1" - } - }, - "md5.js": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", - "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", - "dev": true, - "requires": { - "hash-base": "3.0.4", - "inherits": "2.0.3", - "safe-buffer": "5.1.2" - } - }, - "memorystream": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz", - "integrity": "sha1-htcJCzDORV1j+64S3aUaR93K+bI=", - "dev": true - }, - "micromatch": { - "version": "3.1.10", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", - "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", - "dev": true, - "requires": { - "arr-diff": "4.0.0", - "array-unique": "0.3.2", - "braces": "2.3.2", - "define-property": "2.0.2", - "extend-shallow": "3.0.2", - "extglob": "2.0.4", - "fragment-cache": "0.2.1", - "kind-of": "6.0.2", - "nanomatch": "1.2.13", - "object.pick": "1.3.0", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" - } - }, - "miller-rabin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", - "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", - "dev": true, - "requires": { - "bn.js": "4.11.8", - "brorand": "1.1.0" - } - }, - "mime": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz", - "integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==", - "dev": true - }, - "mime-db": { - "version": "1.40.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz", - "integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA==", - "dev": true - }, - "mime-types": { - "version": "2.1.24", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz", - "integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==", - "dev": true, - "requires": { - "mime-db": "1.40.0" - } - }, - "minimalistic-assert": { - "version": "1.0.1", + }, + "dependencies": { + "anymatch": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", + "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", + "dev": true, + "requires": { + "micromatch": "3.1.10", + "normalize-path": "2.1.1" + }, + "dependencies": { + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "1.1.0" + } + } + } + }, + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "braces": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "dev": true, + "requires": { + "arr-flatten": "1.1.0", + "array-unique": "0.3.2", + "extend-shallow": "2.0.1", + "fill-range": "4.0.0", + "isobject": "3.0.1", + "repeat-element": "1.1.3", + "snapdragon": "0.8.2", + "snapdragon-node": "2.1.1", + "split-string": "3.1.0", + "to-regex": "3.0.2" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "0.1.1" + } + } + } + }, + "chokidar": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.5.tgz", + "integrity": "sha512-i0TprVWp+Kj4WRPtInjexJ8Q+BqTE909VpH8xVhXrJkoc5QC8VO9TryGOqTr+2hljzc1sC62t22h5tZePodM/A==", + "dev": true, + "requires": { + "anymatch": "2.0.0", + "async-each": "1.0.3", + "braces": "2.3.2", + "fsevents": "1.2.9", + "glob-parent": "3.1.0", + "inherits": "2.0.3", + "is-binary-path": "1.0.1", + "is-glob": "4.0.1", + "normalize-path": "3.0.0", + "path-is-absolute": "1.0.1", + "readdirp": "2.2.1", + "upath": "1.1.2" + } + }, + "expand-brackets": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "2.6.9", + "define-property": "0.2.5", + "extend-shallow": "2.0.1", + "posix-character-classes": "0.1.1", + "regex-not": "1.0.2", + "snapdragon": "0.8.2", + "to-regex": "3.0.2" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "0.1.6" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "0.1.1" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "0.1.6", + "is-data-descriptor": "0.1.4", + "kind-of": "5.1.0" + } + }, + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "extglob": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "dev": true, + "requires": { + "array-unique": "0.3.2", + "define-property": "1.0.0", + "expand-brackets": "2.1.4", + "extend-shallow": "2.0.1", + "fragment-cache": "0.2.1", + "regex-not": "1.0.2", + "snapdragon": "0.8.2", + "to-regex": "3.0.2" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "1.0.2" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "0.1.1" + } + } + } + }, + "fill-range": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "dev": true, + "requires": { + "extend-shallow": "2.0.1", + "is-number": "3.0.0", + "repeat-string": "1.6.1", + "to-regex-range": "2.1.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "0.1.1" + } + } + } + }, + "glob-parent": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", + "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", + "dev": true, + "requires": { + "is-glob": "3.1.0", + "path-dirname": "1.0.2" + }, + "dependencies": { + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "dev": true, + "requires": { + "is-extglob": "2.1.1" + } + } + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "6.0.2" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "6.0.2" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "1.0.0", + "is-data-descriptor": "1.0.0", + "kind-of": "6.0.2" + } + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-glob": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "dev": true, + "requires": { + "is-extglob": "2.1.1" + } + }, + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + }, + "micromatch": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", + "dev": true, + "requires": { + "arr-diff": "4.0.0", + "array-unique": "0.3.2", + "braces": "2.3.2", + "define-property": "2.0.2", + "extend-shallow": "3.0.2", + "extglob": "2.0.4", + "fragment-cache": "0.2.1", + "kind-of": "6.0.2", + "nanomatch": "1.2.13", + "object.pick": "1.3.0", + "regex-not": "1.0.2", + "snapdragon": "0.8.2", + "to-regex": "3.0.2" + } + }, + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=", + "dev": true + } + } + }, + "lodash": { + "version": "4.17.11", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", + "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==", + "dev": true + }, + "lodash.memoize": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-3.0.4.tgz", + "integrity": "sha1-LcvSwofLwKVcxCMovQxzYVDVPj8=", + "dev": true + }, + "long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" + }, + "loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dev": true, + "requires": { + "js-tokens": "3.0.2" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "dev": true + }, + "map-stream": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.1.0.tgz", + "integrity": "sha1-5WqpTEyAVaFkBKBnS3jyFffI4ZQ=", + "dev": true + }, + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "dev": true, + "requires": { + "object-visit": "1.0.1" + } + }, + "math-random": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/math-random/-/math-random-1.0.4.tgz", + "integrity": "sha512-rUxjysqif/BZQH2yhd5Aaq7vXMSx9NdEsQcyA07uEzIvxgI7zIr33gGsh+RU0/XjmQpCW7RsVof1vlkvQVCK5A==", + "dev": true, + "optional": true + }, + "md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "dev": true, + "requires": { + "hash-base": "3.0.4", + "inherits": "2.0.3", + "safe-buffer": "5.1.2" + } + }, + "micromatch": { + "version": "2.3.11", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-2.3.11.tgz", + "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", + "dev": true, + "optional": true, + "requires": { + "arr-diff": "2.0.0", + "array-unique": "0.2.1", + "braces": "1.8.5", + "expand-brackets": "0.1.5", + "extglob": "0.3.2", + "filename-regex": "2.0.1", + "is-extglob": "1.0.0", + "is-glob": "2.0.1", + "kind-of": "3.2.2", + "normalize-path": "2.1.1", + "object.omit": "2.0.1", + "parse-glob": "3.0.4", + "regex-cache": "0.4.4" + } + }, + "miller-rabin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", + "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", + "dev": true, + "requires": { + "bn.js": "4.11.8", + "brorand": "1.1.0" + } + }, + "mime": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz", + "integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==", + "dev": true + }, + "mime-db": { + "version": "1.40.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz", + "integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA==", + "dev": true + }, + "mime-types": { + "version": "2.1.24", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz", + "integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==", + "dev": true, + "requires": { + "mime-db": "1.40.0" + } + }, + "minimalistic-assert": { + "version": "1.0.1", "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", "dev": true @@ -3352,7 +3574,7 @@ "inherits": "2.0.3", "parents": "1.0.1", "readable-stream": "2.3.6", - "resolve": "1.10.0", + "resolve": "1.10.1", "stream-combiner2": "1.1.1", "subarg": "1.0.0", "through2": "2.0.5", @@ -3402,84 +3624,41 @@ "regex-not": "1.0.2", "snapdragon": "0.8.2", "to-regex": "3.0.2" + }, + "dependencies": { + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + } } }, "negotiator": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", - "integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=", - "dev": true - }, - "nice-try": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", - "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", + "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==", "dev": true }, - "normalize-package-data": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", - "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", - "dev": true, - "requires": { - "hosted-git-info": "2.7.1", - "resolve": "1.10.0", - "semver": "5.7.0", - "validate-npm-package-license": "3.0.4" - } - }, "normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true - }, - "npm-run-all": { - "version": "4.1.5", - "resolved": "https://registry.npmjs.org/npm-run-all/-/npm-run-all-4.1.5.tgz", - "integrity": "sha512-Oo82gJDAVcaMdi3nuoKFavkIHBRVqQ1qvMb+9LHk/cF4P6B2m8aP04hGf7oL6wZ9BuGwX1onlLhpuoofSyoQDQ==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", "dev": true, "requires": { - "ansi-styles": "3.2.1", - "chalk": "2.4.2", - "cross-spawn": "6.0.5", - "memorystream": "0.3.1", - "minimatch": "3.0.4", - "pidtree": "0.3.0", - "read-pkg": "3.0.0", - "shell-quote": "1.6.1", - "string.prototype.padend": "3.0.0" - }, - "dependencies": { - "ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "requires": { - "color-convert": "1.9.3" - } - }, - "chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "requires": { - "ansi-styles": "3.2.1", - "escape-string-regexp": "1.0.5", - "supports-color": "5.5.0" - } - }, - "supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "requires": { - "has-flag": "3.0.0" - } - } + "remove-trailing-separator": "1.1.0" } }, "number-is-nan": { @@ -3513,24 +3692,9 @@ "requires": { "is-descriptor": "0.1.6" } - }, - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } } } }, - "object-keys": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", - "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", - "dev": true - }, "object-visit": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", @@ -3538,6 +3702,25 @@ "dev": true, "requires": { "isobject": "3.0.1" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } + } + }, + "object.omit": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/object.omit/-/object.omit-2.0.1.tgz", + "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", + "dev": true, + "optional": true, + "requires": { + "for-own": "0.1.5", + "is-extendable": "0.1.1" } }, "object.pick": { @@ -3547,6 +3730,14 @@ "dev": true, "requires": { "isobject": "3.0.1" + }, + "dependencies": { + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + } } }, "on-finished": { @@ -3600,13 +3791,15 @@ "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", "dev": true }, - "outpipe": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/outpipe/-/outpipe-1.1.1.tgz", - "integrity": "sha1-UM+GFjZeh+Ax4ppeyTOaPaRyX6I=", + "output-file-sync": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/output-file-sync/-/output-file-sync-1.1.2.tgz", + "integrity": "sha1-0KM+7+YaIF+suQCS6CZZjVJFznY=", "dev": true, "requires": { - "shell-quote": "1.6.1" + "graceful-fs": "4.1.15", + "mkdirp": "0.5.1", + "object-assign": "4.1.1" } }, "pako": { @@ -3638,14 +3831,17 @@ "safe-buffer": "5.1.2" } }, - "parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", + "parse-glob": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/parse-glob/-/parse-glob-3.0.4.tgz", + "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", "dev": true, + "optional": true, "requires": { - "error-ex": "1.3.2", - "json-parse-better-errors": "1.0.2" + "glob-base": "0.3.0", + "is-dotfile": "1.0.3", + "is-extglob": "1.0.0", + "is-glob": "2.0.1" } }, "parseurl": { @@ -3678,12 +3874,6 @@ "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", "dev": true }, - "path-key": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", - "dev": true - }, "path-parse": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", @@ -3696,15 +3886,6 @@ "integrity": "sha1-6GQhf3TDaFDwhSt43Hv31KVyG/I=", "dev": true }, - "path-type": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", - "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", - "dev": true, - "requires": { - "pify": "3.0.0" - } - }, "pause-stream": { "version": "0.0.11", "resolved": "https://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz", @@ -3727,24 +3908,19 @@ "sha.js": "2.4.11" } }, - "pidtree": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/pidtree/-/pidtree-0.3.0.tgz", - "integrity": "sha512-9CT4NFlDcosssyg8KVFltgokyKZIFjoBxw8CTGy+5F38Y1eQWrt8tRayiUOXE+zVKQnYu5BR8JjCtvK3BcnBhg==", - "dev": true - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - }, "posix-character-classes": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", "dev": true }, + "preserve": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/preserve/-/preserve-0.2.0.tgz", + "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", + "dev": true, + "optional": true + }, "private": { "version": "0.1.8", "resolved": "https://registry.npmjs.org/private/-/private-0.1.8.tgz", @@ -3767,7 +3943,6 @@ "version": "6.8.8", "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.8.8.tgz", "integrity": "sha512-AAmHtD5pXgZfi7GMpllpO3q1Xw1OYldr+dMUlAnffGTAhqkg72WdmSY71uKBF/JuyiKs8psYbtKrhi0ASCD8qw==", - "dev": true, "requires": { "@protobufjs/aspromise": "1.1.2", "@protobufjs/base64": "1.1.2", @@ -3787,8 +3962,7 @@ "@types/long": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.0.tgz", - "integrity": "sha512-1w52Nyx4Gq47uuu0EVcsHBxZFJgurQ+rTKS3qMHxR1GY2T8c2AJYd6vZoZ9q1rupaDjU0yT+Jc2XTyXkjeMA+Q==", - "dev": true + "integrity": "sha512-1w52Nyx4Gq47uuu0EVcsHBxZFJgurQ+rTKS3qMHxR1GY2T8c2AJYd6vZoZ9q1rupaDjU0yT+Jc2XTyXkjeMA+Q==" } } }, @@ -3830,10 +4004,33 @@ "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=", "dev": true }, - "quicktask": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/quicktask/-/quicktask-1.1.0.tgz", - "integrity": "sha512-b3w19IEXnt5auacLAbePVsqPyVQUwmuhJQrrWnVhm4pP8PAMg2U9vFHbAD9XYXXbMDjdLJs0x5NLqwTV8uFK4g==" + "randomatic": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/randomatic/-/randomatic-3.1.1.tgz", + "integrity": "sha512-TuDE5KxZ0J461RVjrJZCJc+J+zCkTb1MbH9AQUq68sMhOMcy9jLcb3BrZKgp9q9Ncltdg4QVqWrH02W2EFFVYw==", + "dev": true, + "optional": true, + "requires": { + "is-number": "4.0.0", + "kind-of": "6.0.2", + "math-random": "1.0.4" + }, + "dependencies": { + "is-number": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-4.0.0.tgz", + "integrity": "sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ==", + "dev": true, + "optional": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true, + "optional": true + } + } }, "randombytes": { "version": "2.1.0", @@ -3869,17 +4066,6 @@ "readable-stream": "2.3.6" } }, - "read-pkg": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", - "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", - "dev": true, - "requires": { - "load-json-file": "4.0.0", - "normalize-package-data": "2.5.0", - "path-type": "3.0.0" - } - }, "readable-stream": { "version": "2.3.6", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", @@ -3893,17 +4079,6 @@ "safe-buffer": "5.1.2", "string_decoder": "1.1.1", "util-deprecate": "1.0.2" - }, - "dependencies": { - "string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "dev": true, - "requires": { - "safe-buffer": "5.1.2" - } - } } }, "readdirp": { @@ -3915,6 +4090,282 @@ "graceful-fs": "4.1.15", "micromatch": "3.1.10", "readable-stream": "2.3.6" + }, + "dependencies": { + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "braces": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "dev": true, + "requires": { + "arr-flatten": "1.1.0", + "array-unique": "0.3.2", + "extend-shallow": "2.0.1", + "fill-range": "4.0.0", + "isobject": "3.0.1", + "repeat-element": "1.1.3", + "snapdragon": "0.8.2", + "snapdragon-node": "2.1.1", + "split-string": "3.1.0", + "to-regex": "3.0.2" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "0.1.1" + } + } + } + }, + "expand-brackets": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "2.6.9", + "define-property": "0.2.5", + "extend-shallow": "2.0.1", + "posix-character-classes": "0.1.1", + "regex-not": "1.0.2", + "snapdragon": "0.8.2", + "to-regex": "3.0.2" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "0.1.6" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "0.1.1" + } + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "0.1.6", + "is-data-descriptor": "0.1.4", + "kind-of": "5.1.0" + } + }, + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "extglob": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "dev": true, + "requires": { + "array-unique": "0.3.2", + "define-property": "1.0.0", + "expand-brackets": "2.1.4", + "extend-shallow": "2.0.1", + "fragment-cache": "0.2.1", + "regex-not": "1.0.2", + "snapdragon": "0.8.2", + "to-regex": "3.0.2" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "1.0.2" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "0.1.1" + } + } + } + }, + "fill-range": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "dev": true, + "requires": { + "extend-shallow": "2.0.1", + "is-number": "3.0.0", + "repeat-string": "1.6.1", + "to-regex-range": "2.1.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "0.1.1" + } + } + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "6.0.2" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "6.0.2" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "1.0.0", + "is-data-descriptor": "1.0.0", + "kind-of": "6.0.2" + } + }, + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "1.1.6" + } + } + } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + }, + "micromatch": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", + "dev": true, + "requires": { + "arr-diff": "4.0.0", + "array-unique": "0.3.2", + "braces": "2.3.2", + "define-property": "2.0.2", + "extend-shallow": "3.0.2", + "extglob": "2.0.4", + "fragment-cache": "0.2.1", + "kind-of": "6.0.2", + "nanomatch": "1.2.13", + "object.pick": "1.3.0", + "regex-not": "1.0.2", + "snapdragon": "0.8.2", + "to-regex": "3.0.2" + } + } } }, "regenerate": { @@ -3940,6 +4391,16 @@ "private": "0.1.8" } }, + "regex-cache": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/regex-cache/-/regex-cache-0.4.4.tgz", + "integrity": "sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ==", + "dev": true, + "optional": true, + "requires": { + "is-equal-shallow": "0.1.3" + } + }, "regex-not": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", @@ -4012,9 +4473,9 @@ } }, "resolve": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.10.0.tgz", - "integrity": "sha512-3sUr9aq5OfSg2S9pNtPA9hL1FVEAjvfOC4leW0SNf/mpnaakz2a9femSd6LqAww2RaFctwyf1lCqnTHuF1rxDg==", + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.10.1.tgz", + "integrity": "sha512-KuIe4mf++td/eFb6wkaPbMDnP6kObCaEtIDuHOUED6MNUo4K670KZUHuuvYPZDxNF0WVLw49n06M2m2dXphEzA==", "dev": true, "requires": { "path-parse": "1.0.6" @@ -4032,6 +4493,15 @@ "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", "dev": true }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "7.1.3" + } + }, "ripemd160": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", @@ -4060,14 +4530,7 @@ "seedrandom": { "version": "2.4.3", "resolved": "https://registry.npmjs.org/seedrandom/-/seedrandom-2.4.3.tgz", - "integrity": "sha1-JDhQTa0zkXMUv/GKxNeU8W1qrsw=", - "dev": true - }, - "semver": { - "version": "5.7.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", - "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==", - "dev": true + "integrity": "sha1-JDhQTa0zkXMUv/GKxNeU8W1qrsw=" }, "send": { "version": "0.16.2", @@ -4104,7 +4567,7 @@ "integrity": "sha1-03aNabHn2C5c4FD/9bRTvqEqkjk=", "dev": true, "requires": { - "accepts": "1.3.5", + "accepts": "1.3.7", "batch": "0.6.1", "debug": "2.6.9", "escape-html": "1.0.3", @@ -4162,21 +4625,6 @@ "sha.js": "2.4.11" } }, - "shebang-command": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", - "dev": true, - "requires": { - "shebang-regex": "1.0.0" - } - }, - "shebang-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", - "dev": true - }, "shell-quote": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.6.1.tgz", @@ -4201,19 +4649,6 @@ "integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=", "dev": true }, - "snabbdom": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/snabbdom/-/snabbdom-0.7.3.tgz", - "integrity": "sha512-XNh90GQiV36hWdfSL46fIVrSSvmBuZlWk3++qaEgBeQWQJCqTphcbjTODPv8/vyZHJaB3VhePsWfGxi/zBxXyw==" - }, - "snabbdom-selector": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/snabbdom-selector/-/snabbdom-selector-4.1.0.tgz", - "integrity": "sha512-NDWOVSUR6yPlxH2F9XRwnF59UObLnItfSXcIw6+azkyrEDqT2c8pZ85UHvjijsgdve3g19qsC0/69tB5eZqTvA==", - "requires": { - "tree-selector": "2.1.0" - } - }, "snapdragon": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", @@ -4298,6 +4733,18 @@ "is-data-descriptor": "1.0.0", "kind-of": "6.0.2" } + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true } } }, @@ -4308,17 +4755,6 @@ "dev": true, "requires": { "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } } }, "source-map": { @@ -4355,38 +4791,6 @@ "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", "dev": true }, - "spdx-correct": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.0.tgz", - "integrity": "sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q==", - "dev": true, - "requires": { - "spdx-expression-parse": "3.0.0", - "spdx-license-ids": "3.0.4" - } - }, - "spdx-exceptions": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz", - "integrity": "sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA==", - "dev": true - }, - "spdx-expression-parse": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz", - "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==", - "dev": true, - "requires": { - "spdx-exceptions": "2.2.0", - "spdx-license-ids": "3.0.4" - } - }, - "spdx-license-ids": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.4.tgz", - "integrity": "sha512-7j8LYJLeY/Yb6ACbQ7F76qy5jHkp0U6jgBfJsk97bwWlVUnUWsAgpyaCvo17h0/RQGnQ036tVDomiwoI4pDkQA==", - "dev": true - }, "split": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/split/-/split-0.3.3.tgz", @@ -4484,21 +4888,10 @@ "readable-stream": "2.3.6" } }, - "string.prototype.padend": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/string.prototype.padend/-/string.prototype.padend-3.0.0.tgz", - "integrity": "sha1-86rvfBcZ8XDF6rHDK/eA2W4h8vA=", - "dev": true, - "requires": { - "define-properties": "1.1.3", - "es-abstract": "1.13.0", - "function-bind": "1.1.1" - } - }, "string_decoder": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.2.0.tgz", - "integrity": "sha512-6YqyX6ZWEYguAxgZzHGL7SsCeGx3V2TtOTqZz1xSTSWnqsbWwbptafNyvf/ACquZUXV3DANr5BDIwNYe1mN42w==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "requires": { "safe-buffer": "5.1.2" @@ -4513,12 +4906,6 @@ "ansi-regex": "2.1.1" } }, - "strip-bom": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", - "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", - "dev": true - }, "subarg": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/subarg/-/subarg-1.0.0.tgz", @@ -4542,11 +4929,6 @@ "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", "dev": true }, - "symbol-observable": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-1.2.0.tgz", - "integrity": "sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ==" - }, "syntax-error": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/syntax-error/-/syntax-error-1.4.0.tgz", @@ -4600,17 +4982,6 @@ "dev": true, "requires": { "kind-of": "3.2.2" - }, - "dependencies": { - "kind-of": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", - "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", - "dev": true, - "requires": { - "is-buffer": "1.1.6" - } - } } }, "to-regex": { @@ -4633,13 +5004,19 @@ "requires": { "is-number": "3.0.0", "repeat-string": "1.6.1" + }, + "dependencies": { + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "3.2.2" + } + } } }, - "tree-selector": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/tree-selector/-/tree-selector-2.1.0.tgz", - "integrity": "sha512-Giao15zxN5PvdzJv7HDubn3aSrlsWD9TG9xngYkiuChhIgPH6cQqvCGV5sJ/sWahm7nRtPx46hKax81eyz1sOg==" - }, "trim-right": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", @@ -4761,6 +5138,12 @@ "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", "dev": true + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true } } }, @@ -4800,6 +5183,12 @@ "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", "dev": true }, + "user-home": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/user-home/-/user-home-1.1.1.tgz", + "integrity": "sha1-K1viOjK2Onyd640PKNSFcko98ZA=", + "dev": true + }, "util": { "version": "0.10.4", "resolved": "https://registry.npmjs.org/util/-/util-0.10.4.tgz", @@ -4827,14 +5216,13 @@ "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==", "dev": true }, - "validate-npm-package-license": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", - "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "v8flags": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/v8flags/-/v8flags-2.1.1.tgz", + "integrity": "sha1-qrGh+jDUX4jdMhFIh1rALAtV5bQ=", "dev": true, "requires": { - "spdx-correct": "3.1.0", - "spdx-expression-parse": "3.0.0" + "user-home": "1.1.1" } }, "vary": { @@ -4849,21 +5237,6 @@ "integrity": "sha512-iq+S7vZJE60yejDYM0ek6zg308+UZsdtPExWP9VZoCFCz1zkJoXFnAX7aZfd/ZwrkidzdUZL0C/ryW+JwAiIGw==", "dev": true }, - "watchify": { - "version": "3.11.1", - "resolved": "https://registry.npmjs.org/watchify/-/watchify-3.11.1.tgz", - "integrity": "sha512-WwnUClyFNRMB2NIiHgJU9RQPQNqVeFk7OmZaWf5dC5EnNa0Mgr7imBydbaJ7tGTuPM2hz1Cb4uiBvK9NVxMfog==", - "dev": true, - "requires": { - "anymatch": "2.0.0", - "browserify": "16.2.3", - "chokidar": "2.1.5", - "defined": "1.0.0", - "outpipe": "1.1.1", - "through2": "2.0.5", - "xtend": "4.0.1" - } - }, "websocket-driver": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.0.tgz", @@ -4880,29 +5253,12 @@ "integrity": "sha512-nqHUnMXmBzT0w570r2JpJxfiSD1IzoI+HGVdd3aZ0yNi3ngvQ4jv1dtHt5VGxfI2yj5yqImPhOK4vmIh2xMbGg==", "dev": true }, - "which": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", - "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", - "dev": true, - "requires": { - "isexe": "2.0.0" - } - }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, - "xstream": { - "version": "11.10.0", - "resolved": "https://registry.npmjs.org/xstream/-/xstream-11.10.0.tgz", - "integrity": "sha512-jzFCiRqGtrJi2S1/RPxVFgJwWVBzy4suMPBXlhOi0BJC7VvsXgo2yOHWnOasnj24n2Dlj2Mgfl6fJXPOYmpHFA==", - "requires": { - "symbol-observable": "1.2.0" - } - }, "xtend": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", diff --git a/package.json b/package.json index 1327e3e..0e21688 100644 --- a/package.json +++ b/package.json @@ -3,31 +3,27 @@ "version": "0.0.0", "description": "", "scripts": { - "build": "browserify src/index.js -t babelify --outfile dist/index.js -dv", - "watch": "mkdirp dist && watchify src/index.js -t babelify --outfile dist/index.js -dv", - "live-server": "live-server --watch=./dist/index.js,./index.html", - "start": "npm-run-all --parallel watch live-server" + "prebuild": "rimraf lib && mkdirp lib", + "build": "babel src -d lib", + "browserify": "mkdirp dist && browserify src/index.js --standalone TimeTravel -t babelify --outfile dist/index.js" }, - "repository": "", + "repository": "https://github.com/mjyc/jammer.js", "author": "Michael Jae-Yoon Chung", "license": "MIT", "dependencies": { - "@cycle/dom": "^22.3.0", - "@cycle/run": "^5.2.0", - "xstream": "^11.10.0" + "hammer-simulator": "0.0.1", + "hammerjs": "2.0.8", + "handtrackjs": "0.0.13" }, "devDependencies": { + "babel-cli": "^6.26.0", "babel-core": "^6.26.3", "babel-plugin-transform-object-rest-spread": "^6.26.0", "babel-preset-es2015": "^6.24.1", "babelify": "^8.0.0", "browserify": "^16.2.2", - "hammer-simulator": "0.0.1", - "hammerjs": "2.0.8", - "handtrackjs": "0.0.13", "live-server": "^1.2.0", "mkdirp": "~0.5.0", - "npm-run-all": "^4.1.5", - "watchify": "^3.11.0" + "rimraf": "^2.6.3" } } diff --git a/src/index.js b/src/index.js index 2f0e95c..a3b97eb 100644 --- a/src/index.js +++ b/src/index.js @@ -1,24 +1,9 @@ -import {run} from '@cycle/run'; -import {div, label, input, hr, h1, makeDOMDriver} from '@cycle/dom'; +console.log('hello world!'); +console.log(require('hammerjs')); +console.log(require('../node_modules/handtrackjs/dist/handtrack.min.js')); +// import * as handTrack from 'handtrackjs'; +// console.log(handTrack); -function main(sources) { - const vdom$ = sources.DOM - .select('.myinput').events('input') - .map(ev => ev.target.value) - .startWith('') - .map(name => - div([ - label('Name:'), - input('.myinput', {attrs: {type: 'text'}}), - hr(), - h1(`Hello ${name}`) - ]) - ); - return { - DOM: vdom$, - }; +export default function TimeTravel () { + return 'TimeTravel'; } - -run(main, { - DOM: makeDOMDriver('#app') -});