From 5f83b154c0ac9ae1aa222e34d7bb9c8f86188a6e Mon Sep 17 00:00:00 2001 From: Itay Weinberger Date: Sun, 12 Oct 2014 11:12:21 +0300 Subject: [PATCH] version bump 0.7.14 --- build/release/joola.css | 1 - build/release/joola.js | 15933 +++++++++++++------------------ build/release/joola.min.css | 2 +- build/release/joola.min.js | 10 +- build/release/joola.min.js.map | 2 +- build/temp/joola.css | 1 - build/temp/joola.js | 2781 ++++-- package.json | 2 +- 8 files changed, 8579 insertions(+), 10153 deletions(-) diff --git a/build/release/joola.css b/build/release/joola.css index 9796a73..4edca1a 100644 --- a/build/release/joola.css +++ b/build/release/joola.css @@ -568,7 +568,6 @@ text-align: center; margin-bottom: 20px; } - [jio-domain="joola"] { margin: 0; padding: 0; diff --git a/build/release/joola.js b/build/release/joola.js index 79fa113..ce45ac7 100644 --- a/build/release/joola.js +++ b/build/release/joola.js @@ -1,4712 +1,1841 @@ -;(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o0) - { - if( b[key] instanceof Array ) // http://javascript.crockford.com/remedial.html - { a[key] = extenduptolevel([], b[key],levels-1,context,newobjs,a,key,true); } - else if(b[key]===null) - { a[key] = null; } - else if( b[key] instanceof Date ) - { a[key]= new b[key].constructor();a[key].setTime(b[key].getTime()); } - else - { a[key] = extenduptolevel({}, b[key],levels-1,context,newobjs,a,key,true); } - } - else - { a[key] = b[key]; } - } - else if(typeof a[key] === 'object' && a[key] !== null && levels>0) - { a[key] = extenduptolevel(a[key], b[key],levels-1,context,newobjs,a,key,true); } - else - { a[key] = b[key]; } - } - } - if(clean_context) {context=null;newobjs=null;} - - if(!haveaparent) - { - aparent=null; - return a; - } - if(typeof a === 'object' && !(a instanceof Array) ) - { - /*a.constructor = b.constructor; - a.prototype = b.prototype;*/ - } - return a; -} exports.extenduptolevel=extenduptolevel; - -function clone(obj) -{ - if (typeof obj === 'object') - { - if (obj ===null ) { return null; } - if (obj instanceof Array ) - { return extend([], obj); } - else if( obj instanceof Date ) - { - var t= new obj.constructor(); - t.setTime(obj.getTime()); - return t; - } - else - { return extend({}, obj); } - } - return obj; -} exports.clone=clone; - -function cloneextend(obj,exteddata) -{ - if (typeof obj === 'object') - { - if (obj ===null ) { return null; } - return extend(clone(obj),exteddata); - } - return obj; -} exports.cloneextend=cloneextend; - - -function cloneuptolevel(obj,level) // clone only numlevels levels other levels leave references -{ - if (typeof obj === 'object') - { - if (obj ===null ) { return null; } - if (obj instanceof Array ) { return extenduptolevel([], obj,level); } - return extenduptolevel({}, obj,level); - } - return obj; -} exports.cloneuptolevel=cloneuptolevel; - -function foreach(object, block, context) -{ - if (object) - { - if (typeof object === "object" && object instanceof Array) - return object.forEach(object, block, context) - else //if (typeof object === "object") // or (object instanceof Function)... - { - if(object) - for (var key in object) - { - if(object.hasOwnProperty(key)) - { - if(block.call(context, object[key], key, object)===false)break; - } - } - } - } -} exports.foreach=foreach; - -/* - hasbugs and useless, yet interesting maybe developed later for dot pathed object transformation: - - { - 'foo.bar':'bluebar', - 'foo.color':'blue' - } - - transforemed to - - { - foo: - { - bar:'bluebar', - color:'blue' - } - } - - like: - - var config={}; - cloneextend.dotpath(config,{ - 'foo.bar':'bluebar', - 'foo.color':'blue' - }) - - // - function dotpath(data,dotkeys,preserve) - { - if(!preserve)preserve=false; - var create=!preserve; - if(create) if(!data) data={}; - var keys= dotkeys.split("."),value=data; - for (var i=0;i - * @license MIT - * - * The MIT License (MIT) - * - * Copyright (c) 2013 Viacheslav Lotsmanov - * - * 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. - */ - -/** - * Extening object that entered in first argument. - * Returns extended object or false if have no target object or incorrect type. - * If you wish to clone object, simply use that: - * deepExtend({}, yourObj_1, [yourObj_N]) - first arg is new empty object - */ -var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { - if (arguments.length < 1 || typeof arguments[0] !== 'object') { - return false; - } - - if (arguments.length < 2) return arguments[0]; - - var target = arguments[0]; - - // convert arguments to array and cut off target object - var args = Array.prototype.slice.call(arguments, 1); - - var key, val, src, clone, tmpBuf; - - args.forEach(function (obj) { - if (typeof obj !== 'object') return; - - for (key in obj) { - if ( ! (key in obj)) continue; - - src = target[key]; - val = obj[key]; - - if (val === target) continue; - - if (typeof val !== 'object' || val === null) { - target[key] = val; - continue; - } else if (val instanceof Buffer) { - tmpBuf = new Buffer(val.length); - val.copy(tmpBuf); - target[key] = tmpBuf; - continue; - } else if (val instanceof Date) { - target[key] = new Date(val.getTime()); - continue; - } - - if (typeof src !== 'object' || src === null) { - clone = (Array.isArray(val)) ? [] : {}; - target[key] = deepExtend(clone, val); - continue; - } - - if (Array.isArray(val)) { - clone = (Array.isArray(src)) ? src : []; - } else { - clone = (!Array.isArray(src)) ? src : {}; - } - - target[key] = deepExtend(clone, val); - } - }); - - return target; -} - -},{"__browserify_Buffer":46}],3:[function(require,module,exports){ -/*! - * EventEmitter2 - * https://github.com/hij1nx/EventEmitter2 - * - * Copyright (c) 2013 hij1nx - * Licensed under the MIT license. - */ -;!function(undefined) { - - var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { - return Object.prototype.toString.call(obj) === "[object Array]"; - }; - var defaultMaxListeners = 10; - - function init() { - this._events = {}; - if (this._conf) { - configure.call(this, this._conf); - } - } - - function configure(conf) { - if (conf) { - - this._conf = conf; - - conf.delimiter && (this.delimiter = conf.delimiter); - conf.maxListeners && (this._events.maxListeners = conf.maxListeners); - conf.wildcard && (this.wildcard = conf.wildcard); - conf.newListener && (this.newListener = conf.newListener); - - if (this.wildcard) { - this.listenerTree = {}; - } - } - } - - function EventEmitter(conf) { - this._events = {}; - this.newListener = false; - configure.call(this, conf); - } - - // - // Attention, function return type now is array, always ! - // It has zero elements if no any matches found and one or more - // elements (leafs) if there are matches - // - function searchListenerTree(handlers, type, tree, i) { - if (!tree) { - return []; - } - var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, - typeLength = type.length, currentType = type[i], nextType = type[i+1]; - if (i === typeLength && tree._listeners) { - // - // If at the end of the event(s) list and the tree has listeners - // invoke those listeners. - // - if (typeof tree._listeners === 'function') { - handlers && handlers.push(tree._listeners); - return [tree]; - } else { - for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { - handlers && handlers.push(tree._listeners[leaf]); - } - return [tree]; - } - } - - if ((currentType === '*' || currentType === '**') || tree[currentType]) { - // - // If the event emitted is '*' at this part - // or there is a concrete match at this patch - // - if (currentType === '*') { - for (branch in tree) { - if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { - listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); - } - } - return listeners; - } else if(currentType === '**') { - endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); - if(endReached && tree._listeners) { - // The next element has a _listeners, add it to the handlers. - listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); - } - - for (branch in tree) { - if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { - if(branch === '*' || branch === '**') { - if(tree[branch]._listeners && !endReached) { - listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); - } - listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); - } else if(branch === nextType) { - listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); - } else { - // No match on this one, shift into the tree but not in the type array. - listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); - } - } - } - return listeners; - } - - listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); - } - - xTree = tree['*']; - if (xTree) { - // - // If the listener tree will allow any match for this part, - // then recursively explore all branches of the tree - // - searchListenerTree(handlers, type, xTree, i+1); - } - - xxTree = tree['**']; - if(xxTree) { - if(i < typeLength) { - if(xxTree._listeners) { - // If we have a listener on a '**', it will catch all, so add its handler. - searchListenerTree(handlers, type, xxTree, typeLength); - } - - // Build arrays of matching next branches and others. - for(branch in xxTree) { - if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { - if(branch === nextType) { - // We know the next element will match, so jump twice. - searchListenerTree(handlers, type, xxTree[branch], i+2); - } else if(branch === currentType) { - // Current node matches, move into the tree. - searchListenerTree(handlers, type, xxTree[branch], i+1); - } else { - isolatedBranch = {}; - isolatedBranch[branch] = xxTree[branch]; - searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); - } - } - } - } else if(xxTree._listeners) { - // We have reached the end and still on a '**' - searchListenerTree(handlers, type, xxTree, typeLength); - } else if(xxTree['*'] && xxTree['*']._listeners) { - searchListenerTree(handlers, type, xxTree['*'], typeLength); - } - } - - return listeners; - } - - function growListenerTree(type, listener) { - - type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); - - // - // Looks for two consecutive '**', if so, don't add the event at all. - // - for(var i = 0, len = type.length; i+1 < len; i++) { - if(type[i] === '**' && type[i+1] === '**') { - return; - } - } - - var tree = this.listenerTree; - var name = type.shift(); - - while (name) { - - if (!tree[name]) { - tree[name] = {}; - } - - tree = tree[name]; - - if (type.length === 0) { - - if (!tree._listeners) { - tree._listeners = listener; - } - else if(typeof tree._listeners === 'function') { - tree._listeners = [tree._listeners, listener]; - } - else if (isArray(tree._listeners)) { - - tree._listeners.push(listener); - - if (!tree._listeners.warned) { - - var m = defaultMaxListeners; - - if (typeof this._events.maxListeners !== 'undefined') { - m = this._events.maxListeners; - } - - if (m > 0 && tree._listeners.length > m) { - - tree._listeners.warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - tree._listeners.length); - console.trace(); - } - } - } - return true; - } - name = type.shift(); - } - return true; - } - - // 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. - // - // Obviously not all Emitters should be limited to 10. This function allows - // that to be increased. Set to zero for unlimited. - - EventEmitter.prototype.delimiter = '.'; - - EventEmitter.prototype.setMaxListeners = function(n) { - this._events || init.call(this); - this._events.maxListeners = n; - if (!this._conf) this._conf = {}; - this._conf.maxListeners = n; - }; - - EventEmitter.prototype.event = ''; - - EventEmitter.prototype.once = function(event, fn) { - this.many(event, 1, fn); - return this; - }; - - EventEmitter.prototype.many = function(event, ttl, fn) { - var self = this; - - if (typeof fn !== 'function') { - throw new Error('many only accepts instances of Function'); - } - - function listener() { - if (--ttl === 0) { - self.off(event, listener); - } - fn.apply(this, arguments); - } - - listener._origin = fn; - - this.on(event, listener); - - return self; - }; - - EventEmitter.prototype.emit = function() { - - this._events || init.call(this); - - var type = arguments[0]; - - if (type === 'newListener' && !this.newListener) { - if (!this._events.newListener) { return false; } - } - - // Loop through the *_all* functions and invoke them. - if (this._all) { - var l = arguments.length; - var args = new Array(l - 1); - for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; - for (i = 0, l = this._all.length; i < l; i++) { - this.event = type; - this._all[i].apply(this, args); - } - } - - // If there is no 'error' event listener then throw. - if (type === 'error') { - - if (!this._all && - !this._events.error && - !(this.wildcard && this.listenerTree.error)) { - - if (arguments[1] instanceof Error) { - throw arguments[1]; // Unhandled 'error' event - } else { - throw new Error("Uncaught, unspecified 'error' event."); - } - return false; - } - } - - var handler; - - if(this.wildcard) { - handler = []; - var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); - searchListenerTree.call(this, handler, ns, this.listenerTree, 0); - } - else { - handler = this._events[type]; - } - - if (typeof handler === 'function') { - this.event = type; - if (arguments.length === 1) { - handler.call(this); - } - else if (arguments.length > 1) - switch (arguments.length) { - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - var l = arguments.length; - var args = new Array(l - 1); - for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; - handler.apply(this, args); - } - return true; - } - else if (handler) { - var l = arguments.length; - var args = new Array(l - 1); - for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; - - var listeners = handler.slice(); - for (var i = 0, l = listeners.length; i < l; i++) { - this.event = type; - listeners[i].apply(this, args); - } - return (listeners.length > 0) || !!this._all; - } - else { - return !!this._all; - } - - }; - - EventEmitter.prototype.on = function(type, listener) { - - if (typeof type === 'function') { - this.onAny(type); - return this; - } - - if (typeof listener !== 'function') { - throw new Error('on only accepts instances of Function'); - } - this._events || init.call(this); - - // To avoid recursion in the case that type == "newListeners"! Before - // adding it to the listeners, first emit "newListeners". - this.emit('newListener', type, listener); - - if(this.wildcard) { - growListenerTree.call(this, type, listener); - return this; - } - - if (!this._events[type]) { - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - } - else if(typeof this._events[type] === 'function') { - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - } - else if (isArray(this._events[type])) { - // If we've already got an array, just append. - this._events[type].push(listener); - - // Check for listener leak - if (!this._events[type].warned) { - - var m = defaultMaxListeners; - - if (typeof this._events.maxListeners !== 'undefined') { - m = this._events.maxListeners; - } - - if (m > 0 && this._events[type].length > m) { - - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - console.trace(); - } - } - } - return this; - }; - - EventEmitter.prototype.onAny = function(fn) { - - if (typeof fn !== 'function') { - throw new Error('onAny only accepts instances of Function'); - } - - if(!this._all) { - this._all = []; - } - - // Add the function to the event listener collection. - this._all.push(fn); - return this; - }; - - EventEmitter.prototype.addListener = EventEmitter.prototype.on; - - EventEmitter.prototype.off = function(type, listener) { - if (typeof listener !== 'function') { - throw new Error('removeListener only takes instances of Function'); - } - - var handlers,leafs=[]; - - if(this.wildcard) { - var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); - leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); - } - else { - // does not use listeners(), so no side effect of creating _events[type] - if (!this._events[type]) return this; - handlers = this._events[type]; - leafs.push({_listeners:handlers}); - } - - for (var iLeaf=0; iLeaf 0) { - fns = this._all; - for(i = 0, l = fns.length; i < l; i++) { - if(fn === fns[i]) { - fns.splice(i, 1); - return this; - } - } - } else { - this._all = []; - } - return this; - }; - - EventEmitter.prototype.removeListener = EventEmitter.prototype.off; - - EventEmitter.prototype.removeAllListeners = function(type) { - if (arguments.length === 0) { - !this._events || init.call(this); - return this; - } - - if(this.wildcard) { - var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); - var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); - - for (var iLeaf=0; iLeaf i; ++i) { - if (array.hasOwnProperty(i)) { - if (isValueSet) { - value = callback(value, array[i], i, array); - } - else { - value = array[i]; - isValueSet = true; - } - } - } - - return value; -}; - -// String.prototype.substr - negative index don't work in IE8 -if ('ab'.substr(-1) !== 'b') { - exports.substr = function (str, start, length) { - // did we get a negative start, calculate how much it is from the beginning of the string - if (start < 0) start = str.length + start; - - // call the original function - return str.substr(start, length); - }; -} else { - exports.substr = function (str, start, length) { - return str.substr(start, length); - }; -} - -// String.prototype.trim is supported in IE9 -exports.trim = function (str) { - if (str.trim) return str.trim(); - return str.replace(/^\s+|\s+$/g, ''); -}; - -// Function.prototype.bind is supported in IE9 -exports.bind = function () { - var args = Array.prototype.slice.call(arguments); - var fn = args.shift(); - if (fn.bind) return fn.bind.apply(fn, args); - var self = args.shift(); - return function () { - fn.apply(self, args.concat([Array.prototype.slice.call(arguments)])); - }; -}; - -// Object.create is supported in IE9 -function create(prototype, properties) { - var object; - if (prototype === null) { - object = { '__proto__' : null }; - } - else { - if (typeof prototype !== 'object') { - throw new TypeError( - 'typeof prototype[' + (typeof prototype) + '] != \'object\'' - ); - } - var Type = function () {}; - Type.prototype = prototype; - object = new Type(); - object.__proto__ = prototype; - } - if (typeof properties !== 'undefined' && Object.defineProperties) { - Object.defineProperties(object, properties); - } - return object; -} -exports.create = typeof Object.create === 'function' ? Object.create : create; - -// Object.keys and Object.getOwnPropertyNames is supported in IE9 however -// they do show a description and number property on Error objects -function notObject(object) { - return ((typeof object != "object" && typeof object != "function") || object === null); -} - -function keysShim(object) { - if (notObject(object)) { - throw new TypeError("Object.keys called on a non-object"); - } - - var result = []; - for (var name in object) { - if (hasOwnProperty.call(object, name)) { - result.push(name); - } - } - return result; -} - -// getOwnPropertyNames is almost the same as Object.keys one key feature -// is that it returns hidden properties, since that can't be implemented, -// this feature gets reduced so it just shows the length property on arrays -function propertyShim(object) { - if (notObject(object)) { - throw new TypeError("Object.getOwnPropertyNames called on a non-object"); - } - - var result = keysShim(object); - if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) { - result.push('length'); - } - return result; -} - -var keys = typeof Object.keys === 'function' ? Object.keys : keysShim; -var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? - Object.getOwnPropertyNames : propertyShim; - -if (new Error().hasOwnProperty('description')) { - var ERROR_PROPERTY_FILTER = function (obj, array) { - if (toString.call(obj) === '[object Error]') { - array = exports.filter(array, function (name) { - return name !== 'description' && name !== 'number' && name !== 'message'; - }); - } - return array; - }; - - exports.keys = function (object) { - return ERROR_PROPERTY_FILTER(object, keys(object)); - }; - exports.getOwnPropertyNames = function (object) { - return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object)); - }; -} else { - exports.keys = keys; - exports.getOwnPropertyNames = getOwnPropertyNames; -} - -// Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements -function valueObject(value, key) { - return { value: value[key] }; -} - -if (typeof Object.getOwnPropertyDescriptor === 'function') { - try { - Object.getOwnPropertyDescriptor({'a': 1}, 'a'); - exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - } catch (e) { - // IE8 dom element issue - use a try catch and default to valueObject - exports.getOwnPropertyDescriptor = function (value, key) { - try { - return Object.getOwnPropertyDescriptor(value, key); - } catch (e) { - return valueObject(value, key); - } - }; - } -} else { - exports.getOwnPropertyDescriptor = valueObject; -} - -},{}],5:[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. - -module.exports = Duplex; -var util = require('util'); -var shims = require('_shims'); -var timers = require('timers'); -var Readable = require('_stream_readable'); -var Writable = require('_stream_writable'); - -util.inherits(Duplex, Readable); - -shims.forEach(shims.keys(Writable.prototype), function(method) { - 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); -} - -// 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. - timers.setImmediate(shims.bind(this.end, this)); -} - -},{"_shims":4,"_stream_readable":7,"_stream_writable":9,"timers":16,"util":18}],6:[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. - -module.exports = PassThrough; - -var Transform = require('_stream_transform'); -var util = require('util'); -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":8,"util":18}],7:[function(require,module,exports){ -var process=require("__browserify_process");// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Readable; -Readable.ReadableState = ReadableState; - -var EE = require('events').EventEmitter; -var Stream = require('stream'); -var shims = require('_shims'); -var Buffer = require('buffer').Buffer; -var timers = require('timers'); -var util = require('util'); -var StringDecoder; - -util.inherits(Readable, Stream); - -function ReadableState(options, stream) { - options = options || {}; - - // 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; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; - - // 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, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write 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; - - - // 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; - - // 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'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // 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) { - if (!(this instanceof Readable)) - return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - Stream.call(this); -} - -// 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; - - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } - - if (state.needReadable) - emitReadable(stream); - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// 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); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require('string_decoder').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; -}; - -// Don't raise the hwm > 128MB -var MAX_HWM = 0x800000; -function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; - } - return n; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; - - if (isNaN(n) || n === null) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; - } - - if (n <= 0) - return 0; - - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); - - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; - } - - return n; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function(n) { - var state = this._readableState; - state.calledRead = true; - var nOrig = n; - - if (typeof n !== 'number' || 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)) { - 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; - - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; - - // 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; - - if (doRead) { - 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 called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !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; - } - - state.length -= n; - - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; - - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); - - return ret; -}; - -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode && - !er) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - - -function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(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) - return; - - state.emittedReadable = true; - if (state.sync) - timers.setImmediate(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); -} - -function emitReadable_(stream) { - stream.emit('readable'); -} - - -// 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; - timers.setImmediate(function() { - maybeReadMore_(stream, state); - }); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - 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('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; - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - timers.setImmediate(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); - } - - function 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); - - function 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', cleanup); - - // 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 (!dest._writableState || dest._writableState.needDrain) - ondrain(); - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - // check for listeners before emit removes one-time listeners. - var errListeners = EE.listenerCount(dest, 'error'); - function onerror(er) { - unpipe(); - if (errListeners === 0 && EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - dest.once('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() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function 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) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); - - state.flowing = true; - timers.setImmediate(function() { - flow(src); - }); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function() { - var dest = this; - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; -} - -function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } - - while (state.pipesCount && null !== (chunk = src.read())) { - - if (state.pipesCount === 1) - write(state.pipes, 0, null); - else - shims.forEach(state.pipes, write); - - src.emit('data', chunk); - - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } - - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; - - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } - - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; -} - -function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } -} - - -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - - // 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; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - 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; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } - - // try to find the right one. - var i = shims.indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - 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' && !this._readableState.flowing) - emitDataEvents(this); - - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// 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() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); -}; - -Readable.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); -}; - -function emitDataEvents(stream, startPaused) { - var state = stream._readableState; - - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } - - var paused = startPaused || false; - var readable = false; - - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream.prototype.pipe; - stream.on = stream.addListener = Stream.prototype.on; - - stream.on('readable', function() { - readable = true; - - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); - - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); - - stream.pause = function() { - paused = true; - this.emit('pause'); - }; - - stream.resume = function() { - paused = false; - if (readable) - timers.setImmediate(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; - - // now make it start, just in case it hadn't already. - stream.emit('readable'); -} - -// 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 state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); - if (!chunk || !state.objectMode && !chunk.length) - return; - - var ret = self.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 (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - shims.forEach(events, function(ev) { - stream.on(ev, shims.bind(self.emit, self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - - - -// 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. -function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; - - // nothing in the list, definitely empty. - if (list.length === 0) - return null; - - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer(n); - - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - 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.calledRead) { - state.ended = true; - timers.setImmediate(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } -} - -},{"__browserify_process":47,"_shims":4,"buffer":20,"events":11,"stream":14,"string_decoder":15,"timers":16,"util":18}],8:[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. - -module.exports = Transform; - -var Duplex = require('_stream_duplex'); -var util = require('util'); -util.inherits(Transform, Duplex); - - -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) - stream.push(data); - - if (cb) - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - - -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - - Duplex.call(this, options); - - var ts = this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // 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; - - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); -} - -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('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 && 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; - } -}; - - -function done(stream, er) { - if (er) - return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var rs = stream._readableState; - var ts = stream._transformState; - - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); - - if (ts.transforming) - throw new Error('calling transform done when still transforming'); - - return stream.push(null); -} - -},{"_stream_duplex":5,"util":18}],9:[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 bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; -Writable.WritableState = WritableState; - -var util = require('util'); -var Stream = require('stream'); -var timers = require('timers'); -var Buffer = require('buffer').Buffer; - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - options = options || {}; - - // 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; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - 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; - - // 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; - - // 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, becuase 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.buffer = []; -} - -function Writable(options) { - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Stream.Duplex)) - return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - 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, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - timers.setImmediate(function() { - cb(er); - }); -} - -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - timers.setImmediate(function() { - cb(er); - }); - valid = false; - } - return valid; -} - -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (typeof cb !== 'function') - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); - - return ret; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// 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, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - state.needDrain = !ret; - - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); - - return ret; -} - -function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - if (sync) - timers.setImmediate(function() { - cb(er); - }); - else - cb(er); - - stream.emit('error', er); -} - -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(stream, state); - - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); - - if (sync) { - timers.setImmediate(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - 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; - - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, len, chunk, encoding, cb); - - // 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) { - c++; - break; - } - } - - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); -}; - -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 (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); -}; - - -function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); -} - -function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - timers.setImmediate(cb); - else - stream.once('finish', cb); - } - state.ended = true; -} - -},{"buffer":20,"stream":14,"timers":16,"util":18}],10:[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. - -// UTILITY -var util = require('util'); -var shims = require('_shims'); -var pSlice = Array.prototype.slice; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - this.message = options.message || getMessage(this); -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; -} - -function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} - -function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try { - var ka = shims.keys(a), - kb = shims.keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; - -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (util.isString(expected)) { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function(err) { if (err) {throw err;}}; -},{"_shims":4,"util":18}],11:[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 util = require('util'); - -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!util.isNumber(n) || n < 0) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (util.isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - throw TypeError('Uncaught, unspecified "error" event.'); - } - return false; - } - } - - handler = this._events[type]; - - if (util.isUndefined(handler)) - return false; - - if (util.isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - handler.apply(this, args); - } - } else if (util.isObject(handler)) { - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!util.isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - util.isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (util.isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (util.isObject(this._events[type]) && !this._events[type].warned) { - var m; - if (!util.isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - console.trace(); - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!util.isFunction(listener)) - throw TypeError('listener must be a function'); - - function g() { - this.removeListener(type, g); - listener.apply(this, arguments); - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!util.isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (util.isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (util.isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o + * @license MIT + */ - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } +var base64 = require('base64-js') +var ieee754 = require('ieee754') - listeners = this._events[type]; +exports.Buffer = Buffer +exports.SlowBuffer = Buffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 - if (util.isFunction(listeners)) { - this.removeListener(type, listeners); - } else { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); +/** + * If `Buffer._useTypedArrays`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (compatible down to IE6) + */ +Buffer._useTypedArrays = (function () { + // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+, + // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding + // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support + // because we need to be able to add all the node Buffer API methods. This is an issue + // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438 + try { + var buf = new ArrayBuffer(0) + var arr = new Uint8Array(buf) + arr.foo = function () { return 42 } + return 42 === arr.foo() && + typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray` + } catch (e) { + return false } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (util.isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.listenerCount = function(emitter, type) { - var ret; - if (!emitter._events || !emitter._events[type]) - ret = 0; - else if (util.isFunction(emitter._events[type])) - ret = 1; - else - ret = emitter._events[type].length; - return ret; -}; -},{"util":18}],12:[function(require,module,exports){ -var http = require('http'); +})() -var https = module.exports; +/** + * Class: Buffer + * ============= + * + * The Buffer constructor returns instances of `Uint8Array` that are augmented + * with function properties for all the node `Buffer` API functions. We use + * `Uint8Array` so that square bracket notation works as expected -- it returns + * a single octet. + * + * By augmenting the instances, we can avoid modifying the `Uint8Array` + * prototype. + */ +function Buffer (subject, encoding, noZero) { + if (!(this instanceof Buffer)) + return new Buffer(subject, encoding, noZero) -for (var key in http) { - if (http.hasOwnProperty(key)) https[key] = http[key]; -}; + var type = typeof subject -https.request = function (params, cb) { - if (!params) params = {}; - params.scheme = 'https'; - return http.request.call(this, params, cb); -} -},{"http":28}],13:[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. + // Workaround: node's base64 implementation allows for non-padded strings + // while base64-js does not. + if (encoding === 'base64' && type === 'string') { + subject = stringtrim(subject) + while (subject.length % 4 !== 0) { + subject = subject + '=' + } + } -// Query String Utilities + // Find the length + var length + if (type === 'number') + length = coerce(subject) + else if (type === 'string') + length = Buffer.byteLength(subject, encoding) + else if (type === 'object') + length = coerce(subject.length) // assume that object is array-like + else + throw new Error('First argument needs to be a number, array or string.') -var QueryString = exports; -var util = require('util'); -var shims = require('_shims'); -var Buffer = require('buffer').Buffer; + var buf + if (Buffer._useTypedArrays) { + // Preferred: Return an augmented `Uint8Array` instance for best performance + buf = Buffer._augment(new Uint8Array(length)) + } else { + // Fallback: Return THIS instance of Buffer (created by `new`) + buf = this + buf.length = length + buf._isBuffer = true + } + + var i + if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') { + // Speed optimization -- use set if we're copying from a typed array + buf._set(subject) + } else if (isArrayish(subject)) { + // Treat array-ish objects as a byte array + for (i = 0; i < length; i++) { + if (Buffer.isBuffer(subject)) + buf[i] = subject.readUInt8(i) + else + buf[i] = subject[i] + } + } else if (type === 'string') { + buf.write(subject, 0, encoding) + } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) { + for (i = 0; i < length; i++) { + buf[i] = 0 + } + } -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); + return buf } +// STATIC METHODS +// ============== -function charCode(c) { - return c.charCodeAt(0); +Buffer.isEncoding = function (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } } +Buffer.isBuffer = function (b) { + return !!(b !== null && b !== undefined && b._isBuffer) +} -// a safe fast alternative to decodeURIComponent -QueryString.unescapeBuffer = function(s, decodeSpaces) { - var out = new Buffer(s.length); - var state = 'CHAR'; // states: CHAR, HEX0, HEX1 - var n, m, hexchar; - - for (var inIndex = 0, outIndex = 0; inIndex <= s.length; inIndex++) { - var c = s.charCodeAt(inIndex); - switch (state) { - case 'CHAR': - switch (c) { - case charCode('%'): - n = 0; - m = 0; - state = 'HEX0'; - break; - case charCode('+'): - if (decodeSpaces) c = charCode(' '); - // pass thru - default: - out[outIndex++] = c; - break; - } - break; +Buffer.byteLength = function (str, encoding) { + var ret + str = str + '' + switch (encoding || 'utf8') { + case 'hex': + ret = str.length / 2 + break + case 'utf8': + case 'utf-8': + ret = utf8ToBytes(str).length + break + case 'ascii': + case 'binary': + case 'raw': + ret = str.length + break + case 'base64': + ret = base64ToBytes(str).length + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = str.length * 2 + break + default: + throw new Error('Unknown encoding') + } + return ret +} - case 'HEX0': - state = 'HEX1'; - hexchar = c; - if (charCode('0') <= c && c <= charCode('9')) { - n = c - charCode('0'); - } else if (charCode('a') <= c && c <= charCode('f')) { - n = c - charCode('a') + 10; - } else if (charCode('A') <= c && c <= charCode('F')) { - n = c - charCode('A') + 10; - } else { - out[outIndex++] = charCode('%'); - out[outIndex++] = c; - state = 'CHAR'; - break; - } - break; +Buffer.concat = function (list, totalLength) { + assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' + + 'list should be an Array.') - case 'HEX1': - state = 'CHAR'; - if (charCode('0') <= c && c <= charCode('9')) { - m = c - charCode('0'); - } else if (charCode('a') <= c && c <= charCode('f')) { - m = c - charCode('a') + 10; - } else if (charCode('A') <= c && c <= charCode('F')) { - m = c - charCode('A') + 10; - } else { - out[outIndex++] = charCode('%'); - out[outIndex++] = hexchar; - out[outIndex++] = c; - break; - } - out[outIndex++] = 16 * n + m; - break; + if (list.length === 0) { + return new Buffer(0) + } else if (list.length === 1) { + return list[0] + } + + var i + if (typeof totalLength !== 'number') { + totalLength = 0 + for (i = 0; i < list.length; i++) { + totalLength += list[i].length } } - // TODO support returning arbitrary buffers. + var buf = new Buffer(totalLength) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} - return out.slice(0, outIndex - 1); -}; +// BUFFER INSTANCE METHODS +// ======================= +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 + } + } -QueryString.unescape = function(s, decodeSpaces) { - return QueryString.unescapeBuffer(s, decodeSpaces).toString(); -}; + // must be an even number of digits + var strLen = string.length + assert(strLen % 2 === 0, 'Invalid hex string') + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var byte = parseInt(string.substr(i * 2, 2), 16) + assert(!isNaN(byte), 'Invalid hex string') + buf[offset + i] = byte + } + Buffer._charsWritten = i * 2 + return i +} -QueryString.escape = function(str) { - return encodeURIComponent(str); -}; +function _utf8Write (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(utf8ToBytes(string), buf, offset, length) + return charsWritten +} -var stringifyPrimitive = function(v) { - if (util.isString(v)) - return v; - if (util.isBoolean(v)) - return v ? 'true' : 'false'; - if (util.isNumber(v)) - return isFinite(v) ? v : ''; - return ''; -}; +function _asciiWrite (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(asciiToBytes(string), buf, offset, length) + return charsWritten +} +function _binaryWrite (buf, string, offset, length) { + return _asciiWrite(buf, string, offset, length) +} -QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (util.isNull(obj)) { - obj = undefined; - } +function _base64Write (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(base64ToBytes(string), buf, offset, length) + return charsWritten +} - if (util.isObject(obj)) { - return shims.map(shims.keys(obj), function(k) { - var ks = QueryString.escape(stringifyPrimitive(k)) + eq; - if (util.isArray(obj[k])) { - return shims.map(obj[k], function(v) { - return ks + QueryString.escape(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + QueryString.escape(stringifyPrimitive(obj[k])); - } - }).join(sep); +function _utf16leWrite (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(utf16leToBytes(string), buf, offset, length) + return charsWritten +} +Buffer.prototype.write = function (string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length + length = undefined + } + } else { // legacy + var swap = encoding + encoding = offset + offset = length + length = swap } - if (!name) return ''; - return QueryString.escape(stringifyPrimitive(name)) + eq + - QueryString.escape(stringifyPrimitive(obj)); -}; - -// Parse a key=val string. -QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; + offset = Number(offset) || 0 + var remaining = this.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + encoding = String(encoding || 'utf8').toLowerCase() - if (!util.isString(qs) || qs.length === 0) { - return obj; + var ret + switch (encoding) { + case 'hex': + ret = _hexWrite(this, string, offset, length) + break + case 'utf8': + case 'utf-8': + ret = _utf8Write(this, string, offset, length) + break + case 'ascii': + ret = _asciiWrite(this, string, offset, length) + break + case 'binary': + ret = _binaryWrite(this, string, offset, length) + break + case 'base64': + ret = _base64Write(this, string, offset, length) + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = _utf16leWrite(this, string, offset, length) + break + default: + throw new Error('Unknown encoding') } + return ret +} - var regexp = /\+/g; - qs = qs.split(sep); +Buffer.prototype.toString = function (encoding, start, end) { + var self = this - var maxKeys = 1000; - if (options && util.isNumber(options.maxKeys)) { - maxKeys = options.maxKeys; + encoding = String(encoding || 'utf8').toLowerCase() + start = Number(start) || 0 + end = (end !== undefined) + ? Number(end) + : end = self.length + + // Fastpath empty strings + if (end === start) + return '' + + var ret + switch (encoding) { + case 'hex': + ret = _hexSlice(self, start, end) + break + case 'utf8': + case 'utf-8': + ret = _utf8Slice(self, start, end) + break + case 'ascii': + ret = _asciiSlice(self, start, end) + break + case 'binary': + ret = _binarySlice(self, start, end) + break + case 'base64': + ret = _base64Slice(self, start, end) + break + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + ret = _utf16leSlice(self, start, end) + break + default: + throw new Error('Unknown encoding') } + return ret +} - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; +Buffer.prototype.toJSON = function () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) } +} - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function (target, target_start, start, end) { + var source = this - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (!target_start) target_start = 0 - try { - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - } catch (e) { - k = QueryString.unescape(kstr, true); - v = QueryString.unescape(vstr, true); - } + // Copy 0 bytes; we're done + if (end === start) return + if (target.length === 0 || source.length === 0) return - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (util.isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } + // Fatal error conditions + assert(end >= start, 'sourceEnd < sourceStart') + assert(target_start >= 0 && target_start < target.length, + 'targetStart out of bounds') + assert(start >= 0 && start < source.length, 'sourceStart out of bounds') + assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) + end = this.length + if (target.length - target_start < end - start) + end = target.length - target_start + start + + var len = end - start + + if (len < 100 || !Buffer._useTypedArrays) { + for (var i = 0; i < len; i++) + target[i + target_start] = this[i + start] + } else { + target._set(this.subarray(start, start + len), target_start) } +} - return obj; -}; -},{"_shims":4,"buffer":20,"util":18}],14:[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. +function _base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} -module.exports = Stream; +function _utf8Slice (buf, start, end) { + var res = '' + var tmp = '' + end = Math.min(buf.length, end) -var EE = require('events').EventEmitter; -var util = require('util'); + for (var i = start; i < end; i++) { + if (buf[i] <= 0x7F) { + res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) + tmp = '' + } else { + tmp += '%' + buf[i].toString(16) + } + } -util.inherits(Stream, EE); -Stream.Readable = require('_stream_readable'); -Stream.Writable = require('_stream_writable'); -Stream.Duplex = require('_stream_duplex'); -Stream.Transform = require('_stream_transform'); -Stream.PassThrough = require('_stream_passthrough'); + return res + decodeUtf8Char(tmp) +} -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; +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]) + return ret +} +function _binarySlice (buf, start, end) { + return _asciiSlice(buf, start, end) +} -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. +function _hexSlice (buf, start, end) { + var len = buf.length -function Stream() { - EE.call(this); + 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 } -Stream.prototype.pipe = function(dest, options) { - var source = this; +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 +} - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } +Buffer.prototype.slice = function (start, end) { + var len = this.length + start = clamp(start, len, 0) + end = clamp(end, len, len) + + if (Buffer._useTypedArrays) { + return Buffer._augment(this.subarray(start, end)) + } else { + var sliceLen = end - start + var newBuf = new Buffer(sliceLen, undefined, true) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] } + return newBuf } +} - source.on('data', ondata); +// `get` will be removed in Node 0.13+ +Buffer.prototype.get = function (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) +} - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } +// `set` will be removed in Node 0.13+ +Buffer.prototype.set = function (v, offset) { + console.log('.set() is deprecated. Access using array indexes instead.') + return this.writeUInt8(v, offset) +} + +Buffer.prototype.readUInt8 = function (offset, noAssert) { + if (!noAssert) { + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset < this.length, 'Trying to read beyond buffer length') } - dest.on('drain', ondrain); + if (offset >= this.length) + return - // 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); + return this[offset] +} + +function _readUInt16 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; + var len = buf.length + if (offset >= len) + return - dest.end(); + var val + if (littleEndian) { + val = buf[offset] + if (offset + 1 < len) + val |= buf[offset + 1] << 8 + } else { + val = buf[offset] << 8 + if (offset + 1 < len) + val |= buf[offset + 1] } + return val +} +Buffer.prototype.readUInt16LE = function (offset, noAssert) { + return _readUInt16(this, offset, true, noAssert) +} - function onclose() { - if (didOnEnd) return; - didOnEnd = true; +Buffer.prototype.readUInt16BE = function (offset, noAssert) { + return _readUInt16(this, offset, false, noAssert) +} - if (typeof dest.destroy === 'function') dest.destroy(); +function _readUInt32 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } - // 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. - } + var len = buf.length + if (offset >= len) + return + + var val + if (littleEndian) { + if (offset + 2 < len) + val = buf[offset + 2] << 16 + if (offset + 1 < len) + val |= buf[offset + 1] << 8 + val |= buf[offset] + if (offset + 3 < len) + val = val + (buf[offset + 3] << 24 >>> 0) + } else { + if (offset + 1 < len) + val = buf[offset + 1] << 16 + if (offset + 2 < len) + val |= buf[offset + 2] << 8 + if (offset + 3 < len) + val |= buf[offset + 3] + val = val + (buf[offset] << 24 >>> 0) } + return val +} - source.on('error', onerror); - dest.on('error', onerror); +Buffer.prototype.readUInt32LE = function (offset, noAssert) { + return _readUInt32(this, offset, true, noAssert) +} - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); +Buffer.prototype.readUInt32BE = function (offset, noAssert) { + return _readUInt32(this, offset, false, noAssert) +} - source.removeListener('end', onend); - source.removeListener('close', onclose); +Buffer.prototype.readInt8 = function (offset, noAssert) { + if (!noAssert) { + assert(offset !== undefined && offset !== null, + 'missing offset') + assert(offset < this.length, 'Trying to read beyond buffer length') + } - source.removeListener('error', onerror); - dest.removeListener('error', onerror); + if (offset >= this.length) + return - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); + var neg = this[offset] & 0x80 + if (neg) + return (0xff - this[offset] + 1) * -1 + else + return this[offset] +} - dest.removeListener('close', cleanup); +function _readInt16 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'Trying to read beyond buffer length') } - source.on('end', cleanup); - source.on('close', cleanup); + var len = buf.length + if (offset >= len) + return - dest.on('close', cleanup); + var val = _readUInt16(buf, offset, littleEndian, true) + var neg = val & 0x8000 + if (neg) + return (0xffff - val + 1) * -1 + else + return val +} - dest.emit('pipe', source); +Buffer.prototype.readInt16LE = function (offset, noAssert) { + return _readInt16(this, offset, true, noAssert) +} - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; +Buffer.prototype.readInt16BE = function (offset, noAssert) { + return _readInt16(this, offset, false, noAssert) +} -},{"_stream_duplex":5,"_stream_passthrough":6,"_stream_readable":7,"_stream_transform":8,"_stream_writable":9,"events":11,"util":18}],15:[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. +function _readInt32 (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') + } -var Buffer = require('buffer').Buffer; + var len = buf.length + if (offset >= len) + return -function assertEncoding(encoding) { - if (encoding && !Buffer.isEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); + var val = _readUInt32(buf, offset, littleEndian, true) + var neg = val & 0x80000000 + if (neg) + return (0xffffffff - val + 1) * -1 + else + return val +} + +Buffer.prototype.readInt32LE = function (offset, noAssert) { + return _readInt32(this, offset, true, noAssert) +} + +Buffer.prototype.readInt32BE = function (offset, noAssert) { + return _readInt32(this, offset, false, noAssert) +} + +function _readFloat (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset + 3 < buf.length, 'Trying to read beyond buffer length') } + + return ieee754.read(buf, offset, littleEndian, 23, 4) } -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; +Buffer.prototype.readFloatLE = function (offset, noAssert) { + return _readFloat(this, offset, true, noAssert) +} + +Buffer.prototype.readFloatBE = function (offset, noAssert) { + return _readFloat(this, offset, false, noAssert) +} + +function _readDouble (buf, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset + 7 < buf.length, 'Trying to read beyond buffer length') } - this.charBuffer = new Buffer(6); - this.charReceived = 0; - this.charLength = 0; -}; + return ieee754.read(buf, offset, littleEndian, 52, 8) +} +Buffer.prototype.readDoubleLE = function (offset, noAssert) { + return _readDouble(this, offset, true, noAssert) +} -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - var offset = 0; +Buffer.prototype.readDoubleBE = function (offset, noAssert) { + return _readDouble(this, offset, false, noAssert) +} - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var i = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; +Buffer.prototype.writeUInt8 = function (value, offset, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset < this.length, 'trying to write beyond buffer length') + verifuint(value, 0xff) + } - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, offset, i); - this.charReceived += (i - offset); - offset = i; + if (offset >= this.length) return - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } + this[offset] = value +} - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); +function _writeUInt16 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'trying to write beyond buffer length') + verifuint(value, 0xffff) + } - // lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; + var len = buf.length + if (offset >= len) + return - // if there are no more bytes in this buffer, just emit our char - if (i == buffer.length) return charStr; + for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) { + buf[offset + i] = + (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} - // otherwise cut off the characters end from the beginning of this buffer - buffer = buffer.slice(i, buffer.length); - break; +Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { + _writeUInt16(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) { + _writeUInt16(this, value, offset, false, noAssert) +} + +function _writeUInt32 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'trying to write beyond buffer length') + verifuint(value, 0xffffffff) } - var lenIncomplete = this.detectIncompleteChar(buffer); + var len = buf.length + if (offset >= len) + return - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - lenIncomplete, end); - this.charReceived = lenIncomplete; - end -= lenIncomplete; + for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { + buf[offset + i] = + (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } +} - charStr += buffer.toString(this.encoding, 0, end); +Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { + _writeUInt32(this, value, offset, true, noAssert) +} - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - this.charBuffer.write(charStr.charAt(charStr.length - 1), this.encoding); - return charStr.substring(0, end); +Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { + _writeUInt32(this, value, offset, false, noAssert) +} + +Buffer.prototype.writeInt8 = function (value, offset, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset < this.length, 'Trying to write beyond buffer length') + verifsint(value, 0x7f, -0x80) + } + + if (offset >= this.length) + return + + if (value >= 0) + this.writeUInt8(value, offset, noAssert) + else + this.writeUInt8(0xff + value + 1, offset, noAssert) +} + +function _writeInt16 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 1 < buf.length, 'Trying to write beyond buffer length') + verifsint(value, 0x7fff, -0x8000) } - // or just emit the charStr - return charStr; -}; + var len = buf.length + if (offset >= len) + return -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; + if (value >= 0) + _writeUInt16(buf, value, offset, littleEndian, noAssert) + else + _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) +} - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; +Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { + _writeInt16(this, value, offset, true, noAssert) +} - // See http://en.wikipedia.org/wiki/UTF-8#Description +Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { + _writeInt16(this, value, offset, false, noAssert) +} - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } +function _writeInt32 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') + verifsint(value, 0x7fffffff, -0x80000000) + } - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + var len = buf.length + if (offset >= len) + return - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } + if (value >= 0) + _writeUInt32(buf, value, offset, littleEndian, noAssert) + else + _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) +} - return i; -}; +Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { + _writeInt32(this, value, offset, true, noAssert) +} -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); +Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { + _writeInt32(this, value, offset, false, noAssert) +} - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); +function _writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 3 < buf.length, 'Trying to write beyond buffer length') + verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38) } - return res; -}; + var len = buf.length + if (offset >= len) + return -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); + ieee754.write(buf, value, offset, littleEndian, 23, 4) } -function utf16DetectIncompleteChar(buffer) { - var incomplete = this.charReceived = buffer.length % 2; - this.charLength = incomplete ? 2 : 0; - return incomplete; +Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { + _writeFloat(this, value, offset, true, noAssert) } -function base64DetectIncompleteChar(buffer) { - var incomplete = this.charReceived = buffer.length % 3; - this.charLength = incomplete ? 3 : 0; - return incomplete; +Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { + _writeFloat(this, value, offset, false, noAssert) } -},{"buffer":20}],16:[function(require,module,exports){ -try { - // Old IE browsers that do not curry arguments - if (!setTimeout.call) { - var slicer = Array.prototype.slice; - exports.setTimeout = function(fn) { - var args = slicer.call(arguments, 1); - return setTimeout(function() { - return fn.apply(this, args); - }) - }; +function _writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + assert(value !== undefined && value !== null, 'missing value') + assert(typeof littleEndian === 'boolean', 'missing or invalid endian') + assert(offset !== undefined && offset !== null, 'missing offset') + assert(offset + 7 < buf.length, + 'Trying to write beyond buffer length') + verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308) + } - exports.setInterval = function(fn) { - var args = slicer.call(arguments, 1); - return setInterval(function() { - return fn.apply(this, args); - }); - }; - } else { - exports.setTimeout = setTimeout; - exports.setInterval = setInterval; - } - exports.clearTimeout = clearTimeout; - exports.clearInterval = clearInterval; - - if (window.setImmediate) { - exports.setImmediate = window.setImmediate; - exports.clearImmediate = window.clearImmediate; - } - - // Chrome and PhantomJS seems to depend on `this` pseudo variable being a - // `window` and throws invalid invocation exception otherwise. If this code - // runs in such JS runtime next line will throw and `catch` clause will - // exported timers functions bound to a window. - exports.setTimeout(function() {}); -} catch (_) { - function bind(f, context) { - return function () { return f.apply(context, arguments) }; - } - - if (typeof window !== 'undefined') { - exports.setTimeout = bind(setTimeout, window); - exports.setInterval = bind(setInterval, window); - exports.clearTimeout = bind(clearTimeout, window); - exports.clearInterval = bind(clearInterval, window); - if (window.setImmediate) { - exports.setImmediate = bind(window.setImmediate, window); - exports.clearImmediate = bind(window.clearImmediate, window); - } - } else { - if (typeof setTimeout !== 'undefined') { - exports.setTimeout = setTimeout; - } - if (typeof setInterval !== 'undefined') { - exports.setInterval = setInterval; - } - if (typeof clearTimeout !== 'undefined') { - exports.clearTimeout = clearTimeout; - } - if (typeof clearInterval === 'function') { - exports.clearInterval = clearInterval; - } - } -} + var len = buf.length + if (offset >= len) + return -exports.unref = function unref() {}; -exports.ref = function ref() {}; + ieee754.write(buf, value, offset, littleEndian, 52, 8) +} -if (!exports.setImmediate) { - var currentKey = 0, queue = {}, active = false; +Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { + _writeDouble(this, value, offset, true, noAssert) +} - exports.setImmediate = (function () { - function drain() { - active = false; - for (var key in queue) { - if (queue.hasOwnProperty(currentKey, key)) { - var fn = queue[key]; - delete queue[key]; - fn(); - } - } - } +Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { + _writeDouble(this, value, offset, false, noAssert) +} - if (typeof window !== 'undefined' && - window.postMessage && window.addEventListener) { - window.addEventListener('message', function (ev) { - if (ev.source === window && ev.data === 'browserify-tick') { - ev.stopPropagation(); - drain(); - } - }, true); +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length - return function setImmediate(fn) { - var id = ++currentKey; - queue[id] = fn; - if (!active) { - active = true; - window.postMessage('browserify-tick', '*'); - } - return id; - }; - } else { - return function setImmediate(fn) { - var id = ++currentKey; - queue[id] = fn; - if (!active) { - active = true; - setTimeout(drain, 0); - } - return id; - }; - } - })(); + if (typeof value === 'string') { + value = value.charCodeAt(0) + } - exports.clearImmediate = function clearImmediate(id) { - delete queue[id]; - }; -} + assert(typeof value === 'number' && !isNaN(value), 'value is not a number') + assert(end >= start, 'end < start') -},{}],17:[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. + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return -var punycode = { encode : function (s) { return s } }; -var util = require('util'); -var shims = require('_shims'); + assert(start >= 0 && start < this.length, 'start out of bounds') + assert(end >= 0 && end <= this.length, 'end out of bounds') -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; + for (var i = start; i < end; i++) { + this[i] = value + } +} -exports.Url = Url; +Buffer.prototype.inspect = function () { + var out = [] + var len = this.length + for (var i = 0; i < len; i++) { + out[i] = toHex(this[i]) + if (i === exports.INSPECT_MAX_BYTES) { + out[i + 1] = '...' + break + } + } + return '' +} -function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.host = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.query = null; - this.pathname = null; - this.path = null; - this.href = null; +/** + * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. + * Added in Node 0.12. Only available in browsers that support ArrayBuffer. + */ +Buffer.prototype.toArrayBuffer = function () { + if (typeof Uint8Array !== 'undefined') { + if (Buffer._useTypedArrays) { + return (new Buffer(this)).buffer + } else { + var buf = new Uint8Array(this.length) + for (var i = 0, len = buf.length; i < len; i += 1) + buf[i] = this[i] + return buf.buffer + } + } else { + throw new Error('Buffer.toArrayBuffer not supported in this browser') + } +} + +// HELPER FUNCTIONS +// ================ + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +var BP = Buffer.prototype + +/** + * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods + */ +Buffer._augment = function (arr) { + arr._isBuffer = true + + // save reference to original Uint8Array get/set methods before overwriting + arr._get = arr.get + arr._set = arr.set + + // deprecated, will be removed in node 0.13+ + arr.get = BP.get + arr.set = BP.set + + arr.write = BP.write + arr.toString = BP.toString + arr.toLocaleString = BP.toString + arr.toJSON = BP.toJSON + arr.copy = BP.copy + arr.slice = BP.slice + arr.readUInt8 = BP.readUInt8 + arr.readUInt16LE = BP.readUInt16LE + arr.readUInt16BE = BP.readUInt16BE + arr.readUInt32LE = BP.readUInt32LE + arr.readUInt32BE = BP.readUInt32BE + arr.readInt8 = BP.readInt8 + arr.readInt16LE = BP.readInt16LE + arr.readInt16BE = BP.readInt16BE + arr.readInt32LE = BP.readInt32LE + arr.readInt32BE = BP.readInt32BE + arr.readFloatLE = BP.readFloatLE + arr.readFloatBE = BP.readFloatBE + arr.readDoubleLE = BP.readDoubleLE + arr.readDoubleBE = BP.readDoubleBE + arr.writeUInt8 = BP.writeUInt8 + arr.writeUInt16LE = BP.writeUInt16LE + arr.writeUInt16BE = BP.writeUInt16BE + arr.writeUInt32LE = BP.writeUInt32LE + arr.writeUInt32BE = BP.writeUInt32BE + arr.writeInt8 = BP.writeInt8 + arr.writeInt16LE = BP.writeInt16LE + arr.writeInt16BE = BP.writeInt16BE + arr.writeInt32LE = BP.writeInt32LE + arr.writeInt32BE = BP.writeInt32BE + arr.writeFloatLE = BP.writeFloatLE + arr.writeFloatBE = BP.writeFloatBE + arr.writeDoubleLE = BP.writeDoubleLE + arr.writeDoubleBE = BP.writeDoubleBE + arr.fill = BP.fill + arr.inspect = BP.inspect + arr.toArrayBuffer = BP.toArrayBuffer + + return arr } -// Reference: RFC 3986, RFC 1808, RFC 2396 +// slice(start, end) +function clamp (index, len, defaultValue) { + if (typeof index !== 'number') return defaultValue + index = ~~index; // Coerce to integer. + if (index >= len) return len + if (index >= 0) return index + index += len + if (index >= 0) return index + return 0 +} -// define these here so at least they only have to be -// compiled once on the first module load. -var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, +function coerce (length) { + // Coerce length to a number (possibly NaN), round up + // in case it's fractional (e.g. 123.456) then do a + // double negate to coerce a NaN to 0. Easy, right? + length = ~~Math.ceil(+length) + return length < 0 ? 0 : length +} - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], +function isArray (subject) { + return (Array.isArray || function (subject) { + return Object.prototype.toString.call(subject) === '[object Array]' + })(subject) +} - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), +function isArrayish (subject) { + return isArray(subject) || Buffer.isBuffer(subject) || + subject && typeof subject === 'object' && + typeof subject.length === 'number' +} - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }, - querystring = require('querystring'); +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) return url; +function utf8ToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + var b = str.charCodeAt(i) + if (b <= 0x7F) + byteArray.push(str.charCodeAt(i)) + else { + var start = i + if (b >= 0xD800 && b <= 0xDFFF) i++ + var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%') + for (var j = 0; j < h.length; j++) + byteArray.push(parseInt(h[j], 16)) + } + } + return byteArray +} - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; +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 } -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); +function utf16leToBytes (str) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) } - var rest = url; + return byteArray +} - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = shims.trim(rest); +function base64ToBytes (str) { + return base64.toByteArray(str) +} - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); +function blitBuffer (src, dst, offset, length) { + var pos + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) + break + dst[i + offset] = src[i] } + return i +} - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } +function decodeUtf8Char (str) { + try { + return decodeURIComponent(str) + } catch (err) { + return String.fromCharCode(0xFFFD) // UTF 8 invalid char } +} + +/* + * We have to make sure that the value is a valid integer. This means that it + * is non-negative. It has no fractional component and that it does not + * exceed the maximum allowed value. + */ +function verifuint (value, max) { + assert(typeof value === 'number', 'cannot write a non-number as a number') + assert(value >= 0, 'specified a negative value for writing an unsigned value') + assert(value <= max, 'value is larger than maximum value for type') + assert(Math.floor(value) === value, 'value has a fractional component') +} - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { +function verifsint (value, max, min) { + assert(typeof value === 'number', 'cannot write a non-number as a number') + assert(value <= max, 'value larger than maximum allowed value') + assert(value >= min, 'value smaller than minimum allowed value') + assert(Math.floor(value) === value, 'value has a fractional component') +} - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c +function verifIEEE754 (value, max, min) { + assert(typeof value === 'number', 'cannot write a non-number as a number') + assert(value <= max, 'value larger than maximum allowed value') + assert(value >= min, 'value smaller than minimum allowed value') +} - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. +function assert (test, message) { + if (!test) throw new Error(message || 'Failed assertion') +} - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } +},{"base64-js":2,"ieee754":3}],2:[function(require,module,exports){ +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } +;(function (exports) { + 'use strict'; - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); - } + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array + + var PLUS = '+'.charCodeAt(0) + var SLASH = '/'.charCodeAt(0) + var NUMBER = '0'.charCodeAt(0) + var LOWER = 'a'.charCodeAt(0) + var UPPER = 'A'.charCodeAt(0) + + function decode (elt) { + var code = elt.charCodeAt(0) + if (code === PLUS) + return 62 // '+' + if (code === SLASH) + return 63 // '/' + if (code < NUMBER) + return -1 //no match + if (code < NUMBER + 10) + return code - NUMBER + 26 + 26 + if (code < UPPER + 26) + return code - UPPER + if (code < LOWER + 26) + return code - LOWER + 26 + } - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - hostEnd = hec; - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - hostEnd = rest.length; + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } - // pull out port. - this.parseHost(); + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + var len = b64.length + placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) continue; - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } - } - } + var L = 0 - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } + function push (v) { + arr[L++] = v + } - if (!ipv6Hostname) { - // IDNA Support: Returns a puny coded representation of "domain". - // It only converts the part of the domain name that - // has non ASCII characters. I.e. it dosent matter if - // you call it with a domain that already is in ASCII. - var domainArray = this.hostname.split('.'); - var newOut = []; - for (var i = 0; i < domainArray.length; ++i) { - var s = domainArray[i]; - newOut.push(s.match(/[^A-Za-z0-9_-]/) ? - 'xn--' + punycode.encode(s) : s); - } - this.hostname = newOut.join('.'); - } + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) + push((tmp & 0xFF0000) >> 16) + push((tmp & 0xFF00) >> 8) + push(tmp & 0xFF) + } - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; + if (placeHolders === 2) { + tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) + push(tmp & 0xFF) + } else if (placeHolders === 1) { + tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) + push((tmp >> 8) & 0xFF) + push(tmp & 0xFF) + } - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } - } + return arr + } - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } - } + function encode (num) { + return lookup.charAt(num) + } + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; - } - if (rest) this.pathname = rest; - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; - } + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) + } - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1] + output += encode(temp >> 2) + output += encode((temp << 4) & 0x3F) + output += '==' + break + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += encode(temp >> 10) + output += encode((temp >> 4) & 0x3F) + output += encode((temp << 2) & 0x3F) + output += '=' + break + } - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; -}; + return output + } -// format a parsed object into a url string -function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (util.isString(obj)) obj = urlParse(obj); - if (!(obj instanceof Url)) return Url.prototype.format.call(obj); - return obj.format(); -} + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } +},{}],3:[function(require,module,exports){ +exports.read = function(buffer, offset, isLE, mLen, nBytes) { + var e, m, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = isLE ? (nBytes - 1) : 0, + d = isLE ? -1 : 1, + s = buffer[offset + i]; - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; + 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 (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } + 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); +}; - if (this.query && - util.isObject(this.query) && - shims.keys(this.query).length) { - query = querystring.stringify(this.query); - } +exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c, + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = isLE ? 0 : (nBytes - 1), + d = isLE ? 1 : -1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - var search = this.search || (query && ('?' + query)) || ''; + value = Math.abs(value); - if (protocol && shims.substr(protocol, -1) !== ':') protocol += ':'; + 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; + } - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; - } else if (!host) { - host = ''; + 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; + } } - if (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - return protocol + host + pathname + search + hash; + buffer[offset + i - d] |= s * 128; }; -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} +},{}],4:[function(require,module,exports){ +var Buffer = require('buffer').Buffer; +var intSize = 4; +var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); +var chrsz = 8; -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); -}; +function toArray(buf, bigEndian) { + if ((buf.length % intSize) !== 0) { + var len = buf.length + (intSize - (buf.length % intSize)); + buf = Buffer.concat([buf, zeroBuffer], len); + } -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); + var arr = []; + var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; + for (var i = 0; i < buf.length; i += intSize) { + arr.push(fn.call(buf, i)); + } + return arr; } -Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; +function toBuffer(arr, size, bigEndian) { + var buf = new Buffer(size); + var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; + for (var i = 0; i < arr.length; i++) { + fn.call(buf, arr[i], i * 4, true); } + return buf; +} - var result = new Url(); - shims.forEach(shims.keys(this), function(k) { - result[k] = this[k]; - }, this); +function hash(buf, fn, hashSize, bigEndian) { + if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); + var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); + return toBuffer(arr, hashSize, bigEndian); +} - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; +module.exports = { hash: hash }; - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } +},{"buffer":1}],5:[function(require,module,exports){ +var Buffer = require('buffer').Buffer +var sha = require('./sha') +var sha256 = require('./sha256') +var rng = require('./rng') +var md5 = require('./md5') - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - shims.forEach(shims.keys(relative), function(k) { - if (k !== 'protocol') - result[k] = relative[k]; - }); +var algorithms = { + sha1: sha, + sha256: sha256, + md5: md5 +} - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } +var blocksize = 64 +var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0) +function hmac(fn, key, data) { + if(!Buffer.isBuffer(key)) key = new Buffer(key) + if(!Buffer.isBuffer(data)) data = new Buffer(data) - result.href = result.format(); - return result; + if(key.length > blocksize) { + key = fn(key) + } else if(key.length < blocksize) { + key = Buffer.concat([key, zeroBuffer], blocksize) } - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - shims.forEach(shims.keys(relative), function(k) { - result[k] = relative[k]; - }); - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())); - if (!relative.host) relative.host = ''; - if (!relative.hostname) relative.hostname = ''; - if (relPath[0] !== '') relPath.unshift(''); - if (relPath.length < 2) relPath.unshift(''); - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; + var ipad = new Buffer(blocksize), opad = new Buffer(blocksize) + for(var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C } - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; + var hash = fn(Buffer.concat([ipad, data])) + return fn(Buffer.concat([opad, hash])) +} - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = null; +function hash(alg, key) { + alg = alg || 'sha1' + var fn = algorithms[alg] + var bufs = [] + var length = 0 + if(!fn) error('algorithm:', alg, 'is not yet supported') + return { + update: function (data) { + if(!Buffer.isBuffer(data)) data = new Buffer(data) + + bufs.push(data) + length += data.length + return this + }, + digest: function (enc) { + var buf = Buffer.concat(bufs) + var r = key ? hmac(fn, key, buf) : fn(buf) + bufs = null + return enc ? r.toString(enc) : r } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } +} - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; +function error () { + var m = [].slice.call(arguments).join(' ') + throw new Error([ + m, + 'we accept pull requests', + 'http://github.com/dominictarr/crypto-browserify' + ].join('\n')) +} + +exports.createHash = function (alg) { return hash(alg) } +exports.createHmac = function (alg, key) { return hash(alg, key) } +exports.randomBytes = function(size, callback) { + if (callback && callback.call) { + try { + callback.call(this, undefined, new Buffer(rng(size))) + } catch (err) { callback(err) } + } else { + return new Buffer(rng(size)) + } +} + +function each(a, f) { + for(var i in a) + f(a[i], i) +} + +// the least I can do is make error messages for the rest of the node.js/crypto api. +each(['createCredentials' +, 'createCipher' +, 'createCipheriv' +, 'createDecipher' +, 'createDecipheriv' +, 'createSign' +, 'createVerify' +, 'createDiffieHellman' +, 'pbkdf2'], function (name) { + exports[name] = function () { + error('sorry,', name, 'is not implemented yet') } +}) + +},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,"buffer":1}],6:[function(require,module,exports){ +/* + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +var helpers = require('./helpers'); + +/* + * Perform a simple self-test to see if the VM is working + */ +function md5_vm_test() +{ + return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; +} + +/* + * Calculate the MD5 of an array of little-endian words, and a bit length + */ +function core_md5(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << ((len) % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + + a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); + d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); + c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); + b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); + a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); + d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); + c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); + b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); + a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); + d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); + c = md5_ff(c, d, a, b, x[i+10], 17, -42063); + b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); + a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); + d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); + c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); + b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); + + a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); + d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); + c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); + b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); + a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); + d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); + c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); + b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); + a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); + d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); + c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); + b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); + a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); + d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); + c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); + b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); + + a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); + d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); + c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); + b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); + a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); + d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); + c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); + b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); + a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); + d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); + c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); + b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); + a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); + d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); + c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); + b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); + + a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); + d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); + c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); + b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); + a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); + d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); + c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); + b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); + a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); + d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); + c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); + b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); + a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); + d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); + c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); + b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + } + return Array(a, b, c, d); + +} + +/* + * These functions implement the four basic operations the algorithm uses. + */ +function md5_cmn(q, a, b, x, s, t) +{ + return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); +} +function md5_ff(a, b, c, d, x, s, t) +{ + return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5_gg(a, b, c, d, x, s, t) +{ + return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5_hh(a, b, c, d, x, s, t) +{ + return md5_cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5_ii(a, b, c, d, x, s, t) +{ + return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function bit_rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function md5(buf) { + return helpers.hash(buf, core_md5, 16); +}; + +},{"./helpers":4}],7:[function(require,module,exports){ +// Original code adapted from Robert Kieffer. +// details at https://github.com/broofa/node-uuid +(function() { + var _global = this; - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } + var mathRNG, whatwgRNG; - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host) && (last === '.' || last === '..') || - last === ''); + // NOTE: Math.random() does not guarantee "cryptographic quality" + mathRNG = function(size) { + var bytes = new Array(size); + var r; - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last == '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; + for (var i = 0, r; i < size; i++) { + if ((i & 0x03) == 0) r = Math.random() * 0x100000000; + bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; } + + return bytes; } - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); + if (_global.crypto && crypto.getRandomValues) { + whatwgRNG = function(size) { + var bytes = new Uint8Array(size); + crypto.getRandomValues(bytes); + return bytes; } } - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } + module.exports = whatwgRNG || mathRNG; - if (hasTrailingSlash && (shims.substr(srcPath.join('/'), -1) !== '/')) { - srcPath.push(''); - } +}()) - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); +},{}],8:[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. + */ - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); +var helpers = require('./helpers'); + +/* + * Calculate the SHA-1 of an array of big-endian words, and a bit length + */ +function core_sha1(x, len) +{ + /* append padding */ + x[len >> 5] |= 0x80 << (24 - len % 32); + x[((len + 64 >> 9) << 4) + 15] = len; + + var w = Array(80); + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + var e = -1009589776; + + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + var olde = e; + + for(var j = 0; j < 80; j++) + { + if(j < 16) w[j] = x[i + j]; + else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); + var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), + safe_add(safe_add(e, w[j]), sha1_kt(j))); + e = d; + d = c; + c = rol(b, 30); + b = a; + a = t; } + + a = safe_add(a, olda); + b = safe_add(b, oldb); + c = safe_add(c, oldc); + d = safe_add(d, oldd); + e = safe_add(e, olde); } + return Array(a, b, c, d, e); - mustEndAbs = mustEndAbs || (result.host && srcPath.length); +} - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } +/* + * Perform the appropriate triplet combination function for the current + * iteration + */ +function sha1_ft(t, b, c, d) +{ + if(t < 20) return (b & c) | ((~b) & d); + if(t < 40) return b ^ c ^ d; + if(t < 60) return (b & c) | (b & d) | (c & d); + return b ^ c ^ d; +} - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } +/* + * Determine the appropriate additive constant for the current iteration + */ +function sha1_kt(t) +{ + return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : + (t < 60) ? -1894007588 : -899497514; +} - //to support request.http - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ +function safe_add(x, y) +{ + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* + * Bitwise rotate a 32-bit number to the left. + */ +function rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} + +module.exports = function sha1(buf) { + return helpers.hash(buf, core_sha1, 20, true); }; -Url.prototype.parseHost = function() { - var host = this.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); +},{"./helpers":4}],9:[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 helpers = require('./helpers'); + +var safe_add = function(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +}; + +var S = function(X, n) { + return (X >>> n) | (X << (32 - n)); +}; + +var R = function(X, n) { + return (X >>> n); +}; + +var Ch = function(x, y, z) { + return ((x & y) ^ ((~x) & z)); +}; + +var Maj = function(x, y, z) { + return ((x & y) ^ (x & z) ^ (y & z)); +}; + +var Sigma0256 = function(x) { + return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); +}; + +var Sigma1256 = function(x) { + return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); +}; + +var Gamma0256 = function(x) { + return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); +}; + +var Gamma1256 = function(x) { + return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); +}; + +var core_sha256 = function(m, l) { + var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,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); + var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19); + var W = new Array(64); + var a, b, c, d, e, f, g, h, i, j; + var T1, T2; + /* append padding */ + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >> 9) << 4) + 15] = l; + for (var i = 0; i < m.length; i += 16) { + a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7]; + for (var j = 0; j < 64; j++) { + if (j < 16) { + W[j] = m[j + i]; + } else { + W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]); + } + T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]); + T2 = safe_add(Sigma0256(a), Maj(a, b, c)); + h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2); } - host = host.substr(0, host.length - port.length); + HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]); + HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]); } - if (host) this.hostname = host; + return HASH; +}; + +module.exports = function sha256(buf) { + return helpers.hash(buf, core_sha256, 32, true); }; -},{"_shims":4,"querystring":13,"util":18}],18:[function(require,module,exports){ + +},{"./helpers":4}],10:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -4728,5715 +1857,5848 @@ Url.prototype.parseHost = function() { // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -var shims = require('_shims'); +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); } - return objects.join(' '); } - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + handler.apply(this, args); } - } - return str; -}; + } else if (isObject(handler)) { + len = arguments.length; + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] + return true; }; -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; +EventEmitter.prototype.addListener = function(type, listener) { + var m; + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + if (!this._events) + this._events = {}; - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; -function stylizeNoColor(str, styleType) { - return str; -} + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + var m; + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } -function arrayToHash(array) { - var hash = {}; + return this; +}; - shims.forEach(array, function(val, idx) { - hash[val] = true; - }); +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - return hash; -} +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + var fired = false; -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); } - return ret; } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - // Look up the keys of the object. - var keys = shims.keys(value); - var visibleKeys = arrayToHash(keys); + if (!this._events || !this._events[type]) + return this; - if (ctx.showHidden) { - keys = shims.getOwnPropertyNames(value); - } + list = this._events[type]; + length = list.length; + position = -1; - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } } - } - var base = '', array = false, braces = ['{', '}']; + if (position < 0) + return this; - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; + if (this._events.removeListener) + this.emit('removeListener', type, listener); } - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + return this; +}; - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + if (!this._events) + return this; - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; } - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; } - ctx.seen.push(value); + listeners = this._events[type]; - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + if (isFunction(listeners)) { + this.removeListener(type, listeners); } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); } + delete this._events[type]; - ctx.seen.pop(); + return this; +}; - return reduceToSingleString(output, base, braces); -} +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; +EventEmitter.listenerCount = function(emitter, type) { + var ret; + if (!emitter._events || !emitter._events[type]) + ret = 0; + else if (isFunction(emitter._events[type])) + ret = 1; + else + ret = emitter._events[type].length; + return ret; +}; -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; } +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; +function isUndefined(arg) { + return arg === void 0; } +},{}],11:[function(require,module,exports){ +var http = module.exports; +var EventEmitter = require('events').EventEmitter; +var Request = require('./lib/request'); +var url = require('url') -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); +http.request = function (params, cb) { + if (typeof params === 'string') { + params = url.parse(params) } - } - - shims.forEach(keys, function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); + if (!params) params = {}; + if (!params.host && !params.port) { + params.port = parseInt(window.location.port, 10); } - }); - return output; -} + if (!params.host && params.hostname) { + params.host = params.hostname; + } + + if (!params.scheme) params.scheme = window.location.protocol.split(':')[0]; + if (!params.host) { + params.host = window.location.hostname || window.location.host; + } + if (/:/.test(params.host)) { + if (!params.port) { + params.port = params.host.split(':')[1]; + } + params.host = params.host.split(':')[0]; + } + if (!params.port) params.port = params.scheme == 'https' ? 443 : 80; + + var req = new Request(new xhrHttp, params); + if (cb) req.on('response', cb); + return req; +}; +http.get = function (params, cb) { + params.method = 'GET'; + var req = http.request(params, cb); + req.end(); + return req; +}; -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = shims.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); +http.Agent = function () {}; +http.Agent.defaultMaxSockets = 4; + +var xhrHttp = (function () { + if (typeof window === 'undefined') { + throw new Error('no window object present'); } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); + else if (window.XMLHttpRequest) { + return window.XMLHttpRequest; } - } - - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (shims.indexOf(ctx.seen, desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); + else if (window.ActiveXObject) { + var axs = [ + 'Msxml2.XMLHTTP.6.0', + 'Msxml2.XMLHTTP.3.0', + 'Microsoft.XMLHTTP' + ]; + for (var i = 0; i < axs.length; i++) { + try { + var ax = new(window.ActiveXObject)(axs[i]); + return function () { + if (ax) { + var ax_ = ax; + ax = null; + return ax_; + } + else { + return new(window.ActiveXObject)(axs[i]); + } + }; + } + catch (e) {} } - } - } else { - str = ctx.stylize('[Circular]', 'special'); + throw new Error('ajax not supported in this browser') } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; + else { + throw new Error('ajax not supported in this browser'); } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); +})(); + +http.STATUS_CODES = { + 100 : 'Continue', + 101 : 'Switching Protocols', + 102 : 'Processing', // RFC 2518, obsoleted by RFC 4918 + 200 : 'OK', + 201 : 'Created', + 202 : 'Accepted', + 203 : 'Non-Authoritative Information', + 204 : 'No Content', + 205 : 'Reset Content', + 206 : 'Partial Content', + 207 : 'Multi-Status', // RFC 4918 + 300 : 'Multiple Choices', + 301 : 'Moved Permanently', + 302 : 'Moved Temporarily', + 303 : 'See Other', + 304 : 'Not Modified', + 305 : 'Use Proxy', + 307 : 'Temporary Redirect', + 400 : 'Bad Request', + 401 : 'Unauthorized', + 402 : 'Payment Required', + 403 : 'Forbidden', + 404 : 'Not Found', + 405 : 'Method Not Allowed', + 406 : 'Not Acceptable', + 407 : 'Proxy Authentication Required', + 408 : 'Request Time-out', + 409 : 'Conflict', + 410 : 'Gone', + 411 : 'Length Required', + 412 : 'Precondition Failed', + 413 : 'Request Entity Too Large', + 414 : 'Request-URI Too Large', + 415 : 'Unsupported Media Type', + 416 : 'Requested Range Not Satisfiable', + 417 : 'Expectation Failed', + 418 : 'I\'m a teapot', // RFC 2324 + 422 : 'Unprocessable Entity', // RFC 4918 + 423 : 'Locked', // RFC 4918 + 424 : 'Failed Dependency', // RFC 4918 + 425 : 'Unordered Collection', // RFC 4918 + 426 : 'Upgrade Required', // RFC 2817 + 428 : 'Precondition Required', // RFC 6585 + 429 : 'Too Many Requests', // RFC 6585 + 431 : 'Request Header Fields Too Large',// RFC 6585 + 500 : 'Internal Server Error', + 501 : 'Not Implemented', + 502 : 'Bad Gateway', + 503 : 'Service Unavailable', + 504 : 'Gateway Time-out', + 505 : 'HTTP Version Not Supported', + 506 : 'Variant Also Negotiates', // RFC 2295 + 507 : 'Insufficient Storage', // RFC 4918 + 509 : 'Bandwidth Limit Exceeded', + 510 : 'Not Extended', // RFC 2774 + 511 : 'Network Authentication Required' // RFC 6585 +}; +},{"./lib/request":12,"events":10,"url":30}],12:[function(require,module,exports){ +var Stream = require('stream'); +var Response = require('./response'); +var Base64 = require('Base64'); +var inherits = require('inherits'); + +var Request = module.exports = function (xhr, params) { + var self = this; + self.writable = true; + self.xhr = xhr; + self.body = []; + + self.uri = (params.scheme || 'http') + '://' + + params.host + + (params.port ? ':' + params.port : '') + + (params.path || '/') + ; + + if (typeof params.withCredentials === 'undefined') { + params.withCredentials = true; } - } - return name + ': ' + str; -} + try { xhr.withCredentials = params.withCredentials } + catch (e) {} + + xhr.open( + params.method || 'GET', + self.uri, + true + ); + self._headers = {}; + + if (params.headers) { + var keys = objectKeys(params.headers); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (!self.isSafeRequestHeader(key)) continue; + var value = params.headers[key]; + self.setHeader(key, value); + } + } + + if (params.auth) { + //basic auth + this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth)); + } -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = shims.reduce(output, function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); + var res = new Response; + res.on('close', function () { + self.emit('close'); + }); + + res.on('ready', function () { + self.emit('response', res); + }); + + xhr.onreadystatechange = function () { + // Fix for IE9 bug + // SCRIPT575: Could not complete the operation due to error c00c023f + // It happens when a request is aborted, calling the success callback anyway with readyState === 4 + if (xhr.__aborted) return; + res.handle(xhr); + }; +}; - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } +inherits(Request, Stream); - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} +Request.prototype.setHeader = function (key, value) { + this._headers[key.toLowerCase()] = value +}; +Request.prototype.getHeader = function (key) { + return this._headers[key.toLowerCase()] +}; -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return shims.isArray(ar); -} -exports.isArray = isArray; +Request.prototype.removeHeader = function (key) { + delete this._headers[key.toLowerCase()] +}; -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; +Request.prototype.write = function (s) { + this.body.push(s); +}; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; +Request.prototype.destroy = function (s) { + this.xhr.__aborted = true; + this.xhr.abort(); + this.emit('close'); +}; -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; +Request.prototype.end = function (s) { + if (s !== undefined) this.body.push(s); + + var keys = objectKeys(this._headers); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = this._headers[key]; + if (isArray(value)) { + for (var j = 0; j < value.length; j++) { + this.xhr.setRequestHeader(key, value[j]); + } + } + else this.xhr.setRequestHeader(key, value) + } -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; + if (this.body.length === 0) { + this.xhr.send(''); + } + else if (typeof this.body[0] === 'string') { + this.xhr.send(this.body.join('')); + } + else if (isArray(this.body[0])) { + var body = []; + for (var i = 0; i < this.body.length; i++) { + body.push.apply(body, this.body[i]); + } + this.xhr.send(body); + } + else if (/Array/.test(Object.prototype.toString.call(this.body[0]))) { + var len = 0; + for (var i = 0; i < this.body.length; i++) { + len += this.body[i].length; + } + var body = new(this.body[0].constructor)(len); + var k = 0; + + for (var i = 0; i < this.body.length; i++) { + var b = this.body[i]; + for (var j = 0; j < b.length; j++) { + body[k++] = b[j]; + } + } + this.xhr.send(body); + } + else { + var body = ''; + for (var i = 0; i < this.body.length; i++) { + body += this.body[i].toString(); + } + this.xhr.send(body); + } +}; -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; +// Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html +Request.unsafeHeaders = [ + "accept-charset", + "accept-encoding", + "access-control-request-headers", + "access-control-request-method", + "connection", + "content-length", + "cookie", + "cookie2", + "content-transfer-encoding", + "date", + "expect", + "host", + "keep-alive", + "origin", + "referer", + "te", + "trailer", + "transfer-encoding", + "upgrade", + "user-agent", + "via" +]; -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; +Request.prototype.isSafeRequestHeader = function (headerName) { + if (!headerName) return false; + return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1; +}; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; -function isObject(arg) { - return typeof arg === 'object' && arg; -} -exports.isObject = isObject; +var indexOf = function (xs, x) { + if (xs.indexOf) return xs.indexOf(x); + for (var i = 0; i < xs.length; i++) { + if (xs[i] === x) return i; + } + return -1; +}; -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; +},{"./response":13,"Base64":14,"inherits":16,"stream":23}],13:[function(require,module,exports){ +var Stream = require('stream'); +var util = require('util'); -function isError(e) { - return isObject(e) && objectToString(e) === '[object Error]'; -} -exports.isError = isError; +var Response = module.exports = function (res) { + this.offset = 0; + this.readable = true; +}; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; +util.inherits(Response, Stream); -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; +var capable = { + streaming : true, + status2 : true +}; -function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.binarySlice === 'function' - ; +function parseHeaders (res) { + var lines = res.getAllResponseHeaders().split(/\r?\n/); + var headers = {}; + for (var i = 0; i < lines.length; i++) { + var line = lines[i]; + if (line === '') continue; + + var m = line.match(/^([^:]+):\s*(.*)/); + if (m) { + var key = m[1].toLowerCase(), value = m[2]; + + if (headers[key] !== undefined) { + + if (isArray(headers[key])) { + headers[key].push(value); + } + else { + headers[key] = [ headers[key], value ]; + } + } + else { + headers[key] = value; + } + } + else { + headers[line] = true; + } + } + return headers; } -exports.isBuffer = isBuffer; -function objectToString(o) { - return Object.prototype.toString.call(o); +Response.prototype.getResponse = function (xhr) { + var respType = String(xhr.responseType).toLowerCase(); + if (respType === 'blob') return xhr.responseBlob || xhr.response; + if (respType === 'arraybuffer') return xhr.response; + return xhr.responseText; } +Response.prototype.getHeader = function (key) { + return this.headers[key.toLowerCase()]; +}; -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - +Response.prototype.handle = function (res) { + if (res.readyState === 2 && capable.status2) { + try { + this.statusCode = res.status; + this.headers = parseHeaders(res); + } + catch (err) { + capable.status2 = false; + } + + if (capable.status2) { + this.emit('ready'); + } + } + else if (capable.streaming && res.readyState === 3) { + try { + if (!this.statusCode) { + this.statusCode = res.status; + this.headers = parseHeaders(res); + this.emit('ready'); + } + } + catch (err) {} + + try { + this._emitData(res); + } + catch (err) { + capable.streaming = false; + } + } + else if (res.readyState === 4) { + if (!this.statusCode) { + this.statusCode = res.status; + this.emit('ready'); + } + this._emitData(res); + + if (res.error) { + this.emit('error', this.getResponse(res)); + } + else this.emit('end'); + + this.emit('close'); + } +}; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; +Response.prototype._emitData = function (res) { + var respBody = this.getResponse(res); + if (respBody.toString().match(/ArrayBuffer/)) { + this.emit('data', new Uint8Array(respBody, this.offset)); + this.offset = respBody.byteLength; + return; + } + if (respBody.length > this.offset) { + this.emit('data', respBody.slice(this.offset)); + this.offset = respBody.length; + } +}; -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; +},{"stream":23,"util":32}],14:[function(require,module,exports){ +;(function () { -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; + var object = typeof exports != 'undefined' ? exports : this; // #8: web workers + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + function InvalidCharacterError(message) { + this.message = message; + } + InvalidCharacterError.prototype = new Error; + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = function(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = shims.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true + // encoder + // [https://gist.github.com/999166] by [https://github.com/nignag] + object.btoa || ( + object.btoa = function (input) { + for ( + // initialize result and counter + var block, charCode, idx = 0, map = chars, output = ''; + // if the next input index does not exist: + // change the mapping table to "=" + // check if d has no fractional digits + input.charAt(idx | 0) || (map = '=', idx % 1); + // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 + output += map.charAt(63 & block >> 8 - idx % 1 * 8) + ) { + charCode = input.charCodeAt(idx += 3/4); + if (charCode > 0xFF) { + throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); + } + block = block << 8 | charCode; } + return output; }); -}; -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = shims.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; + // decoder + // [https://gist.github.com/1020396] by [https://github.com/atk] + object.atob || ( + object.atob = function (input) { + input = input.replace(/=+$/, ''); + if (input.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); + } + for ( + // initialize result and counters + var bc = 0, bs, buffer, idx = 0, output = ''; + // get next character + buffer = input.charAt(idx++); + // character found in table? initialize bit storage and add its ascii value; + ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, + // and if not first of each 4 characters, + // convert the first 8 bits to one ascii character + bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 + ) { + // try to find character in table (0-63, not found => -1) + buffer = chars.indexOf(buffer); + } + return output; + }); -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} +}()); -},{"_shims":4}],19:[function(require,module,exports){ -exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) { - var e, m, - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = isBE ? 0 : (nBytes - 1), - d = isBE ? 1 : -1, - s = buffer[offset + i]; +},{}],15:[function(require,module,exports){ +var http = require('http'); - i += d; +var https = module.exports; - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key]; +}; - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); +https.request = function (params, cb) { + if (!params) params = {}; + params.scheme = 'https'; + return http.request.call(this, params, cb); +} - 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; +},{"http":11}],16:[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 } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; +} -exports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) { - var e, m, c, - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = isBE ? (nBytes - 1) : 0, - d = isBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; +},{}],17:[function(require,module,exports){ +// shim for using process in browser - value = Math.abs(value); +var process = module.exports = {}; - 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; +process.nextTick = (function () { + var canSetImmediate = typeof window !== 'undefined' + && window.setImmediate; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; + + if (canSetImmediate) { + return function (f) { return window.setImmediate(f) }; } - 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; + if (canPost) { + var queue = []; + window.addEventListener('message', function (ev) { + var source = ev.source; + if ((source === window || source === null) && ev.data === 'process-tick') { + ev.stopPropagation(); + if (queue.length > 0) { + var fn = queue.shift(); + fn(); + } + } + }, true); + + return function nextTick(fn) { + queue.push(fn); + window.postMessage('process-tick', '*'); + }; } - } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + return function nextTick(fn) { + setTimeout(fn, 0); + }; +})(); - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; - buffer[offset + i - d] |= s * 128; -}; +function noop() {} -},{}],20:[function(require,module,exports){ -var assert; -exports.Buffer = Buffer; -exports.SlowBuffer = Buffer; -Buffer.poolSize = 8192; -exports.INSPECT_MAX_BYTES = 50; - -function stringtrim(str) { - if (str.trim) return str.trim(); - return str.replace(/^\s+|\s+$/g, ''); +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); } -function Buffer(subject, encoding, offset) { - if(!assert) assert= require('assert'); - if (!(this instanceof Buffer)) { - return new Buffer(subject, encoding, offset); - } - this.parent = this; - this.offset = 0; +// TODO(shtylman) +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; - // Work-around: node's base64 implementation - // allows for non-padded strings while base64-js - // does not.. - if (encoding == "base64" && typeof subject == "string") { - subject = stringtrim(subject); - while (subject.length % 4 != 0) { - subject = subject + "="; - } - } +},{}],18:[function(require,module,exports){ +(function (global){ +/*! http://mths.be/punycode v1.2.4 by @mathias */ +;(function(root) { - var type; + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports; + var freeModule = typeof module == 'object' && module && + module.exports == freeExports && module; + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + root = freeGlobal; + } - // Are we slicing? - if (typeof offset === 'number') { - this.length = coerce(encoding); - // slicing works, with limitations (no parent tracking/update) - // check https://github.com/toots/buffer-browserify/issues/19 - for (var i = 0; i < this.length; i++) { - this[i] = subject.get(i+offset); - } - } else { - // Find the length - switch (type = typeof subject) { - case 'number': - this.length = coerce(subject); - break; + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; - case 'string': - this.length = Buffer.byteLength(subject, encoding); - break; + /*--------------------------------------------------------------------------*/ - case 'object': // Assume object is an array - this.length = coerce(subject.length); - break; + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } - default: - throw new Error('First argument needs to be a number, ' + - 'array or string.'); - } + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + while (length--) { + array[length] = fn(array[length]); + } + return array; + } - // Treat array-ish objects as a byte array. - if (isArrayIsh(subject)) { - for (var i = 0; i < this.length; i++) { - if (subject instanceof Buffer) { - this[i] = subject.readUInt8(i); - } - else { - this[i] = subject[i]; - } - } - } else if (type == 'string') { - // We are a string - this.length = this.write(subject, 0, encoding); - } else if (type === 'number') { - for (var i = 0; i < this.length; i++) { - this[i] = 0; - } - } - } -} + /** + * A simple `Array#map`-like wrapper to work with domain name strings. + * @private + * @param {String} domain The domain name. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + return map(string.split(regexSeparators), fn).join('.'); + } -Buffer.prototype.get = function get(i) { - if (i < 0 || i >= this.length) throw new Error('oob'); - return this[i]; -}; + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } -Buffer.prototype.set = function set(i, v) { - if (i < 0 || i >= this.length) throw new Error('oob'); - return this[i] = v; -}; + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } -Buffer.byteLength = function (str, encoding) { - switch (encoding || "utf8") { - case 'hex': - return str.length / 2; + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } - case 'utf8': - case 'utf-8': - return utf8ToBytes(str).length; + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } - case 'ascii': - case 'binary': - return str.length; + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } - case 'base64': - return base64ToBytes(str).length; + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } - default: - throw new Error('Unknown encoding'); - } -}; + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } -Buffer.prototype.utf8Write = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length); -}; + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. -Buffer.prototype.asciiWrite = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length); -}; + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { -Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite; + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { -Buffer.prototype.base64Write = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length); -}; + if (index >= inputLength) { + error('invalid-input'); + } -Buffer.prototype.base64Slice = function (start, end) { - var bytes = Array.prototype.slice.apply(this, arguments) - return require("base64-js").fromByteArray(bytes); -}; + digit = basicToDigit(input.charCodeAt(index++)); -Buffer.prototype.utf8Slice = function () { - var bytes = Array.prototype.slice.apply(this, arguments); - var res = ""; - var tmp = ""; - var i = 0; - while (i < bytes.length) { - if (bytes[i] <= 0x7F) { - res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]); - tmp = ""; - } else - tmp += "%" + bytes[i].toString(16); + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } - i++; - } + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - return res + decodeUtf8Char(tmp); -} + if (digit < t) { + break; + } -Buffer.prototype.asciiSlice = function () { - var bytes = Array.prototype.slice.apply(this, arguments); - var ret = ""; - for (var i = 0; i < bytes.length; i++) - ret += String.fromCharCode(bytes[i]); - return ret; -} + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } -Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice; + w *= baseMinusT; -Buffer.prototype.inspect = function() { - var out = [], - len = this.length; - for (var i = 0; i < len; i++) { - out[i] = toHex(this[i]); - if (i == exports.INSPECT_MAX_BYTES) { - out[i + 1] = '...'; - break; - } - } - return ''; -}; + } + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); -Buffer.prototype.hexSlice = function(start, end) { - var len = this.length; + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; + n += floor(i / out); + i %= out; - var out = ''; - for (var i = start; i < end; i++) { - out += toHex(this[i]); - } - return out; -}; + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + } -Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - start = +start || 0; - if (typeof end == 'undefined') end = this.length; + return ucs2encode(output); + } - // Fastpath empty strings - if (+end == start) { - return ''; - } + /** + * Converts a string of Unicode symbols to a Punycode string of ASCII-only + * symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } - switch (encoding) { - case 'hex': - return this.hexSlice(start, end); + handledCPCount = basicLength = output.length; - case 'utf8': - case 'utf-8': - return this.utf8Slice(start, end); + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. - case 'ascii': - return this.asciiSlice(start, end); + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } - case 'binary': - return this.binarySlice(start, end); + // Main encoding loop: + while (handledCPCount < inputLength) { - case 'base64': - return this.base64Slice(start, end); + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } - case 'ucs2': - case 'ucs-2': - return this.ucs2Slice(start, end); + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } - default: - throw new Error('Unknown encoding'); - } -}; + delta += (m - n) * handledCPCountPlusOne; + n = m; + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; -Buffer.prototype.hexWrite = function(string, offset, length) { - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } - // must be an even number of digits - var strLen = string.length; - if (strLen % 2) { - throw new Error('Invalid hex string'); - } - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; i++) { - var byte = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(byte)) throw new Error('Invalid hex string'); - this[offset + i] = byte; - } - Buffer._charsWritten = i * 2; - return i; -}; + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + ++delta; + ++n; -Buffer.prototype.write = function(string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } + } + return output.join(''); + } - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - encoding = String(encoding || 'utf8').toLowerCase(); + /** + * Converts a Punycode string representing a domain name to Unicode. Only the + * Punycoded parts of the domain name will be converted, i.e. it doesn't + * matter if you call it on a string that has already been converted to + * Unicode. + * @memberOf punycode + * @param {String} domain The Punycode domain name to convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(domain) { + return mapDomain(domain, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } - switch (encoding) { - case 'hex': - return this.hexWrite(string, offset, length); + /** + * Converts a Unicode string representing a domain name to Punycode. Only the + * non-ASCII parts of the domain name will be converted, i.e. it doesn't + * matter if you call it with a domain that's already in ASCII. + * @memberOf punycode + * @param {String} domain The domain name to convert, as a Unicode string. + * @returns {String} The Punycode representation of the given domain name. + */ + function toASCII(domain) { + return mapDomain(domain, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } - case 'utf8': - case 'utf-8': - return this.utf8Write(string, offset, length); + /*--------------------------------------------------------------------------*/ - case 'ascii': - return this.asciiWrite(string, offset, length); + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.2.4', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; - case 'binary': - return this.binaryWrite(string, offset, length); + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } - case 'base64': - return this.base64Write(string, offset, length); +}(this)); - case 'ucs2': - case 'ucs-2': - return this.ucs2Write(string, offset, length); +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],19:[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. - default: - throw new Error('Unknown encoding'); - } -}; +'use strict'; -// slice(start, end) -function clamp(index, len, defaultValue) { - if (typeof index !== 'number') return defaultValue; - index = ~~index; // Coerce to integer. - if (index >= len) return len; - if (index >= 0) return index; - index += len; - if (index >= 0) return index; - return 0; +// If obj.hasOwnProperty has been overridden, then calling +// obj.hasOwnProperty(prop) will break. +// See: https://github.com/joyent/node/issues/1707 +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); } -Buffer.prototype.slice = function(start, end) { - var len = this.length; - start = clamp(start, len, 0); - end = clamp(end, len, len); - return new Buffer(this, end - start, +start); -}; +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function(target, target_start, start, end) { - var source = this; - start || (start = 0); - if (end === undefined || isNaN(end)) { - end = this.length; + if (typeof qs !== 'string' || qs.length === 0) { + return obj; } - target_start || (target_start = 0); - - if (end < start) throw new Error('sourceEnd < sourceStart'); - // Copy 0 bytes; we're done - if (end === start) return 0; - if (target.length == 0 || source.length == 0) return 0; + var regexp = /\+/g; + qs = qs.split(sep); - if (target_start < 0 || target_start >= target.length) { - throw new Error('targetStart out of bounds'); + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; } - if (start < 0 || start >= source.length) { - throw new Error('sourceStart out of bounds'); + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; } - if (end < 0 || end > source.length) { - throw new Error('sourceEnd out of bounds'); - } + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; - // Are we oob? - if (end > this.length) { - end = this.length; - } + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } - if (target.length - target_start < end - start) { - end = target.length - target_start + start; - } + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); - var temp = []; - for (var i=start; i= this.length) { - throw new Error('start out of bounds'); - } + case 'boolean': + return v ? 'true' : 'false'; - if (end < 0 || end > this.length) { - throw new Error('end out of bounds'); - } + case 'number': + return isFinite(v) ? v : ''; - for (var i = start; i < end; i++) { - this[i] = value; + default: + return ''; } -} - -// Static methods -Buffer.isBuffer = function isBuffer(b) { - return b instanceof Buffer || b instanceof Buffer; }; -Buffer.concat = function (list, totalLength) { - if (!isArray(list)) { - throw new Error("Usage: Buffer.concat(list, [totalLength])\n \ - list should be an Array."); +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; } - if (list.length === 0) { - return new Buffer(0); - } else if (list.length === 1) { - return list[0]; - } + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); - if (typeof totalLength !== 'number') { - totalLength = 0; - for (var i = 0; i < list.length; i++) { - var buf = list[i]; - totalLength += buf.length; - } } - var buffer = new Buffer(totalLength); - var pos = 0; - for (var i = 0; i < list.length; i++) { - var buf = list[i]; - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer; + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); }; -Buffer.isEncoding = function(encoding) { - switch ((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; - } +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; }; -// helpers - -function coerce(length) { - // Coerce length to a number (possibly NaN), round up - // in case it's fractional (e.g. 123.456) then do a - // double negate to coerce a NaN to 0. Easy, right? - length = ~~Math.ceil(+length); - return length < 0 ? 0 : length; +function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; } -function isArray(subject) { - return (Array.isArray || - function(subject){ - return {}.toString.apply(subject) == '[object Array]' - }) - (subject) -} +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; +}; -function isArrayIsh(subject) { - return isArray(subject) || Buffer.isBuffer(subject) || - subject && typeof subject === 'object' && - typeof subject.length === 'number'; -} +},{}],21:[function(require,module,exports){ +'use strict'; -function toHex(n) { - if (n < 16) return '0' + n.toString(16); - return n.toString(16); -} +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); -function utf8ToBytes(str) { - var byteArray = []; - for (var i = 0; i < str.length; i++) - if (str.charCodeAt(i) <= 0x7F) - byteArray.push(str.charCodeAt(i)); - else { - var h = encodeURIComponent(str.charAt(i)).substr(1).split('%'); - for (var j = 0; j < h.length; j++) - byteArray.push(parseInt(h[j], 16)); - } +},{"./decode":19,"./encode":20}],22:[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. - return byteArray; -} +// 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. -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 ); +module.exports = Duplex; +var inherits = require('inherits'); +var setImmediate = require('process/browser.js').nextTick; +var Readable = require('./readable.js'); +var Writable = require('./writable.js'); - return byteArray; -} +inherits(Duplex, Readable); -function base64ToBytes(str) { - return require("base64-js").toByteArray(str); -} +Duplex.prototype.write = Writable.prototype.write; +Duplex.prototype.end = Writable.prototype.end; +Duplex.prototype._write = Writable.prototype._write; -function blitBuffer(src, dst, offset, length) { - var pos, i = 0; - while (i < length) { - if ((i+offset >= dst.length) || (i >= src.length)) - break; +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); - dst[i + offset] = src[i]; - i++; - } - return i; -} + Readable.call(this, options); + Writable.call(this, options); -function decodeUtf8Char(str) { - try { - return decodeURIComponent(str); - } catch (err) { - return String.fromCharCode(0xFFFD); // UTF 8 invalid char - } -} + if (options && options.readable === false) + this.readable = false; -// read/write bit-twiddling + if (options && options.writable === false) + this.writable = false; -Buffer.prototype.readUInt8 = function(offset, noAssert) { - var buffer = this; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; - if (!noAssert) { - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + this.once('end', onend); +} - assert.ok(offset < buffer.length, - 'Trying to read beyond buffer length'); - } +// 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; - if (offset >= buffer.length) return; + // no more data can be written. + // But allow more writes to happen in this tick. + var self = this; + setImmediate(function () { + self.end(); + }); +} - return buffer[offset]; -}; +},{"./readable.js":26,"./writable.js":28,"inherits":16,"process/browser.js":24}],23:[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. -function readUInt16(buffer, offset, isBigEndian, noAssert) { - var val = 0; +module.exports = Stream; +var EE = require('events').EventEmitter; +var inherits = require('inherits'); - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); +inherits(Stream, EE); +Stream.Readable = require('./readable.js'); +Stream.Writable = require('./writable.js'); +Stream.Duplex = require('./duplex.js'); +Stream.Transform = require('./transform.js'); +Stream.PassThrough = require('./passthrough.js'); - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; - assert.ok(offset + 1 < buffer.length, - 'Trying to read beyond buffer length'); - } - if (offset >= buffer.length) return 0; - if (isBigEndian) { - val = buffer[offset] << 8; - if (offset + 1 < buffer.length) { - val |= buffer[offset + 1]; - } - } else { - val = buffer[offset]; - if (offset + 1 < buffer.length) { - val |= buffer[offset + 1] << 8; - } - } +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. - return val; +function Stream() { + EE.call(this); } -Buffer.prototype.readUInt16LE = function(offset, noAssert) { - return readUInt16(this, offset, false, noAssert); -}; - -Buffer.prototype.readUInt16BE = function(offset, noAssert) { - return readUInt16(this, offset, true, noAssert); -}; - -function readUInt32(buffer, offset, isBigEndian, noAssert) { - var val = 0; - - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); +Stream.prototype.pipe = function(dest, options) { + var source = this; - assert.ok(offset + 3 < buffer.length, - 'Trying to read beyond buffer length'); + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } } - if (offset >= buffer.length) return 0; + source.on('data', ondata); - if (isBigEndian) { - if (offset + 1 < buffer.length) - val = buffer[offset + 1] << 16; - if (offset + 2 < buffer.length) - val |= buffer[offset + 2] << 8; - if (offset + 3 < buffer.length) - val |= buffer[offset + 3]; - val = val + (buffer[offset] << 24 >>> 0); - } else { - if (offset + 2 < buffer.length) - val = buffer[offset + 2] << 16; - if (offset + 1 < buffer.length) - val |= buffer[offset + 1] << 8; - val |= buffer[offset]; - if (offset + 3 < buffer.length) - val = val + (buffer[offset + 3] << 24 >>> 0); + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } } - return val; -} + dest.on('drain', ondrain); -Buffer.prototype.readUInt32LE = function(offset, noAssert) { - return readUInt32(this, offset, false, noAssert); -}; + // 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); + } -Buffer.prototype.readUInt32BE = function(offset, noAssert) { - return readUInt32(this, offset, true, noAssert); -}; + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + dest.end(); + } -/* - * Signed integer types, yay team! A reminder on how two's complement actually - * works. The first bit is the signed bit, i.e. tells us whether or not the - * number should be positive or negative. If the two's complement value is - * positive, then we're done, as it's equivalent to the unsigned representation. - * - * Now if the number is positive, you're pretty much done, you can just leverage - * the unsigned translations and return those. Unfortunately, negative numbers - * aren't quite that straightforward. - * - * At first glance, one might be inclined to use the traditional formula to - * translate binary numbers between the positive and negative values in two's - * complement. (Though it doesn't quite work for the most negative value) - * Mainly: - * - invert all the bits - * - add one to the result - * - * Of course, this doesn't quite work in Javascript. Take for example the value - * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of - * course, Javascript will do the following: - * - * > ~0xff80 - * -65409 - * - * Whoh there, Javascript, that's not quite right. But wait, according to - * Javascript that's perfectly correct. When Javascript ends up seeing the - * constant 0xff80, it has no notion that it is actually a signed number. It - * assumes that we've input the unsigned value 0xff80. Thus, when it does the - * binary negation, it casts it into a signed value, (positive 0xff80). Then - * when you perform binary negation on that, it turns it into a negative number. - * - * Instead, we're going to have to use the following general formula, that works - * in a rather Javascript friendly way. I'm glad we don't support this kind of - * weird numbering scheme in the kernel. - * - * (BIT-MAX - (unsigned)val + 1) * -1 - * - * The astute observer, may think that this doesn't make sense for 8-bit numbers - * (really it isn't necessary for them). However, when you get 16-bit numbers, - * you do. Let's go back to our prior example and see how this will look: - * - * (0xffff - 0xff80 + 1) * -1 - * (0x007f + 1) * -1 - * (0x0080) * -1 - */ -Buffer.prototype.readInt8 = function(offset, noAssert) { - var buffer = this; - var neg; - if (!noAssert) { - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + function onclose() { + if (didOnEnd) return; + didOnEnd = true; - assert.ok(offset < buffer.length, - 'Trying to read beyond buffer length'); + if (typeof dest.destroy === 'function') dest.destroy(); } - if (offset >= buffer.length) return; - - neg = buffer[offset] & 0x80; - if (!neg) { - return (buffer[offset]); + // 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. + } } - return ((0xff - buffer[offset] + 1) * -1); -}; + source.on('error', onerror); + dest.on('error', onerror); -function readInt16(buffer, offset, isBigEndian, noAssert) { - var neg, val; + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + source.removeListener('end', onend); + source.removeListener('close', onclose); - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + source.removeListener('error', onerror); + dest.removeListener('error', onerror); - assert.ok(offset + 1 < buffer.length, - 'Trying to read beyond buffer length'); - } + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); - val = readUInt16(buffer, offset, isBigEndian, noAssert); - neg = val & 0x8000; - if (!neg) { - return val; + dest.removeListener('close', cleanup); } - return (0xffff - val + 1) * -1; -} - -Buffer.prototype.readInt16LE = function(offset, noAssert) { - return readInt16(this, offset, false, noAssert); -}; + source.on('end', cleanup); + source.on('close', cleanup); -Buffer.prototype.readInt16BE = function(offset, noAssert) { - return readInt16(this, offset, true, noAssert); -}; + dest.on('close', cleanup); -function readInt32(buffer, offset, isBigEndian, noAssert) { - var neg, val; + dest.emit('pipe', source); - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); +},{"./duplex.js":22,"./passthrough.js":25,"./readable.js":26,"./transform.js":27,"./writable.js":28,"events":10,"inherits":16}],24:[function(require,module,exports){ +// shim for using process in browser - assert.ok(offset + 3 < buffer.length, - 'Trying to read beyond buffer length'); - } +var process = module.exports = {}; - val = readUInt32(buffer, offset, isBigEndian, noAssert); - neg = val & 0x80000000; - if (!neg) { - return (val); - } +process.nextTick = (function () { + var canSetImmediate = typeof window !== 'undefined' + && window.setImmediate; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; - return (0xffffffff - val + 1) * -1; -} + if (canSetImmediate) { + return function (f) { return window.setImmediate(f) }; + } -Buffer.prototype.readInt32LE = function(offset, noAssert) { - return readInt32(this, offset, false, noAssert); -}; + if (canPost) { + var queue = []; + window.addEventListener('message', function (ev) { + var source = ev.source; + if ((source === window || source === null) && ev.data === 'process-tick') { + ev.stopPropagation(); + if (queue.length > 0) { + var fn = queue.shift(); + fn(); + } + } + }, true); -Buffer.prototype.readInt32BE = function(offset, noAssert) { - return readInt32(this, offset, true, noAssert); -}; + return function nextTick(fn) { + queue.push(fn); + window.postMessage('process-tick', '*'); + }; + } -function readFloat(buffer, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + return function nextTick(fn) { + setTimeout(fn, 0); + }; +})(); - assert.ok(offset + 3 < buffer.length, - 'Trying to read beyond buffer length'); - } +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; - return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, - 23, 4); +process.binding = function (name) { + throw new Error('process.binding is not supported'); } -Buffer.prototype.readFloatLE = function(offset, noAssert) { - return readFloat(this, offset, false, noAssert); +// TODO(shtylman) +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); }; -Buffer.prototype.readFloatBE = function(offset, noAssert) { - return readFloat(this, offset, true, noAssert); -}; +},{}],25:[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. -function readDouble(buffer, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. - assert.ok(offset + 7 < buffer.length, - 'Trying to read beyond buffer length'); - } +module.exports = PassThrough; + +var Transform = require('./transform.js'); +var inherits = require('inherits'); +inherits(PassThrough, Transform); - return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, - 52, 8); +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); } -Buffer.prototype.readDoubleLE = function(offset, noAssert) { - return readDouble(this, offset, false, noAssert); +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); }; -Buffer.prototype.readDoubleBE = function(offset, noAssert) { - return readDouble(this, offset, true, noAssert); -}; +},{"./transform.js":27,"inherits":16}],26:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +module.exports = Readable; +Readable.ReadableState = ReadableState; -/* - * We have to make sure that the value is a valid integer. This means that it is - * non-negative. It has no fractional component and that it does not exceed the - * maximum allowed value. - * - * value The number to check for validity - * - * max The maximum value - */ -function verifuint(value, max) { - assert.ok(typeof (value) == 'number', - 'cannot write a non-number as a number'); +var EE = require('events').EventEmitter; +var Stream = require('./index.js'); +var Buffer = require('buffer').Buffer; +var setImmediate = require('process/browser.js').nextTick; +var StringDecoder; - assert.ok(value >= 0, - 'specified a negative value for writing an unsigned value'); +var inherits = require('inherits'); +inherits(Readable, Stream); - assert.ok(value <= max, 'value is larger than maximum value for type'); +function ReadableState(options, stream) { + options = options || {}; - assert.ok(Math.floor(value) === value, 'value has a fractional component'); -} + // 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; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; -Buffer.prototype.writeUInt8 = function(value, offset, noAssert) { - var buffer = this; + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; - assert.ok(offset < buffer.length, - 'trying to write beyond buffer length'); + // 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, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - verifuint(value, 0xff); - } + // 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; - if (offset < buffer.length) { - buffer[offset] = value; - } -}; -function writeUInt16(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); + // 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; - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + // 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'; - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - assert.ok(offset + 1 < buffer.length, - 'trying to write beyond buffer length'); + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - verifuint(value, 0xffff); - } + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - for (var i = 0; i < Math.min(buffer.length - offset, 2); i++) { - buffer[offset + i] = - (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>> - (isBigEndian ? 1 - i : i) * 8; + 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; } - } -Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) { - writeUInt16(this, value, offset, false, noAssert); -}; - -Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) { - writeUInt16(this, value, offset, true, noAssert); -}; - -function writeUInt32(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); +function Readable(options) { + if (!(this instanceof Readable)) + return new Readable(options); - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + this._readableState = new ReadableState(options, this); - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + // legacy + this.readable = true; - assert.ok(offset + 3 < buffer.length, - 'trying to write beyond buffer length'); + Stream.call(this); +} - verifuint(value, 0xffffffff); - } +// 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; - for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) { - buffer[offset + i] = - (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff; + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } } -} -Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) { - writeUInt32(this, value, offset, false, noAssert); + return readableAddChunk(this, state, chunk, encoding, false); }; -Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) { - writeUInt32(this, value, offset, true, noAssert); +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); }; +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); -/* - * We now move onto our friends in the signed number category. Unlike unsigned - * numbers, we're going to have to worry a bit more about how we put values into - * arrays. Since we are only worrying about signed 32-bit values, we're in - * slightly better shape. Unfortunately, we really can't do our favorite binary - * & in this system. It really seems to do the wrong thing. For example: - * - * > -32 & 0xff - * 224 - * - * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of - * this aren't treated as a signed number. Ultimately a bad thing. - * - * What we're going to want to do is basically create the unsigned equivalent of - * our representation and pass that off to the wuint* functions. To do that - * we're going to do the following: - * - * - if the value is positive - * we can pass it directly off to the equivalent wuint - * - if the value is negative - * we do the following computation: - * mb + val + 1, where - * mb is the maximum unsigned value in that byte size - * val is the Javascript negative integer - * - * - * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If - * you do out the computations: - * - * 0xffff - 128 + 1 - * 0xffff - 127 - * 0xff80 - * - * You can then encode this value as the signed version. This is really rather - * hacky, but it should work and get the job done which is our goal here. - */ - -/* - * A series of checks to make sure we actually have a signed 32-bit number - */ -function verifsint(value, max, min) { - assert.ok(typeof (value) == 'number', - 'cannot write a non-number as a number'); + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } - assert.ok(value <= max, 'value larger than maximum allowed value'); + if (state.needReadable) + emitReadable(stream); - assert.ok(value >= min, 'value smaller than minimum allowed value'); + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } - assert.ok(Math.floor(value) === value, 'value has a fractional component'); + return needMoreData(state); } -function verifIEEE754(value, max, min) { - assert.ok(typeof (value) == 'number', - 'cannot write a non-number as a number'); - assert.ok(value <= max, 'value larger than maximum allowed value'); - assert.ok(value >= min, 'value smaller than minimum allowed value'); +// 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); } -Buffer.prototype.writeInt8 = function(value, offset, noAssert) { - var buffer = this; +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; +}; - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); +// Don't raise the hwm > 128MB +var MAX_HWM = 0x800000; +function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; +} - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; - assert.ok(offset < buffer.length, - 'Trying to write beyond buffer length'); + if (state.objectMode) + return n === 0 ? 0 : 1; - verifsint(value, 0x7f, -0x80); + if (isNaN(n) || n === null) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; } - if (value >= 0) { - buffer.writeUInt8(value, offset, noAssert); - } else { - buffer.writeUInt8(0xff + value + 1, offset, noAssert); - } -}; + if (n <= 0) + return 0; -function writeInt16(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + return n; +} - assert.ok(offset + 1 < buffer.length, - 'Trying to write beyond buffer length'); +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; - verifsint(value, 0x7fff, -0x8000); - } + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; - if (value >= 0) { - writeUInt16(buffer, value, offset, isBigEndian, noAssert); - } else { - writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert); + // 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)) { + emitReadable(this); + return null; } -} -Buffer.prototype.writeInt16LE = function(value, offset, noAssert) { - writeInt16(this, value, offset, false, noAssert); -}; + n = howMuchToRead(n, state); -Buffer.prototype.writeInt16BE = function(value, offset, noAssert) { - writeInt16(this, value, offset, true, noAssert); -}; + // 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; + } -function writeInt32(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); + // 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. - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; - assert.ok(offset + 3 < buffer.length, - 'Trying to write beyond buffer length'); + // 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; - verifsint(value, 0x7fffffff, -0x80000000); + if (doRead) { + 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 (value >= 0) { - writeUInt32(buffer, value, offset, isBigEndian, noAssert); - } else { - writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert); + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !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; } -} -Buffer.prototype.writeInt32LE = function(value, offset, noAssert) { - writeInt32(this, value, offset, false, noAssert); -}; + state.length -= n; -Buffer.prototype.writeInt32BE = function(value, offset, noAssert) { - writeInt32(this, value, offset, true, noAssert); -}; + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; -function writeFloat(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + return ret; +}; - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode && + !er) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} - assert.ok(offset + 3 < buffer.length, - 'Trying to write beyond buffer length'); - verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38); +function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } } + state.ended = true; - require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, - 23, 4); + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); } -Buffer.prototype.writeFloatLE = function(value, offset, noAssert) { - writeFloat(this, value, offset, false, noAssert); -}; - -Buffer.prototype.writeFloatBE = function(value, offset, noAssert) { - writeFloat(this, value, offset, true, noAssert); -}; - -function writeDouble(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); +// 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) + return; - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + state.emittedReadable = true; + if (state.sync) + setImmediate(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); +} - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); +function emitReadable_(stream) { + stream.emit('readable'); +} - assert.ok(offset + 7 < buffer.length, - 'Trying to write beyond buffer length'); - verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308); +// 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; + setImmediate(function() { + maybeReadMore_(stream, state); + }); } - - require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, - 52, 8); } -Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) { - writeDouble(this, value, offset, false, noAssert); -}; +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; +} -Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) { - writeDouble(this, value, offset, true, noAssert); +// 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('not implemented')); }; -},{"./buffer_ieee754":19,"assert":10,"base64-js":21}],21:[function(require,module,exports){ -(function (exports) { - 'use strict'; - - var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - - function b64ToByteArray(b64) { - var i, j, l, tmp, placeHolders, arr; - - if (b64.length % 4 > 0) { - throw 'Invalid string. Length must be a multiple of 4'; - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64.indexOf('='); - placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0; - - // base64 is 4/3 + up to two characters of the original data - arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]); - arr.push((tmp & 0xFF0000) >> 16); - arr.push((tmp & 0xFF00) >> 8); - arr.push(tmp & 0xFF); - } - - if (placeHolders === 2) { - tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4); - arr.push(tmp & 0xFF); - } else if (placeHolders === 1) { - tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2); - arr.push((tmp >> 8) & 0xFF); - arr.push(tmp & 0xFF); - } +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; - return arr; - } + 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; - function uint8ToBase64(uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; - }; + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + setImmediate(endFn); + else + src.once('end', endFn); - // go through the array every three bytes, we'll deal with trailing stuff later - for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output += tripletToBase64(temp); - } + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1]; - output += lookup[temp >> 2]; - output += lookup[(temp << 4) & 0x3F]; - output += '=='; - break; - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]); - output += lookup[temp >> 10]; - output += lookup[(temp >> 4) & 0x3F]; - output += lookup[(temp << 2) & 0x3F]; - output += '='; - break; - } + function onend() { + dest.end(); + } - return output; - } + // 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); - module.exports.toByteArray = b64ToByteArray; - module.exports.fromByteArray = uint8ToBase64; -}()); + function 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', cleanup); -},{}],22:[function(require,module,exports){ -var Buffer = require('buffer').Buffer; -var intSize = 4; -var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); -var chrsz = 8; + // 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 (!dest._writableState || dest._writableState.needDrain) + ondrain(); + } -function toArray(buf, bigEndian) { - if ((buf.length % intSize) !== 0) { - var len = buf.length + (intSize - (buf.length % intSize)); - buf = Buffer.concat([buf, zeroBuffer], len); + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + // check for listeners before emit removes one-time listeners. + var errListeners = EE.listenerCount(dest, 'error'); + function onerror(er) { + unpipe(); + if (errListeners === 0 && EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); } + dest.once('error', onerror); - var arr = []; - var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; - for (var i = 0; i < buf.length; i += intSize) { - arr.push(fn.call(buf, i)); + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } - return arr; -} + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); -function toBuffer(arr, size, bigEndian) { - var buf = new Buffer(size); - var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE; - for (var i = 0; i < arr.length; i++) { - fn.call(buf, arr[i], i * 4, true); + function unpipe() { + src.unpipe(dest); } - return buf; -} -function hash(buf, fn, hashSize, bigEndian) { - if (!Buffer.isBuffer(buf)) buf = new Buffer(buf); - var arr = fn(toArray(buf, bigEndian), buf.length * chrsz); - return toBuffer(arr, hashSize, bigEndian); -} + // tell the dest that it's being piped to + dest.emit('pipe', src); -module.exports = { hash: hash }; + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); -},{"buffer":20}],23:[function(require,module,exports){ -var Buffer = require('buffer').Buffer -var sha = require('./sha') -var sha256 = require('./sha256') -var rng = require('./rng') -var md5 = require('./md5') + state.flowing = true; + setImmediate(function() { + flow(src); + }); + } -var algorithms = { - sha1: sha, - sha256: sha256, - md5: md5 + return dest; +}; + +function pipeOnDrain(src) { + return function() { + var dest = this; + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; } -var blocksize = 64 -var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0) -function hmac(fn, key, data) { - if(!Buffer.isBuffer(key)) key = new Buffer(key) - if(!Buffer.isBuffer(data)) data = new Buffer(data) +function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; - if(key.length > blocksize) { - key = fn(key) - } else if(key.length < blocksize) { - key = Buffer.concat([key, zeroBuffer], blocksize) + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } } - var ipad = new Buffer(blocksize), opad = new Buffer(blocksize) - for(var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C + while (state.pipesCount && null !== (chunk = src.read())) { + + if (state.pipesCount === 1) + write(state.pipes, 0, null); + else + forEach(state.pipes, write); + + src.emit('data', chunk); + + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; } - var hash = fn(Buffer.concat([ipad, data])) - return fn(Buffer.concat([opad, hash])) -} + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; -function hash(alg, key) { - alg = alg || 'sha1' - var fn = algorithms[alg] - var bufs = [] - var length = 0 - if(!fn) error('algorithm:', alg, 'is not yet supported') - return { - update: function (data) { - if(!Buffer.isBuffer(data)) data = new Buffer(data) - - bufs.push(data) - length += data.length - return this - }, - digest: function (enc) { - var buf = Buffer.concat(bufs) - var r = key ? hmac(fn, key, buf) : fn(buf) - bufs = null - return enc ? r.toString(enc) : r - } + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; } -} -function error () { - var m = [].slice.call(arguments).join(' ') - throw new Error([ - m, - 'we accept pull requests', - 'http://github.com/dominictarr/crypto-browserify' - ].join('\n')) + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; } -exports.createHash = function (alg) { return hash(alg) } -exports.createHmac = function (alg, key) { return hash(alg, key) } -exports.randomBytes = function(size, callback) { - if (callback && callback.call) { - try { - callback.call(this, undefined, new Buffer(rng(size))) - } catch (err) { callback(err) } - } else { - return new Buffer(rng(size)) +function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); } } -function each(a, f) { - for(var i in a) - f(a[i], i) -} -// the least I can do is make error messages for the rest of the node.js/crypto api. -each(['createCredentials' -, 'createCipher' -, 'createCipheriv' -, 'createDecipher' -, 'createDecipheriv' -, 'createSign' -, 'createVerify' -, 'createDiffieHellman' -, 'pbkdf2'], function (name) { - exports[name] = function () { - error('sorry,', name, 'is not implemented yet') - } -}) +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; -},{"./md5":24,"./rng":25,"./sha":26,"./sha256":27,"buffer":20}],24:[function(require,module,exports){ -/* - * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message - * Digest Algorithm, as defined in RFC 1321. - * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for more info. - */ - -var helpers = require('./helpers'); - -/* - * Perform a simple self-test to see if the VM is working - */ -function md5_vm_test() -{ - return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; -} - -/* - * Calculate the MD5 of an array of little-endian words, and a bit length - */ -function core_md5(x, len) -{ - /* append padding */ - x[len >> 5] |= 0x80 << ((len) % 32); - x[(((len + 64) >>> 9) << 4) + 14] = len; - - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for(var i = 0; i < x.length; i += 16) - { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - - a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); - d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); - c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); - b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); - a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); - d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); - c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); - b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); - a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); - d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); - c = md5_ff(c, d, a, b, x[i+10], 17, -42063); - b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); - a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); - d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); - c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); - b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); - - a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); - d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); - c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); - b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); - a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); - d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); - c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); - b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); - a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); - d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); - c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); - b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); - a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); - d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); - c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); - b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); - - a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); - d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); - c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); - b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); - a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); - d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); - c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); - b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); - a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); - d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); - c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); - b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); - a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); - d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); - c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); - b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); - - a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); - d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); - c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); - b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); - a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); - d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); - c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); - b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); - a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); - d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); - c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); - b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); - a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); - d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); - c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); - b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); - - a = safe_add(a, olda); - b = safe_add(b, oldb); - c = safe_add(c, oldc); - d = safe_add(d, oldd); - } - return Array(a, b, c, d); - -} - -/* - * These functions implement the four basic operations the algorithm uses. - */ -function md5_cmn(q, a, b, x, s, t) -{ - return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); -} -function md5_ff(a, b, c, d, x, s, t) -{ - return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); -} -function md5_gg(a, b, c, d, x, s, t) -{ - return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); -} -function md5_hh(a, b, c, d, x, s, t) -{ - return md5_cmn(b ^ c ^ d, a, b, x, s, t); -} -function md5_ii(a, b, c, d, x, s, t) -{ - return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); -} - -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ -function safe_add(x, y) -{ - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); -} - -/* - * Bitwise rotate a 32-bit number to the left. - */ -function bit_rol(num, cnt) -{ - return (num << cnt) | (num >>> (32 - cnt)); -} - -module.exports = function md5(buf) { - return helpers.hash(buf, core_md5, 16); -}; + // 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; -},{"./helpers":22}],25:[function(require,module,exports){ -// Original code adapted from Robert Kieffer. -// details at https://github.com/broofa/node-uuid -(function() { - var _global = this; + if (!dest) + dest = state.pipes; - var mathRNG, whatwgRNG; + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } - // NOTE: Math.random() does not guarantee "cryptographic quality" - mathRNG = function(size) { - var bytes = new Array(size); - var r; + // slow case. multiple pipe destinations. - for (var i = 0, r; i < size; i++) { - if ((i & 0x03) == 0) r = Math.random() * 0x100000000; - bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; - } + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; - return bytes; + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; } - if (_global.crypto && crypto.getRandomValues) { - whatwgRNG = function(size) { - var bytes = new Uint8Array(size); - crypto.getRandomValues(bytes); - return bytes; + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + 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' && !this._readableState.flowing) + emitDataEvents(this); + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this, state); + } } } - module.exports = whatwgRNG || mathRNG; + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; -}()) +// 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() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); +}; -},{}],26:[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. - */ +Readable.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); +}; -var helpers = require('./helpers'); +function emitDataEvents(stream, startPaused) { + var state = stream._readableState; -/* - * Calculate the SHA-1 of an array of big-endian words, and a bit length - */ -function core_sha1(x, len) -{ - /* append padding */ - x[len >> 5] |= 0x80 << (24 - len % 32); - x[((len + 64 >> 9) << 4) + 15] = len; + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } - var w = Array(80); - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - var e = -1009589776; + var paused = startPaused || false; + var readable = false; - for(var i = 0; i < x.length; i += 16) - { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - var olde = e; + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream.prototype.pipe; + stream.on = stream.addListener = Stream.prototype.on; - for(var j = 0; j < 80; j++) - { - if(j < 16) w[j] = x[i + j]; - else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); - var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), - safe_add(safe_add(e, w[j]), sha1_kt(j))); - e = d; - d = c; - c = rol(b, 30); - b = a; - a = t; + stream.on('readable', function() { + readable = true; + + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); + + if (c === null) { + readable = false; + stream._readableState.needReadable = true; } + }); - a = safe_add(a, olda); - b = safe_add(b, oldb); - c = safe_add(c, oldc); - d = safe_add(d, oldd); - e = safe_add(e, olde); - } - return Array(a, b, c, d, e); + stream.pause = function() { + paused = true; + this.emit('pause'); + }; -} + stream.resume = function() { + paused = false; + if (readable) + setImmediate(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; -/* - * Perform the appropriate triplet combination function for the current - * iteration - */ -function sha1_ft(t, b, c, d) -{ - if(t < 20) return (b & c) | ((~b) & d); - if(t < 40) return b ^ c ^ d; - if(t < 60) return (b & c) | (b & d) | (c & d); - return b ^ c ^ d; + // now make it start, just in case it hadn't already. + stream.emit('readable'); } -/* - * Determine the appropriate additive constant for the current iteration - */ -function sha1_kt(t) -{ - return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : - (t < 60) ? -1894007588 : -899497514; -} +// 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 state = this._readableState; + var paused = false; -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ -function safe_add(x, y) -{ - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); -} + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } -/* - * Bitwise rotate a 32-bit number to the left. - */ -function rol(num, cnt) -{ - return (num << cnt) | (num >>> (32 - cnt)); -} + self.push(null); + }); -module.exports = function sha1(buf) { - return helpers.hash(buf, core_sha1, 20, true); -}; + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); + if (!chunk || !state.objectMode && !chunk.length) + return; -},{"./helpers":22}],27:[function(require,module,exports){ + var ret = self.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 (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } -/** - * 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 - * - */ + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, function (x) { + return self.emit.apply(self, ev, x); + }); + }); -var helpers = require('./helpers'); + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; -var safe_add = function(x, y) { - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); + return self; }; -var S = function(X, n) { - return (X >>> n) | (X << (32 - n)); -}; -var R = function(X, n) { - return (X >>> n); -}; -var Ch = function(x, y, z) { - return ((x & y) ^ ((~x) & z)); -}; +// exposed for testing purposes only. +Readable._fromList = fromList; -var Maj = function(x, y, z) { - return ((x & y) ^ (x & z) ^ (y & z)); -}; +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; -var Sigma0256 = function(x) { - return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); -}; + // nothing in the list, definitely empty. + if (list.length === 0) + return null; -var Sigma1256 = function(x) { - return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); -}; + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); -var Gamma0256 = function(x) { - return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); -}; + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); -var Gamma1256 = function(x) { - return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); -}; + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); -var core_sha256 = function(m, l) { - var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,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); - var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19); - var W = new Array(64); - var a, b, c, d, e, f, g, h, i, j; - var T1, T2; - /* append padding */ - m[l >> 5] |= 0x80 << (24 - l % 32); - m[((l + 64 >> 9) << 4) + 15] = l; - for (var i = 0; i < m.length; i += 16) { - a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7]; - for (var j = 0; j < 64; j++) { - if (j < 16) { - W[j] = m[j + i]; - } else { - W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]); + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; } - T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]); - T2 = safe_add(Sigma0256(a), Maj(a, b, c)); - h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2); } - HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]); - HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]); } - return HASH; -}; - -module.exports = function sha256(buf) { - return helpers.hash(buf, core_sha256, 32, true); -}; - -},{"./helpers":22}],28:[function(require,module,exports){ -var http = module.exports; -var EventEmitter = require('events').EventEmitter; -var Request = require('./lib/request'); - -http.request = function (params, cb) { - if (!params) params = {}; - if (!params.host && !params.port) { - params.port = parseInt(window.location.port, 10); - } - if (!params.host) params.host = window.location.hostname; - if (!params.port) params.port = 80; - if (!params.scheme) params.scheme = window.location.protocol.split(':')[0]; - - var req = new Request(new xhrHttp, params); - if (cb) req.on('response', cb); - return req; -}; - -http.get = function (params, cb) { - params.method = 'GET'; - var req = http.request(params, cb); - req.end(); - return req; -}; -http.Agent = function () {}; -http.Agent.defaultMaxSockets = 4; - -var xhrHttp = (function () { - if (typeof window === 'undefined') { - throw new Error('no window object present'); - } - else if (window.XMLHttpRequest) { - return window.XMLHttpRequest; - } - else if (window.ActiveXObject) { - var axs = [ - 'Msxml2.XMLHTTP.6.0', - 'Msxml2.XMLHTTP.3.0', - 'Microsoft.XMLHTTP' - ]; - for (var i = 0; i < axs.length; i++) { - try { - var ax = new(window.ActiveXObject)(axs[i]); - return function () { - if (ax) { - var ax_ = ax; - ax = null; - return ax_; - } - else { - return new(window.ActiveXObject)(axs[i]); - } - }; - } - catch (e) {} - } - throw new Error('ajax not supported in this browser') - } - else { - throw new Error('ajax not supported in this browser'); - } -})(); + return ret; +} -},{"./lib/request":29,"events":11}],29:[function(require,module,exports){ -var Stream = require('stream'); -var Response = require('./response'); -var concatStream = require('concat-stream'); -var Base64 = require('Base64'); -var util = require('util'); +function endReadable(stream) { + var state = stream._readableState; -var Request = module.exports = function (xhr, params) { - var self = this; - self.writable = true; - self.xhr = xhr; - self.body = concatStream() - - var uri = params.host - + (params.port ? ':' + params.port : '') - + (params.path || '/') - ; - - xhr.open( - params.method || 'GET', - (params.scheme || 'http') + '://' + uri, - true - ); - - if (params.headers) { - var keys = objectKeys(params.headers); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (!self.isSafeRequestHeader(key)) continue; - var value = params.headers[key]; - if (isArray(value)) { - for (var j = 0; j < value.length; j++) { - xhr.setRequestHeader(key, value[j]); - } - } - else xhr.setRequestHeader(key, value) - } - } - - if (params.auth) { - //basic auth - this.setHeader('Authorization', 'Basic ' + Base64.btoa(params.auth)); - } + // 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'); - var res = new Response; - res.on('close', function () { - self.emit('close'); - }); - - res.on('ready', function () { - self.emit('response', res); - }); - - xhr.onreadystatechange = function () { - res.handle(xhr); - }; -}; + if (!state.endEmitted && state.calledRead) { + state.ended = true; + setImmediate(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } +} -util.inherits(Request, Stream); +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} -Request.prototype.setHeader = function (key, value) { - if (isArray(value)) { - for (var i = 0; i < value.length; i++) { - this.xhr.setRequestHeader(key, value[i]); - } - } - else { - this.xhr.setRequestHeader(key, value); - } -}; +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} -Request.prototype.write = function (s) { - this.body.write(s); -}; +}).call(this,require("FWaASH")) +},{"./index.js":23,"FWaASH":17,"buffer":1,"events":10,"inherits":16,"process/browser.js":24,"string_decoder":29}],27:[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. -Request.prototype.destroy = function (s) { - this.xhr.abort(); - this.emit('close'); -}; +// 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. -Request.prototype.end = function (s) { - if (s !== undefined) this.body.write(s); - this.body.end() - this.xhr.send(this.body.getBody()); -}; +module.exports = Transform; -// Taken from http://dxr.mozilla.org/mozilla/mozilla-central/content/base/src/nsXMLHttpRequest.cpp.html -Request.unsafeHeaders = [ - "accept-charset", - "accept-encoding", - "access-control-request-headers", - "access-control-request-method", - "connection", - "content-length", - "cookie", - "cookie2", - "content-transfer-encoding", - "date", - "expect", - "host", - "keep-alive", - "origin", - "referer", - "te", - "trailer", - "transfer-encoding", - "upgrade", - "user-agent", - "via" -]; +var Duplex = require('./duplex.js'); +var inherits = require('inherits'); +inherits(Transform, Duplex); -Request.prototype.isSafeRequestHeader = function (headerName) { - if (!headerName) return false; - return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1; -}; -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -}; +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; +} -var indexOf = function (xs, x) { - if (xs.indexOf) return xs.indexOf(x); - for (var i = 0; i < xs.length; i++) { - if (xs[i] === x) return i; - } - return -1; -}; +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; -},{"./response":30,"Base64":31,"concat-stream":32,"stream":14,"util":18}],30:[function(require,module,exports){ -var Stream = require('stream'); -var util = require('util'); + var cb = ts.writecb; -var Response = module.exports = function (res) { - this.offset = 0; - this.readable = true; -}; + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); -util.inherits(Response, Stream); + ts.writechunk = null; + ts.writecb = null; -var capable = { - streaming : true, - status2 : true -}; + if (data !== null && data !== undefined) + stream.push(data); -function parseHeaders (res) { - var lines = res.getAllResponseHeaders().split(/\r?\n/); - var headers = {}; - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line === '') continue; - - var m = line.match(/^([^:]+):\s*(.*)/); - if (m) { - var key = m[1].toLowerCase(), value = m[2]; - - if (headers[key] !== undefined) { - - if (isArray(headers[key])) { - headers[key].push(value); - } - else { - headers[key] = [ headers[key], value ]; - } - } - else { - headers[key] = value; - } - } - else { - headers[line] = true; - } - } - return headers; -} + if (cb) + cb(er); -Response.prototype.getResponse = function (xhr) { - var respType = String(xhr.responseType).toLowerCase(); - if (respType === 'blob') return xhr.responseBlob || xhr.response; - if (respType === 'arraybuffer') return xhr.response; - return xhr.responseText; + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } } -Response.prototype.getHeader = function (key) { - return this.headers[key.toLowerCase()]; -}; -Response.prototype.handle = function (res) { - if (res.readyState === 2 && capable.status2) { - try { - this.statusCode = res.status; - this.headers = parseHeaders(res); - } - catch (err) { - capable.status2 = false; - } - - if (capable.status2) { - this.emit('ready'); - } - } - else if (capable.streaming && res.readyState === 3) { - try { - if (!this.statusCode) { - this.statusCode = res.status; - this.headers = parseHeaders(res); - this.emit('ready'); - } - } - catch (err) {} - - try { - this._emitData(res); - } - catch (err) { - capable.streaming = false; - } - } - else if (res.readyState === 4) { - if (!this.statusCode) { - this.statusCode = res.status; - this.emit('ready'); - } - this._emitData(res); - - if (res.error) { - this.emit('error', this.getResponse(res)); - } - else this.emit('end'); - - this.emit('close'); - } +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + var ts = this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // 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; + + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); +} + +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); }; -Response.prototype._emitData = function (res) { - var respBody = this.getResponse(res); - if (respBody.toString().match(/ArrayBuffer/)) { - this.emit('data', new Uint8Array(respBody, this.offset)); - this.offset = respBody.byteLength; - return; - } - if (respBody.length > this.offset) { - this.emit('data', respBody.slice(this.offset)); - this.offset = respBody.length; - } +// 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('not implemented'); }; -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; +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); + } }; -},{"stream":14,"util":18}],31:[function(require,module,exports){ -;(function () { +// 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; - var - object = typeof exports != 'undefined' ? exports : this, // #8: web workers - chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', - INVALID_CHARACTER_ERR = (function () { - // fabricate a suitable error object - try { document.createElement('$'); } - catch (error) { return error; }}()); + if (ts.writechunk && 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; + } +}; - // encoder - // [https://gist.github.com/999166] by [https://github.com/nignag] - object.btoa || ( - object.btoa = function (input) { - for ( - // initialize result and counter - var block, charCode, idx = 0, map = chars, output = ''; - // if the next input index does not exist: - // change the mapping table to "=" - // check if d has no fractional digits - input.charAt(idx | 0) || (map = '=', idx % 1); - // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 - output += map.charAt(63 & block >> 8 - idx % 1 * 8) - ) { - charCode = input.charCodeAt(idx += 3/4); - if (charCode > 0xFF) throw INVALID_CHARACTER_ERR; - block = block << 8 | charCode; - } - return output; - }); - // decoder - // [https://gist.github.com/1020396] by [https://github.com/atk] - object.atob || ( - object.atob = function (input) { - input = input.replace(/=+$/, '') - if (input.length % 4 == 1) throw INVALID_CHARACTER_ERR; - for ( - // initialize result and counters - var bc = 0, bs, buffer, idx = 0, output = ''; - // get next character - buffer = input.charAt(idx++); - // character found in table? initialize bit storage and add its ascii value; - ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, - // and if not first of each 4 characters, - // convert the first 8 bits to one ascii character - bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0 - ) { - // try to find character in table (0-63, not found => -1) - buffer = chars.indexOf(buffer); - } - return output; - }); +function done(stream, er) { + if (er) + return stream.emit('error', er); -}()); + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var rs = stream._readableState; + var ts = stream._transformState; -},{}],32:[function(require,module,exports){ -var stream = require('stream') -var bops = require('bops') -var util = require('util') - -function ConcatStream(cb) { - stream.Stream.call(this) - this.writable = true - if (cb) this.cb = cb - this.body = [] - this.on('error', function(err) { - // no-op - }) -} + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); -util.inherits(ConcatStream, stream.Stream) + if (ts.transforming) + throw new Error('calling transform done when still transforming'); -ConcatStream.prototype.write = function(chunk) { - this.body.push(chunk) + return stream.push(null); } -ConcatStream.prototype.destroy = function() {} +},{"./duplex.js":22,"inherits":16}],28:[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. -ConcatStream.prototype.arrayConcat = function(arrs) { - if (arrs.length === 0) return [] - if (arrs.length === 1) return arrs[0] - return arrs.reduce(function (a, b) { return a.concat(b) }) -} +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. -ConcatStream.prototype.isArray = function(arr) { - return Array.isArray(arr) -} +module.exports = Writable; +Writable.WritableState = WritableState; -ConcatStream.prototype.getBody = function () { - if (this.body.length === 0) return - if (typeof(this.body[0]) === "string") return this.body.join('') - if (this.isArray(this.body[0])) return this.arrayConcat(this.body) - if (bops.is(this.body[0])) return bops.join(this.body) - return this.body -} +var isUint8Array = typeof Uint8Array !== 'undefined' + ? function (x) { return x instanceof Uint8Array } + : function (x) { + return x && x.constructor && x.constructor.name === 'Uint8Array' + } +; +var isArrayBuffer = typeof ArrayBuffer !== 'undefined' + ? function (x) { return x instanceof ArrayBuffer } + : function (x) { + return x && x.constructor && x.constructor.name === 'ArrayBuffer' + } +; -ConcatStream.prototype.end = function() { - if (this.cb) this.cb(this.getBody()) -} +var inherits = require('inherits'); +var Stream = require('./index.js'); +var setImmediate = require('process/browser.js').nextTick; +var Buffer = require('buffer').Buffer; -module.exports = function(cb) { - return new ConcatStream(cb) +inherits(Writable, Stream); + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; } -module.exports.ConcatStream = ConcatStream +function WritableState(options, stream) { + options = options || {}; + + // 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; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; -},{"bops":33,"stream":14,"util":18}],33:[function(require,module,exports){ -var proto = {} -module.exports = proto + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; -proto.from = require('./from.js') -proto.to = require('./to.js') -proto.is = require('./is.js') -proto.subarray = require('./subarray.js') -proto.join = require('./join.js') -proto.copy = require('./copy.js') -proto.create = require('./create.js') + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; -mix(require('./read.js'), proto) -mix(require('./write.js'), proto) + 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; -function mix(from, into) { - for(var key in from) { - into[key] = from[key] - } + // 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; + + // 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, becuase 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.buffer = []; } -},{"./copy.js":36,"./create.js":37,"./from.js":38,"./is.js":39,"./join.js":40,"./read.js":42,"./subarray.js":43,"./to.js":44,"./write.js":45}],34:[function(require,module,exports){ -module.exports=require(21) -},{}],35:[function(require,module,exports){ -module.exports = to_utf8 - -var out = [] - , col = [] - , fcc = String.fromCharCode - , mask = [0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01] - , unmask = [ - 0x00 - , 0x01 - , 0x02 | 0x01 - , 0x04 | 0x02 | 0x01 - , 0x08 | 0x04 | 0x02 | 0x01 - , 0x10 | 0x08 | 0x04 | 0x02 | 0x01 - , 0x20 | 0x10 | 0x08 | 0x04 | 0x02 | 0x01 - , 0x40 | 0x20 | 0x10 | 0x08 | 0x04 | 0x02 | 0x01 - ] - -function to_utf8(bytes, start, end) { - start = start === undefined ? 0 : start - end = end === undefined ? bytes.length : end - - var idx = 0 - , hi = 0x80 - , collecting = 0 - , pos - , by - - col.length = - out.length = 0 - - while(idx < bytes.length) { - by = bytes[idx] - if(!collecting && by & hi) { - pos = find_pad_position(by) - collecting += pos - if(pos < 8) { - col[col.length] = by & unmask[6 - pos] - } - } else if(collecting) { - col[col.length] = by & unmask[6] - --collecting - if(!collecting && col.length) { - out[out.length] = fcc(reduced(col, pos)) - col.length = 0 - } - } else { - out[out.length] = fcc(by) - } - ++idx - } - if(col.length && !collecting) { - out[out.length] = fcc(reduced(col, pos)) - col.length = 0 - } - return out.join('') +function Writable(options) { + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Stream.Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + Stream.call(this); } -function find_pad_position(byt) { - for(var i = 0; i < 7; ++i) { - if(!(byt & mask[i])) { - break - } - } - return i +// 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, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + setImmediate(function() { + cb(er); + }); } -function reduced(list) { - var out = 0 - for(var i = 0, len = list.length; i < len; ++i) { - out |= list[i] << ((len - i - 1) * 6) +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + setImmediate(function() { + cb(er); + }); + valid = false; } - return out + return valid; } -},{}],36:[function(require,module,exports){ -module.exports = copy - -var slice = [].slice - -function copy(source, target, target_start, source_start, source_end) { - target_start = arguments.length < 3 ? 0 : target_start - source_start = arguments.length < 4 ? 0 : source_start - source_end = arguments.length < 5 ? source.length : source_end +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - if(source_end === source_start) { - return + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - if(target.length === 0 || source.length === 0) { - return - } + if (!Buffer.isBuffer(chunk) && isUint8Array(chunk)) + chunk = new Buffer(chunk); + if (isArrayBuffer(chunk) && typeof Uint8Array !== 'undefined') + chunk = new Buffer(new Uint8Array(chunk)); + + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; - if(source_end > source.length) { - source_end = source.length - } + if (typeof cb !== 'function') + cb = function() {}; - if(target.length - target_start < source_end - source_start) { - source_end = target.length - target_start + start - } + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); + + return ret; +}; - if(source.buffer !== target.buffer) { - return fast_copy(source, target, target_start, source_start, source_end) +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); } - return slow_copy(source, target, target_start, source_start, source_end) + return chunk; } -function fast_copy(source, target, target_start, source_start, source_end) { - var len = (source_end - source_start) + target_start +// 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, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; - for(var i = target_start, j = source_start; - i < len; - ++i, - ++j) { - target[i] = source[j] - } -} + var ret = state.length < state.highWaterMark; + state.needDrain = !ret; -function slow_copy(from, to, j, i, jend) { - // the buffers could overlap. - var iend = jend + i - , tmp = new Uint8Array(slice.call(from, i, iend)) - , x = 0 + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); - for(; i < iend; ++i, ++x) { - to[j++] = tmp[x] - } + return ret; } -},{}],37:[function(require,module,exports){ -module.exports = function(size) { - return new Uint8Array(size) +function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; } -},{}],38:[function(require,module,exports){ -module.exports = from - -var base64 = require('base64-js') +function onwriteError(stream, state, sync, er, cb) { + if (sync) + setImmediate(function() { + cb(er); + }); + else + cb(er); -var decoders = { - hex: from_hex - , utf8: from_utf - , base64: from_base64 + stream.emit('error', er); } -function from(source, encoding) { - if(Array.isArray(source)) { - return new Uint8Array(source) - } - - return decoders[encoding || 'utf8'](source) +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; } -function from_hex(str) { - var size = str.length / 2 - , buf = new Uint8Array(size) - , character = '' +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; - for(var i = 0, len = str.length; i < len; ++i) { - character += str.charAt(i) + onwriteStateUpdate(state); - if(i > 0 && (i % 2) === 1) { - buf[i>>>1] = parseInt(character, 16) - character = '' - } - } + 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(stream, state); - return buf -} + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); -function from_utf(str) { - var bytes = [] - , tmp - , ch - - for(var i = 0, len = str.length; i < len; ++i) { - ch = str.charCodeAt(i) - if(ch & 0x80) { - tmp = encodeURIComponent(str.charAt(i)).substr(1).split('%') - for(var j = 0, jlen = tmp.length; j < jlen; ++j) { - bytes[bytes.length] = parseInt(tmp[j], 16) - } + if (sync) { + setImmediate(function() { + afterWrite(stream, state, finished, cb); + }); } else { - bytes[bytes.length] = ch + afterWrite(stream, state, finished, cb); } } - - return new Uint8Array(bytes) } -function from_base64(str) { - return new Uint8Array(base64.toByteArray(str)) +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); } -},{"base64-js":34}],39:[function(require,module,exports){ - -module.exports = function(buffer) { - return buffer instanceof Uint8Array; +// 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'); + } } -},{}],40:[function(require,module,exports){ -module.exports = join -function join(targets, hint) { - if(!targets.length) { - return new Uint8Array(0) - } +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; - var len = hint !== undefined ? hint : get_length(targets) - , out = new Uint8Array(len) - , cur = targets[0] - , curlen = cur.length - , curidx = 0 - , curoff = 0 - , i = 0 + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, len, chunk, encoding, cb); - while(i < len) { - if(curoff === curlen) { - curoff = 0 - ++curidx - cur = targets[curidx] - curlen = cur && cur.length - continue + // 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) { + c++; + break; } - out[i++] = cur[curoff++] } - return out + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; } -function get_length(targets) { - var size = 0 - for(var i = 0, len = targets.length; i < len; ++i) { - size += targets[i].byteLength - } - return size -} +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); +}; -},{}],41:[function(require,module,exports){ -var proto - , map +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; + } -module.exports = proto = {} + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); -map = typeof WeakMap === 'undefined' ? null : new WeakMap + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); +}; -proto.get = !map ? no_weakmap_get : get -function no_weakmap_get(target) { - return new DataView(target.buffer, 0) +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); } -function get(target) { - var out = map.get(target.buffer) - if(!out) { - map.set(target.buffer, out = new DataView(target.buffer, 0)) +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); } - return out + return need; } -},{}],42:[function(require,module,exports){ -module.exports = { - readUInt8: read_uint8 - , readInt8: read_int8 - , readUInt16LE: read_uint16_le - , readUInt32LE: read_uint32_le - , readInt16LE: read_int16_le - , readInt32LE: read_int32_le - , readFloatLE: read_float_le - , readDoubleLE: read_double_le - , readUInt16BE: read_uint16_be - , readUInt32BE: read_uint32_be - , readInt16BE: read_int16_be - , readInt32BE: read_int32_be - , readFloatBE: read_float_be - , readDoubleBE: read_double_be +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + setImmediate(cb); + else + stream.once('finish', cb); + } + state.ended = true; } -var map = require('./mapped.js') +},{"./index.js":23,"buffer":1,"inherits":16,"process/browser.js":24}],29:[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 Buffer = require('buffer').Buffer; -function read_uint8(target, at) { - return target[at] +function assertEncoding(encoding) { + if (encoding && !Buffer.isEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } } -function read_int8(target, at) { - var v = target[at]; - return v < 0x80 ? v : v - 0x100 -} +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + this.charBuffer = new Buffer(6); + this.charReceived = 0; + this.charLength = 0; +}; -function read_uint16_le(target, at) { - var dv = map.get(target); - return dv.getUint16(at + target.byteOffset, true) -} -function read_uint32_le(target, at) { - var dv = map.get(target); - return dv.getUint32(at + target.byteOffset, true) -} +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + var offset = 0; -function read_int16_le(target, at) { - var dv = map.get(target); - return dv.getInt16(at + target.byteOffset, true) -} + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var i = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; -function read_int32_le(target, at) { - var dv = map.get(target); - return dv.getInt32(at + target.byteOffset, true) -} + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, offset, i); + this.charReceived += (i - offset); + offset = i; -function read_float_le(target, at) { - var dv = map.get(target); - return dv.getFloat32(at + target.byteOffset, true) -} + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } -function read_double_le(target, at) { - var dv = map.get(target); - return dv.getFloat64(at + target.byteOffset, true) -} + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); -function read_uint16_be(target, at) { - var dv = map.get(target); - return dv.getUint16(at + target.byteOffset, false) -} + // lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; -function read_uint32_be(target, at) { - var dv = map.get(target); - return dv.getUint32(at + target.byteOffset, false) -} + // if there are no more bytes in this buffer, just emit our char + if (i == buffer.length) return charStr; -function read_int16_be(target, at) { - var dv = map.get(target); - return dv.getInt16(at + target.byteOffset, false) -} + // otherwise cut off the characters end from the beginning of this buffer + buffer = buffer.slice(i, buffer.length); + break; + } -function read_int32_be(target, at) { - var dv = map.get(target); - return dv.getInt32(at + target.byteOffset, false) -} + var lenIncomplete = this.detectIncompleteChar(buffer); -function read_float_be(target, at) { - var dv = map.get(target); - return dv.getFloat32(at + target.byteOffset, false) -} + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - lenIncomplete, end); + this.charReceived = lenIncomplete; + end -= lenIncomplete; + } -function read_double_be(target, at) { - var dv = map.get(target); - return dv.getFloat64(at + target.byteOffset, false) -} + charStr += buffer.toString(this.encoding, 0, end); -},{"./mapped.js":41}],43:[function(require,module,exports){ -module.exports = subarray + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + this.charBuffer.write(charStr.charAt(charStr.length - 1), this.encoding); + return charStr.substring(0, end); + } -function subarray(buf, from, to) { - return buf.subarray(from || 0, to || buf.length) -} + // or just emit the charStr + return charStr; +}; -},{}],44:[function(require,module,exports){ -module.exports = to +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; -var base64 = require('base64-js') - , toutf8 = require('to-utf8') + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; -var encoders = { - hex: to_hex - , utf8: to_utf - , base64: to_base64 -} + // See http://en.wikipedia.org/wiki/UTF-8#Description -function to(buf, encoding) { - return encoders[encoding || 'utf8'](buf) -} + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } -function to_hex(buf) { - var str = '' - , byt + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } - for(var i = 0, len = buf.length; i < len; ++i) { - byt = buf[i] - str += ((byt & 0xF0) >>> 4).toString(16) - str += (byt & 0x0F).toString(16) + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } } - return str -} + return i; +}; -function to_utf(buf) { - return toutf8(buf) -} +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); -function to_base64(buf) { - return base64.fromByteArray(buf) -} + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + return res; +}; -},{"base64-js":34,"to-utf8":35}],45:[function(require,module,exports){ -module.exports = { - writeUInt8: write_uint8 - , writeInt8: write_int8 - , writeUInt16LE: write_uint16_le - , writeUInt32LE: write_uint32_le - , writeInt16LE: write_int16_le - , writeInt32LE: write_int32_le - , writeFloatLE: write_float_le - , writeDoubleLE: write_double_le - , writeUInt16BE: write_uint16_be - , writeUInt32BE: write_uint32_be - , writeInt16BE: write_int16_be - , writeInt32BE: write_int32_be - , writeFloatBE: write_float_be - , writeDoubleBE: write_double_be +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); } -var map = require('./mapped.js') - -function write_uint8(target, value, at) { - return target[at] = value +function utf16DetectIncompleteChar(buffer) { + var incomplete = this.charReceived = buffer.length % 2; + this.charLength = incomplete ? 2 : 0; + return incomplete; } -function write_int8(target, value, at) { - return target[at] = value < 0 ? value + 0x100 : value +function base64DetectIncompleteChar(buffer) { + var incomplete = this.charReceived = buffer.length % 3; + this.charLength = incomplete ? 3 : 0; + return incomplete; } -function write_uint16_le(target, value, at) { - var dv = map.get(target); - return dv.setUint16(at + target.byteOffset, value, true) -} +},{"buffer":1}],30:[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. -function write_uint32_le(target, value, at) { - var dv = map.get(target); - return dv.setUint32(at + target.byteOffset, value, true) -} +var punycode = require('punycode'); -function write_int16_le(target, value, at) { - var dv = map.get(target); - return dv.setInt16(at + target.byteOffset, value, true) -} +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; -function write_int32_le(target, value, at) { - var dv = map.get(target); - return dv.setInt32(at + target.byteOffset, value, true) -} +exports.Url = Url; -function write_float_le(target, value, at) { - var dv = map.get(target); - return dv.setFloat32(at + target.byteOffset, value, true) +function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; } -function write_double_le(target, value, at) { - var dv = map.get(target); - return dv.setFloat64(at + target.byteOffset, value, true) -} +// Reference: RFC 3986, RFC 1808, RFC 2396 -function write_uint16_be(target, value, at) { - var dv = map.get(target); - return dv.setUint16(at + target.byteOffset, value, false) -} +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, -function write_uint32_be(target, value, at) { - var dv = map.get(target); - return dv.setUint32(at + target.byteOffset, value, false) -} + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], -function write_int16_be(target, value, at) { - var dv = map.get(target); - return dv.setInt16(at + target.byteOffset, value, false) -} + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), -function write_int32_be(target, value, at) { - var dv = map.get(target); - return dv.setInt32(at + target.byteOffset, value, false) -} + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = require('querystring'); -function write_float_be(target, value, at) { - var dv = map.get(target); - return dv.setFloat32(at + target.byteOffset, value, false) -} +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject(url) && url instanceof Url) return url; -function write_double_be(target, value, at) { - var dv = map.get(target); - return dv.setFloat64(at + target.byteOffset, value, false) + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; } -},{"./mapped.js":41}],46:[function(require,module,exports){ -require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o> 1, - nBits = -7, - i = isBE ? 0 : (nBytes - 1), - d = isBE ? 1 : -1, - 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; +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; -exports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) { - var e, m, c, - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = isBE ? (nBytes - 1) : 0, - d = isBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + var rest = url; - value = Math.abs(value); + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); - 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; - } + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } - 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; + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; } } - 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; -}; + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { -},{}],"q9TxCC":[function(require,module,exports){ -var assert; -exports.Buffer = Buffer; -exports.SlowBuffer = Buffer; -Buffer.poolSize = 8192; -exports.INSPECT_MAX_BYTES = 50; + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c -function stringtrim(str) { - if (str.trim) return str.trim(); - return str.replace(/^\s+|\s+$/g, ''); -} + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. -function Buffer(subject, encoding, offset) { - if(!assert) assert= require('assert'); - if (!(this instanceof Buffer)) { - return new Buffer(subject, encoding, offset); - } - this.parent = this; - this.offset = 0; + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } - // Work-around: node's base64 implementation - // allows for non-padded strings while base64-js - // does not.. - if (encoding == "base64" && typeof subject == "string") { - subject = stringtrim(subject); - while (subject.length % 4 != 0) { - subject = subject + "="; + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); } - } - var type; + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } - // Are we slicing? - if (typeof offset === 'number') { - this.length = coerce(encoding); - // slicing works, with limitations (no parent tracking/update) - // check https://github.com/toots/buffer-browserify/issues/19 - for (var i = 0; i < this.length; i++) { - this[i] = subject.get(i+offset); + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; } - } else { - // Find the length - switch (type = typeof subject) { - case 'number': - this.length = coerce(subject); - break; + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; - case 'string': - this.length = Buffer.byteLength(subject, encoding); - break; + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); - case 'object': // Assume object is an array - this.length = coerce(subject.length); - break; + // pull out port. + this.parseHost(); - default: - throw new Error('First argument needs to be a number, ' + - 'array or string.'); - } + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; - // Treat array-ish objects as a byte array. - if (isArrayIsh(subject)) { - for (var i = 0; i < this.length; i++) { - if (subject instanceof Buffer) { - this[i] = subject.readUInt8(i); - } - else { - this[i] = subject[i]; + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } } } - } else if (type == 'string') { - // We are a string - this.length = this.write(subject, 0, encoding); - } else if (type === 'number') { - for (var i = 0; i < this.length; i++) { - this[i] = 0; - } } - } -} - -Buffer.prototype.get = function get(i) { - if (i < 0 || i >= this.length) throw new Error('oob'); - return this[i]; -}; -Buffer.prototype.set = function set(i, v) { - if (i < 0 || i >= this.length) throw new Error('oob'); - return this[i] = v; -}; + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } -Buffer.byteLength = function (str, encoding) { - switch (encoding || "utf8") { - case 'hex': - return str.length / 2; + if (!ipv6Hostname) { + // IDNA Support: Returns a puny coded representation of "domain". + // It only converts the part of the domain name that + // has non ASCII characters. I.e. it dosent matter if + // you call it with a domain that already is in ASCII. + var domainArray = this.hostname.split('.'); + var newOut = []; + for (var i = 0; i < domainArray.length; ++i) { + var s = domainArray[i]; + newOut.push(s.match(/[^A-Za-z0-9_-]/) ? + 'xn--' + punycode.encode(s) : s); + } + this.hostname = newOut.join('.'); + } - case 'utf8': - case 'utf-8': - return utf8ToBytes(str).length; + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; - case 'ascii': - case 'binary': - return str.length; + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } - case 'base64': - return base64ToBytes(str).length; + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { - default: - throw new Error('Unknown encoding'); + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } } -}; - -Buffer.prototype.utf8Write = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length); -}; -Buffer.prototype.asciiWrite = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length); -}; -Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite; + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) this.pathname = rest; + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } -Buffer.prototype.base64Write = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length); -}; + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } -Buffer.prototype.base64Slice = function (start, end) { - var bytes = Array.prototype.slice.apply(this, arguments) - return require("base64-js").fromByteArray(bytes); + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; }; -Buffer.prototype.utf8Slice = function () { - var bytes = Array.prototype.slice.apply(this, arguments); - var res = ""; - var tmp = ""; - var i = 0; - while (i < bytes.length) { - if (bytes[i] <= 0x7F) { - res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]); - tmp = ""; - } else - tmp += "%" + bytes[i].toString(16); - - i++; - } - - return res + decodeUtf8Char(tmp); +// format a parsed object into a url string +function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (isString(obj)) obj = urlParse(obj); + if (!(obj instanceof Url)) return Url.prototype.format.call(obj); + return obj.format(); } -Buffer.prototype.asciiSlice = function () { - var bytes = Array.prototype.slice.apply(this, arguments); - var ret = ""; - for (var i = 0; i < bytes.length; i++) - ret += String.fromCharCode(bytes[i]); - return ret; -} +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } -Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice; + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; -Buffer.prototype.inspect = function() { - var out = [], - len = this.length; - for (var i = 0; i < len; i++) { - out[i] = toHex(this[i]); - if (i == exports.INSPECT_MAX_BYTES) { - out[i + 1] = '...'; - break; + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; } } - return ''; -}; + if (this.query && + isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } -Buffer.prototype.hexSlice = function(start, end) { - var len = this.length; + var search = this.search || (query && ('?' + query)) || ''; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - var out = ''; - for (var i = start; i < end; i++) { - out += toHex(this[i]); + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; } - return out; -}; + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; -Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - start = +start || 0; - if (typeof end == 'undefined') end = this.length; + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); - // Fastpath empty strings - if (+end == start) { - return ''; - } + return protocol + host + pathname + search + hash; +}; - switch (encoding) { - case 'hex': - return this.hexSlice(start, end); +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); +} - case 'utf8': - case 'utf-8': - return this.utf8Slice(start, end); +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); +}; - case 'ascii': - return this.asciiSlice(start, end); +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} - case 'binary': - return this.binarySlice(start, end); +Url.prototype.resolveObject = function(relative) { + if (isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } - case 'base64': - return this.base64Slice(start, end); + var result = new Url(); + Object.keys(this).forEach(function(k) { + result[k] = this[k]; + }, this); - case 'ucs2': - case 'ucs-2': - return this.ucs2Slice(start, end); + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; - default: - throw new Error('Unknown encoding'); + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; } -}; + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + Object.keys(relative).forEach(function(k) { + if (k !== 'protocol') + result[k] = relative[k]; + }); -Buffer.prototype.hexWrite = function(string, offset, length) { - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; } - } - // must be an even number of digits - var strLen = string.length; - if (strLen % 2) { - throw new Error('Invalid hex string'); - } - if (length > strLen / 2) { - length = strLen / 2; + result.href = result.format(); + return result; } - for (var i = 0; i < length; i++) { - var byte = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(byte)) throw new Error('Invalid hex string'); - this[offset + i] = byte; + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + Object.keys(relative).forEach(function(k) { + result[k] = relative[k]; + }); + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; } - Buffer._charsWritten = i * 2; - return i; -}; + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; -Buffer.prototype.write = function(string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especialy happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); } - } - encoding = String(encoding || 'utf8').toLowerCase(); - - switch (encoding) { - case 'hex': - return this.hexWrite(string, offset, length); - - case 'utf8': - case 'utf-8': - return this.utf8Write(string, offset, length); - - case 'ascii': - return this.asciiWrite(string, offset, length); - - case 'binary': - return this.binaryWrite(string, offset, length); - - case 'base64': - return this.base64Write(string, offset, length); - - case 'ucs2': - case 'ucs-2': - return this.ucs2Write(string, offset, length); - - default: - throw new Error('Unknown encoding'); - } -}; - -// slice(start, end) -function clamp(index, len, defaultValue) { - if (typeof index !== 'number') return defaultValue; - index = ~~index; // Coerce to integer. - if (index >= len) return len; - if (index >= 0) return index; - index += len; - if (index >= 0) return index; - return 0; -} - -Buffer.prototype.slice = function(start, end) { - var len = this.length; - start = clamp(start, len, 0); - end = clamp(end, len, len); - return new Buffer(this, end - start, +start); -}; - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function(target, target_start, start, end) { - var source = this; - start || (start = 0); - if (end === undefined || isNaN(end)) { - end = this.length; - } - target_start || (target_start = 0); - - if (end < start) throw new Error('sourceEnd < sourceStart'); - - // Copy 0 bytes; we're done - if (end === start) return 0; - if (target.length == 0 || source.length == 0) return 0; - - if (target_start < 0 || target_start >= target.length) { - throw new Error('targetStart out of bounds'); + result.href = result.format(); + return result; } - if (start < 0 || start >= source.length) { - throw new Error('sourceStart out of bounds'); + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; } - if (end < 0 || end > source.length) { - throw new Error('sourceEnd out of bounds'); - } + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host) && (last === '.' || last === '..') || + last === ''); - // Are we oob? - if (end > this.length) { - end = this.length; + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last == '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } } - if (target.length - target_start < end - start) { - end = target.length - target_start + start; + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } } - var temp = []; - for (var i=start; i 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } } - if (end < start) throw new Error('end < start'); - - // Fill 0 bytes; we're done - if (end === start) return 0; - if (this.length == 0) return 0; + mustEndAbs = mustEndAbs || (result.host && srcPath.length); - if (start < 0 || start >= this.length) { - throw new Error('start out of bounds'); + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); } - if (end < 0 || end > this.length) { - throw new Error('end out of bounds'); + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); } - for (var i = start; i < end; i++) { - this[i] = value; + //to support request.http + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); } -} - -// Static methods -Buffer.isBuffer = function isBuffer(b) { - return b instanceof Buffer || b instanceof Buffer; + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; }; -Buffer.concat = function (list, totalLength) { - if (!isArray(list)) { - throw new Error("Usage: Buffer.concat(list, [totalLength])\n \ - list should be an Array."); - } - - if (list.length === 0) { - return new Buffer(0); - } else if (list.length === 1) { - return list[0]; - } - - if (typeof totalLength !== 'number') { - totalLength = 0; - for (var i = 0; i < list.length; i++) { - var buf = list[i]; - totalLength += buf.length; +Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); } + host = host.substr(0, host.length - port.length); } - - var buffer = new Buffer(totalLength); - var pos = 0; - for (var i = 0; i < list.length; i++) { - var buf = list[i]; - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer; -}; - -Buffer.isEncoding = function(encoding) { - switch ((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; - } + if (host) this.hostname = host; }; -// helpers - -function coerce(length) { - // Coerce length to a number (possibly NaN), round up - // in case it's fractional (e.g. 123.456) then do a - // double negate to coerce a NaN to 0. Easy, right? - length = ~~Math.ceil(+length); - return length < 0 ? 0 : length; -} - -function isArray(subject) { - return (Array.isArray || - function(subject){ - return {}.toString.apply(subject) == '[object Array]' - }) - (subject) -} - -function isArrayIsh(subject) { - return isArray(subject) || Buffer.isBuffer(subject) || - subject && typeof subject === 'object' && - typeof subject.length === 'number'; -} - -function toHex(n) { - if (n < 16) return '0' + n.toString(16); - return n.toString(16); -} - -function utf8ToBytes(str) { - var byteArray = []; - for (var i = 0; i < str.length; i++) - if (str.charCodeAt(i) <= 0x7F) - byteArray.push(str.charCodeAt(i)); - else { - var h = encodeURIComponent(str.charAt(i)).substr(1).split('%'); - for (var j = 0; j < h.length; j++) - byteArray.push(parseInt(h[j], 16)); - } - - return byteArray; +function isString(arg) { + return typeof arg === "string"; } -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 isObject(arg) { + return typeof arg === 'object' && arg !== null; } -function base64ToBytes(str) { - return require("base64-js").toByteArray(str); +function isNull(arg) { + return arg === null; } - -function blitBuffer(src, dst, offset, length) { - var pos, i = 0; - while (i < length) { - if ((i+offset >= dst.length) || (i >= src.length)) - break; - - dst[i + offset] = src[i]; - i++; - } - return i; +function isNullOrUndefined(arg) { + return arg == null; } -function decodeUtf8Char(str) { - try { - return decodeURIComponent(str); - } catch (err) { - return String.fromCharCode(0xFFFD); // UTF 8 invalid char - } +},{"punycode":18,"querystring":21}],31:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; } +},{}],32:[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. -// read/write bit-twiddling - -Buffer.prototype.readUInt8 = function(offset, noAssert) { - var buffer = this; - - if (!noAssert) { - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset < buffer.length, - 'Trying to read beyond buffer length'); - } - - if (offset >= buffer.length) return; - - return buffer[offset]; -}; - -function readUInt16(buffer, offset, isBigEndian, noAssert) { - var val = 0; - - - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset + 1 < buffer.length, - 'Trying to read beyond buffer length'); +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); } - if (offset >= buffer.length) return 0; - - if (isBigEndian) { - val = buffer[offset] << 8; - if (offset + 1 < buffer.length) { - val |= buffer[offset + 1]; + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; } - } else { - val = buffer[offset]; - if (offset + 1 < buffer.length) { - val |= buffer[offset + 1] << 8; + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); } } - - return val; -} - -Buffer.prototype.readUInt16LE = function(offset, noAssert) { - return readUInt16(this, offset, false, noAssert); -}; - -Buffer.prototype.readUInt16BE = function(offset, noAssert) { - return readUInt16(this, offset, true, noAssert); + return str; }; -function readUInt32(buffer, offset, isBigEndian, noAssert) { - var val = 0; - - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset + 3 < buffer.length, - 'Trying to read beyond buffer length'); - } - - if (offset >= buffer.length) return 0; - if (isBigEndian) { - if (offset + 1 < buffer.length) - val = buffer[offset + 1] << 16; - if (offset + 2 < buffer.length) - val |= buffer[offset + 2] << 8; - if (offset + 3 < buffer.length) - val |= buffer[offset + 3]; - val = val + (buffer[offset] << 24 >>> 0); - } else { - if (offset + 2 < buffer.length) - val = buffer[offset + 2] << 16; - if (offset + 1 < buffer.length) - val |= buffer[offset + 1] << 8; - val |= buffer[offset]; - if (offset + 3 < buffer.length) - val = val + (buffer[offset + 3] << 24 >>> 0); +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; } - return val; -} - -Buffer.prototype.readUInt32LE = function(offset, noAssert) { - return readUInt32(this, offset, false, noAssert); -}; - -Buffer.prototype.readUInt32BE = function(offset, noAssert) { - return readUInt32(this, offset, true, noAssert); -}; - - -/* - * Signed integer types, yay team! A reminder on how two's complement actually - * works. The first bit is the signed bit, i.e. tells us whether or not the - * number should be positive or negative. If the two's complement value is - * positive, then we're done, as it's equivalent to the unsigned representation. - * - * Now if the number is positive, you're pretty much done, you can just leverage - * the unsigned translations and return those. Unfortunately, negative numbers - * aren't quite that straightforward. - * - * At first glance, one might be inclined to use the traditional formula to - * translate binary numbers between the positive and negative values in two's - * complement. (Though it doesn't quite work for the most negative value) - * Mainly: - * - invert all the bits - * - add one to the result - * - * Of course, this doesn't quite work in Javascript. Take for example the value - * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of - * course, Javascript will do the following: - * - * > ~0xff80 - * -65409 - * - * Whoh there, Javascript, that's not quite right. But wait, according to - * Javascript that's perfectly correct. When Javascript ends up seeing the - * constant 0xff80, it has no notion that it is actually a signed number. It - * assumes that we've input the unsigned value 0xff80. Thus, when it does the - * binary negation, it casts it into a signed value, (positive 0xff80). Then - * when you perform binary negation on that, it turns it into a negative number. - * - * Instead, we're going to have to use the following general formula, that works - * in a rather Javascript friendly way. I'm glad we don't support this kind of - * weird numbering scheme in the kernel. - * - * (BIT-MAX - (unsigned)val + 1) * -1 - * - * The astute observer, may think that this doesn't make sense for 8-bit numbers - * (really it isn't necessary for them). However, when you get 16-bit numbers, - * you do. Let's go back to our prior example and see how this will look: - * - * (0xffff - 0xff80 + 1) * -1 - * (0x007f + 1) * -1 - * (0x0080) * -1 - */ -Buffer.prototype.readInt8 = function(offset, noAssert) { - var buffer = this; - var neg; - - if (!noAssert) { - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset < buffer.length, - 'Trying to read beyond buffer length'); + if (process.noDeprecation === true) { + return fn; } - if (offset >= buffer.length) return; - - neg = buffer[offset] & 0x80; - if (!neg) { - return (buffer[offset]); + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); } - return ((0xff - buffer[offset] + 1) * -1); + return deprecated; }; -function readInt16(buffer, offset, isBigEndian, noAssert) { - var neg, val; - - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset + 1 < buffer.length, - 'Trying to read beyond buffer length'); - } - val = readUInt16(buffer, offset, isBigEndian, noAssert); - neg = val & 0x8000; - if (!neg) { - return val; +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } } - - return (0xffff - val + 1) * -1; -} - -Buffer.prototype.readInt16LE = function(offset, noAssert) { - return readInt16(this, offset, false, noAssert); -}; - -Buffer.prototype.readInt16BE = function(offset, noAssert) { - return readInt16(this, offset, true, noAssert); + return debugs[set]; }; -function readInt32(buffer, offset, isBigEndian, noAssert) { - var neg, val; - - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset + 3 < buffer.length, - 'Trying to read beyond buffer length'); - } - val = readUInt32(buffer, offset, isBigEndian, noAssert); - neg = val & 0x80000000; - if (!neg) { - return (val); +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); } - - return (0xffffffff - val + 1) * -1; + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); } +exports.inspect = inspect; -Buffer.prototype.readInt32LE = function(offset, noAssert) { - return readInt32(this, offset, false, noAssert); -}; -Buffer.prototype.readInt32BE = function(offset, noAssert) { - return readInt32(this, offset, true, noAssert); +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] }; -function readFloat(buffer, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset + 3 < buffer.length, - 'Trying to read beyond buffer length'); - } - - return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, - 23, 4); -} - -Buffer.prototype.readFloatLE = function(offset, noAssert) { - return readFloat(this, offset, false, noAssert); +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' }; -Buffer.prototype.readFloatBE = function(offset, noAssert) { - return readFloat(this, offset, true, noAssert); -}; -function readDouble(buffer, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; - assert.ok(offset + 7 < buffer.length, - 'Trying to read beyond buffer length'); + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; } - - return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, - 52, 8); } -Buffer.prototype.readDoubleLE = function(offset, noAssert) { - return readDouble(this, offset, false, noAssert); -}; - -Buffer.prototype.readDoubleBE = function(offset, noAssert) { - return readDouble(this, offset, true, noAssert); -}; +function stylizeNoColor(str, styleType) { + return str; +} -/* - * We have to make sure that the value is a valid integer. This means that it is - * non-negative. It has no fractional component and that it does not exceed the - * maximum allowed value. - * - * value The number to check for validity - * - * max The maximum value - */ -function verifuint(value, max) { - assert.ok(typeof (value) == 'number', - 'cannot write a non-number as a number'); - assert.ok(value >= 0, - 'specified a negative value for writing an unsigned value'); +function arrayToHash(array) { + var hash = {}; - assert.ok(value <= max, 'value is larger than maximum value for type'); + array.forEach(function(val, idx) { + hash[val] = true; + }); - assert.ok(Math.floor(value) === value, 'value has a fractional component'); + return hash; } -Buffer.prototype.writeUInt8 = function(value, offset, noAssert) { - var buffer = this; - - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - assert.ok(offset < buffer.length, - 'trying to write beyond buffer length'); - - verifuint(value, 0xff); +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; } - if (offset < buffer.length) { - buffer[offset] = value; + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; } -}; - -function writeUInt16(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset + 1 < buffer.length, - 'trying to write beyond buffer length'); + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - verifuint(value, 0xffff); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); } - for (var i = 0; i < Math.min(buffer.length - offset, 2); i++) { - buffer[offset + i] = - (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>> - (isBigEndian ? 1 - i : i) * 8; + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); } -} - -Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) { - writeUInt16(this, value, offset, false, noAssert); -}; - -Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) { - writeUInt16(this, value, offset, true, noAssert); -}; - -function writeUInt32(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); - - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } - assert.ok(offset + 3 < buffer.length, - 'trying to write beyond buffer length'); + var base = '', array = false, braces = ['{', '}']; - verifuint(value, 0xffffffff); + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; } - for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) { - buffer[offset + i] = - (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff; + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; } -} -Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) { - writeUInt32(this, value, offset, false, noAssert); -}; + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } -Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) { - writeUInt32(this, value, offset, true, noAssert); -}; + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } -/* - * We now move onto our friends in the signed number category. Unlike unsigned - * numbers, we're going to have to worry a bit more about how we put values into - * arrays. Since we are only worrying about signed 32-bit values, we're in - * slightly better shape. Unfortunately, we really can't do our favorite binary - * & in this system. It really seems to do the wrong thing. For example: - * - * > -32 & 0xff - * 224 - * - * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of - * this aren't treated as a signed number. Ultimately a bad thing. - * - * What we're going to want to do is basically create the unsigned equivalent of - * our representation and pass that off to the wuint* functions. To do that - * we're going to do the following: - * - * - if the value is positive - * we can pass it directly off to the equivalent wuint - * - if the value is negative - * we do the following computation: - * mb + val + 1, where - * mb is the maximum unsigned value in that byte size - * val is the Javascript negative integer - * - * - * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If - * you do out the computations: - * - * 0xffff - 128 + 1 - * 0xffff - 127 - * 0xff80 - * - * You can then encode this value as the signed version. This is really rather - * hacky, but it should work and get the job done which is our goal here. - */ + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } -/* - * A series of checks to make sure we actually have a signed 32-bit number - */ -function verifsint(value, max, min) { - assert.ok(typeof (value) == 'number', - 'cannot write a non-number as a number'); + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } - assert.ok(value <= max, 'value larger than maximum allowed value'); + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } - assert.ok(value >= min, 'value smaller than minimum allowed value'); + ctx.seen.pop(); - assert.ok(Math.floor(value) === value, 'value has a fractional component'); + return reduceToSingleString(output, base, braces); } -function verifIEEE754(value, max, min) { - assert.ok(typeof (value) == 'number', - 'cannot write a non-number as a number'); - assert.ok(value <= max, 'value larger than maximum allowed value'); - - assert.ok(value >= min, 'value smaller than minimum allowed value'); +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); } -Buffer.prototype.writeInt8 = function(value, offset, noAssert) { - var buffer = this; - - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} - assert.ok(offset < buffer.length, - 'Trying to write beyond buffer length'); - verifsint(value, 0x7f, -0x80); +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} - if (value >= 0) { - buffer.writeUInt8(value, offset, noAssert); + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } } else { - buffer.writeUInt8(0xff + value + 1, offset, noAssert); + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } } -}; - -function writeInt16(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); - - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset + 1 < buffer.length, - 'Trying to write beyond buffer length'); - - verifsint(value, 0x7fff, -0x8000); + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; } - - if (value >= 0) { - writeUInt16(buffer, value, offset, isBigEndian, noAssert); - } else { - writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert); + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } } -} - -Buffer.prototype.writeInt16LE = function(value, offset, noAssert) { - writeInt16(this, value, offset, false, noAssert); -}; - -Buffer.prototype.writeInt16BE = function(value, offset, noAssert) { - writeInt16(this, value, offset, true, noAssert); -}; - -function writeInt32(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + return name + ': ' + str; +} - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - assert.ok(offset + 3 < buffer.length, - 'Trying to write beyond buffer length'); +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); - verifsint(value, 0x7fffffff, -0x80000000); + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; } - if (value >= 0) { - writeUInt32(buffer, value, offset, isBigEndian, noAssert); - } else { - writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert); - } + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } -Buffer.prototype.writeInt32LE = function(value, offset, noAssert) { - writeInt32(this, value, offset, false, noAssert); -}; - -Buffer.prototype.writeInt32BE = function(value, offset, noAssert) { - writeInt32(this, value, offset, true, noAssert); -}; -function writeFloat(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; - assert.ok(offset + 3 < buffer.length, - 'Trying to write beyond buffer length'); +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; - verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38); - } +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; - require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, - 23, 4); +function isString(arg) { + return typeof arg === 'string'; } +exports.isString = isString; -Buffer.prototype.writeFloatLE = function(value, offset, noAssert) { - writeFloat(this, value, offset, false, noAssert); -}; +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; -Buffer.prototype.writeFloatBE = function(value, offset, noAssert) { - writeFloat(this, value, offset, true, noAssert); -}; +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; -function writeDouble(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; - assert.ok(offset + 7 < buffer.length, - 'Trying to write beyond buffer length'); +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; - verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308); - } +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; - require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, - 52, 8); +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; -Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) { - writeDouble(this, value, offset, false, noAssert); -}; +exports.isBuffer = require('./support/isBuffer'); -Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) { - writeDouble(this, value, offset, true, noAssert); -}; +function objectToString(o) { + return Object.prototype.toString.call(o); +} -},{"./buffer_ieee754":1,"assert":6,"base64-js":4}],"buffer-browserify":[function(require,module,exports){ -module.exports=require('q9TxCC'); -},{}],4:[function(require,module,exports){ -(function (exports) { - 'use strict'; - var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} - function b64ToByteArray(b64) { - var i, j, l, tmp, placeHolders, arr; - - if (b64.length % 4 > 0) { - throw 'Invalid string. Length must be a multiple of 4'; - } - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64.indexOf('='); - placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0; +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; - // base64 is 4/3 + up to two characters of the original data - arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders); +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length; - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]); - arr.push((tmp & 0xFF0000) >> 16); - arr.push((tmp & 0xFF00) >> 8); - arr.push(tmp & 0xFF); - } +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; - if (placeHolders === 2) { - tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4); - arr.push(tmp & 0xFF); - } else if (placeHolders === 1) { - tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2); - arr.push((tmp >> 8) & 0xFF); - arr.push(tmp & 0xFF); - } - return arr; - } +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); - function uint8ToBase64(uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length; +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; - }; + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; - // go through the array every three bytes, we'll deal with trailing stuff later - for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { - temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output += tripletToBase64(temp); - } +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} - // pad the end with zeros, but make sure to not forget the extra bytes - switch (extraBytes) { - case 1: - temp = uint8[uint8.length - 1]; - output += lookup[temp >> 2]; - output += lookup[(temp << 4) & 0x3F]; - output += '=='; - break; - case 2: - temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]); - output += lookup[temp >> 10]; - output += lookup[(temp >> 4) & 0x3F]; - output += lookup[(temp << 2) & 0x3F]; - output += '='; - break; - } +}).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":31,"FWaASH":17,"inherits":16}],33:[function(require,module,exports){ +function replace(a, b) +{ + if (!b) + { + return a; + } + var key; + for (key in b) + { + if(b.hasOwnProperty(key)) + { + a[key] = b[key]; + } + } + + return a; +} exports.replace=replace; + +function add(a, b) +{ + if (!b) + { + return a; + } + var key; + for (key in b) + { + if(b.hasOwnProperty(key)) + { + if(typeof a[key] === 'undefined' || a[key]===null) + { + a[key] = b[key]; + } + } + } + return a; +} exports.add=add; + + +function extend(a, b, context, newobjs, aparent, aname, haveaparent) // context is anti circular references mechanism +{ + if (a==b){ return a;} + if (!b) { return a;} + + var key, clean_context=false, return_sublevel=false,b_pos; + if(!haveaparent){ aparent={'a':a}; aname='a'; } + if(!context){clean_context=true;context=[];newobjs=[];} + b_pos=context.indexOf(b); + if( b_pos==-1 ) {context.push(b);newobjs.push([aparent, aname]);} else { return newobjs[b_pos][0][ newobjs[b_pos][1] ]; } + + for (key in b) + { + if(b.hasOwnProperty(key)) + { + if(typeof a[key] === 'undefined') + { + if(typeof b[key] === 'object') + { + if( b[key] instanceof Array ) // http://javascript.crockford.com/remedial.html + {a[key] = extend([], b[key],context,newobjs,a,key,true);} + else if(b[key]===null) + {a[key] = null;} + else if( b[key] instanceof Date ) + { a[key]= new b[key].constructor();a[key].setTime(b[key].getTime()); } + else + { a[key] = extend({}, b[key],context,newobjs,a,key,true); /*a[key].constructor = b[key].constructor; a[key].prototype = b[key].prototype;*/ } + } + else + { a[key] = b[key]; } + } + else if(typeof a[key] === 'object' && a[key] !== null) + { a[key] = extend(a[key], b[key],context,newobjs,a,key,true); /*a[key].constructor = b[key].constructor; a[key].prototype = b[key].prototype;*/ } + else + { a[key] = b[key]; } + } + } + if(clean_context) {context=null;newobjs=null;} + if(!haveaparent) + { + aparent=null; + return a; + } + if(typeof a === 'object' && !(a instanceof Array) ) + { + /*a.constructor = b.constructor; + a.prototype = b.prototype*/; + } + return a; +} exports.extend=extend; + +function extenduptolevel(a, b, levels, context, newobjs, aparent, aname, haveaparent) +{ + if (a==b){ return a;} + if (!b){ return a;} + + var key, clean_context=false, return_sublevel=false; + if(!haveaparent){ aparent={'a':a}; aname='a'; } + if(!context){clean_context=true;context=[];newobjs=[];} + b_pos=context.indexOf(b); + if( b_pos==-1 ) {context.push(b);newobjs.push([aparent, aname]);} else { return newobjs[b_pos][0][ newobjs[b_pos][1] ]; } + + for (key in b) + { + if(b.hasOwnProperty(key)) + { + if(typeof a[key] === 'undefined') + { + if(typeof b[key] === 'object' && levels>0) + { + if( b[key] instanceof Array ) // http://javascript.crockford.com/remedial.html + { a[key] = extenduptolevel([], b[key],levels-1,context,newobjs,a,key,true); } + else if(b[key]===null) + { a[key] = null; } + else if( b[key] instanceof Date ) + { a[key]= new b[key].constructor();a[key].setTime(b[key].getTime()); } + else + { a[key] = extenduptolevel({}, b[key],levels-1,context,newobjs,a,key,true); } + } + else + { a[key] = b[key]; } + } + else if(typeof a[key] === 'object' && a[key] !== null && levels>0) + { a[key] = extenduptolevel(a[key], b[key],levels-1,context,newobjs,a,key,true); } + else + { a[key] = b[key]; } + } + } + if(clean_context) {context=null;newobjs=null;} + + if(!haveaparent) + { + aparent=null; + return a; + } + if(typeof a === 'object' && !(a instanceof Array) ) + { + /*a.constructor = b.constructor; + a.prototype = b.prototype;*/ + } + return a; +} exports.extenduptolevel=extenduptolevel; + +function clone(obj) +{ + if (typeof obj === 'object') + { + if (obj ===null ) { return null; } + if (obj instanceof Array ) + { return extend([], obj); } + else if( obj instanceof Date ) + { + var t= new obj.constructor(); + t.setTime(obj.getTime()); + return t; + } + else + { return extend({}, obj); } + } + return obj; +} exports.clone=clone; + +function cloneextend(obj,exteddata) +{ + if (typeof obj === 'object') + { + if (obj ===null ) { return null; } + return extend(clone(obj),exteddata); + } + return obj; +} exports.cloneextend=cloneextend; + + +function cloneuptolevel(obj,level) // clone only numlevels levels other levels leave references +{ + if (typeof obj === 'object') + { + if (obj ===null ) { return null; } + if (obj instanceof Array ) { return extenduptolevel([], obj,level); } + return extenduptolevel({}, obj,level); + } + return obj; +} exports.cloneuptolevel=cloneuptolevel; + +function foreach(object, block, context) +{ + if (object) + { + if (typeof object === "object" && object instanceof Array) + return object.forEach(object, block, context) + else //if (typeof object === "object") // or (object instanceof Function)... + { + if(object) + for (var key in object) + { + if(object.hasOwnProperty(key)) + { + if(block.call(context, object[key], key, object)===false)break; + } + } + } + } +} exports.foreach=foreach; + +/* + hasbugs and useless, yet interesting maybe developed later for dot pathed object transformation: + + { + 'foo.bar':'bluebar', + 'foo.color':'blue' + } + + transforemed to + + { + foo: + { + bar:'bluebar', + color:'blue' + } + } + + like: + + var config={}; + cloneextend.dotpath(config,{ + 'foo.bar':'bluebar', + 'foo.color':'blue' + }) + + // + function dotpath(data,dotkeys,preserve) + { + if(!preserve)preserve=false; + var create=!preserve; + if(create) if(!data) data={}; + var keys= dotkeys.split("."),value=data; + for (var i=0;i + * @license MIT + * + * The MIT License (MIT) + * + * Copyright (c) 2013 Viacheslav Lotsmanov + * + * 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. + */ - return output; +/** + * Extening object that entered in first argument. + * Returns extended object or false if have no target object or incorrect type. + * If you wish to clone object, simply use that: + * deepExtend({}, yourObj_1, [yourObj_N]) - first arg is new empty object + */ +var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { + if (arguments.length < 1 || typeof arguments[0] !== 'object') { + return false; } - module.exports.toByteArray = b64ToByteArray; - module.exports.fromByteArray = uint8ToBase64; -}()); - -},{}],5:[function(require,module,exports){ - - -// -// The shims in this file are not fully implemented shims for the ES5 -// features, but do work for the particular usecases there is in -// the other modules. -// - -var toString = Object.prototype.toString; -var hasOwnProperty = Object.prototype.hasOwnProperty; - -// Array.isArray is supported in IE9 -function isArray(xs) { - return toString.call(xs) === '[object Array]'; -} -exports.isArray = typeof Array.isArray === 'function' ? Array.isArray : isArray; - -// Array.prototype.indexOf is supported in IE9 -exports.indexOf = function indexOf(xs, x) { - if (xs.indexOf) return xs.indexOf(x); - for (var i = 0; i < xs.length; i++) { - if (x === xs[i]) return i; - } - return -1; -}; - -// Array.prototype.filter is supported in IE9 -exports.filter = function filter(xs, fn) { - if (xs.filter) return xs.filter(fn); - var res = []; - for (var i = 0; i < xs.length; i++) { - if (fn(xs[i], i, xs)) res.push(xs[i]); - } - return res; -}; - -// Array.prototype.forEach is supported in IE9 -exports.forEach = function forEach(xs, fn, self) { - if (xs.forEach) return xs.forEach(fn, self); - for (var i = 0; i < xs.length; i++) { - fn.call(self, xs[i], i, xs); - } -}; - -// Array.prototype.map is supported in IE9 -exports.map = function map(xs, fn) { - if (xs.map) return xs.map(fn); - var out = new Array(xs.length); - for (var i = 0; i < xs.length; i++) { - out[i] = fn(xs[i], i, xs); - } - return out; -}; - -// Array.prototype.reduce is supported in IE9 -exports.reduce = function reduce(array, callback, opt_initialValue) { - if (array.reduce) return array.reduce(callback, opt_initialValue); - var value, isValueSet = false; - - if (2 < arguments.length) { - value = opt_initialValue; - isValueSet = true; - } - for (var i = 0, l = array.length; l > i; ++i) { - if (array.hasOwnProperty(i)) { - if (isValueSet) { - value = callback(value, array[i], i, array); - } - else { - value = array[i]; - isValueSet = true; - } - } - } - - return value; -}; - -// String.prototype.substr - negative index don't work in IE8 -if ('ab'.substr(-1) !== 'b') { - exports.substr = function (str, start, length) { - // did we get a negative start, calculate how much it is from the beginning of the string - if (start < 0) start = str.length + start; - - // call the original function - return str.substr(start, length); - }; -} else { - exports.substr = function (str, start, length) { - return str.substr(start, length); - }; -} - -// String.prototype.trim is supported in IE9 -exports.trim = function (str) { - if (str.trim) return str.trim(); - return str.replace(/^\s+|\s+$/g, ''); -}; - -// Function.prototype.bind is supported in IE9 -exports.bind = function () { - var args = Array.prototype.slice.call(arguments); - var fn = args.shift(); - if (fn.bind) return fn.bind.apply(fn, args); - var self = args.shift(); - return function () { - fn.apply(self, args.concat([Array.prototype.slice.call(arguments)])); - }; -}; - -// Object.create is supported in IE9 -function create(prototype, properties) { - var object; - if (prototype === null) { - object = { '__proto__' : null }; - } - else { - if (typeof prototype !== 'object') { - throw new TypeError( - 'typeof prototype[' + (typeof prototype) + '] != \'object\'' - ); - } - var Type = function () {}; - Type.prototype = prototype; - object = new Type(); - object.__proto__ = prototype; - } - if (typeof properties !== 'undefined' && Object.defineProperties) { - Object.defineProperties(object, properties); - } - return object; -} -exports.create = typeof Object.create === 'function' ? Object.create : create; - -// Object.keys and Object.getOwnPropertyNames is supported in IE9 however -// they do show a description and number property on Error objects -function notObject(object) { - return ((typeof object != "object" && typeof object != "function") || object === null); -} - -function keysShim(object) { - if (notObject(object)) { - throw new TypeError("Object.keys called on a non-object"); - } - - var result = []; - for (var name in object) { - if (hasOwnProperty.call(object, name)) { - result.push(name); - } - } - return result; -} - -// getOwnPropertyNames is almost the same as Object.keys one key feature -// is that it returns hidden properties, since that can't be implemented, -// this feature gets reduced so it just shows the length property on arrays -function propertyShim(object) { - if (notObject(object)) { - throw new TypeError("Object.getOwnPropertyNames called on a non-object"); - } - - var result = keysShim(object); - if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) { - result.push('length'); - } - return result; -} - -var keys = typeof Object.keys === 'function' ? Object.keys : keysShim; -var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? - Object.getOwnPropertyNames : propertyShim; - -if (new Error().hasOwnProperty('description')) { - var ERROR_PROPERTY_FILTER = function (obj, array) { - if (toString.call(obj) === '[object Error]') { - array = exports.filter(array, function (name) { - return name !== 'description' && name !== 'number' && name !== 'message'; - }); - } - return array; - }; - - exports.keys = function (object) { - return ERROR_PROPERTY_FILTER(object, keys(object)); - }; - exports.getOwnPropertyNames = function (object) { - return ERROR_PROPERTY_FILTER(object, getOwnPropertyNames(object)); - }; -} else { - exports.keys = keys; - exports.getOwnPropertyNames = getOwnPropertyNames; -} - -// Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements -function valueObject(value, key) { - return { value: value[key] }; -} - -if (typeof Object.getOwnPropertyDescriptor === 'function') { - try { - Object.getOwnPropertyDescriptor({'a': 1}, 'a'); - exports.getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - } catch (e) { - // IE8 dom element issue - use a try catch and default to valueObject - exports.getOwnPropertyDescriptor = function (value, key) { - try { - return Object.getOwnPropertyDescriptor(value, key); - } catch (e) { - return valueObject(value, key); - } - }; - } -} else { - exports.getOwnPropertyDescriptor = valueObject; -} - -},{}],6:[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. - -// UTILITY -var util = require('util'); -var shims = require('_shims'); -var pSlice = Array.prototype.slice; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - this.message = options.message || getMessage(this); -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; -} - -function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} - -function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try { - var ka = shims.keys(a), - kb = shims.keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + if (arguments.length < 2) return arguments[0]; -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; + var target = arguments[0]; -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } + // convert arguments to array and cut off target object + var args = Array.prototype.slice.call(arguments, 1); - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } + var key, val, src, clone, tmpBuf; - return false; -} + args.forEach(function (obj) { + if (typeof obj !== 'object') return; -function _throws(shouldThrow, block, expected, message) { - var actual; + for (key in obj) { + if ( ! (key in obj)) continue; - if (util.isString(expected)) { - message = expected; - expected = null; - } + src = target[key]; + val = obj[key]; - try { - block(); - } catch (e) { - actual = e; - } + if (val === target) continue; - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); + if (typeof val !== 'object' || val === null) { + target[key] = val; + continue; + } else if (val instanceof Buffer) { + tmpBuf = new Buffer(val.length); + val.copy(tmpBuf); + target[key] = tmpBuf; + continue; + } else if (val instanceof Date) { + target[key] = new Date(val.getTime()); + continue; + } - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } + if (typeof src !== 'object' || src === null) { + clone = (Array.isArray(val)) ? [] : {}; + target[key] = deepExtend(clone, val); + continue; + } - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } + if (Array.isArray(val)) { + clone = (Array.isArray(src)) ? src : []; + } else { + clone = (!Array.isArray(src)) ? src : {}; + } - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } + target[key] = deepExtend(clone, val); + } + }); + + return target; } -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); +}).call(this,require("buffer").Buffer) +},{"buffer":1}],35:[function(require,module,exports){ +/*! + * EventEmitter2 + * https://github.com/hij1nx/EventEmitter2 + * + * Copyright (c) 2013 hij1nx + * Licensed under the MIT license. + */ +;!function(undefined) { -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; + var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + var defaultMaxListeners = 10; -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; + function init() { + this._events = {}; + if (this._conf) { + configure.call(this, this._conf); + } + } -assert.ifError = function(err) { if (err) {throw err;}}; -},{"_shims":5,"util":7}],7:[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. + function configure(conf) { + if (conf) { -var shims = require('_shims'); + this._conf = conf; -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } + conf.delimiter && (this.delimiter = conf.delimiter); + conf.maxListeners && (this._events.maxListeners = conf.maxListeners); + conf.wildcard && (this.wildcard = conf.wildcard); + conf.newListener && (this.newListener = conf.newListener); - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); + if (this.wildcard) { + this.listenerTree = {}; + } } } - return str; -}; -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); + function EventEmitter(conf) { + this._events = {}; + this.newListener = false; + configure.call(this, conf); } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; + // + // Attention, function return type now is array, always ! + // It has zero elements if no any matches found and one or more + // elements (leafs) if there are matches + // + function searchListenerTree(handlers, type, tree, i) { + if (!tree) { + return []; + } + var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, + typeLength = type.length, currentType = type[i], nextType = type[i+1]; + if (i === typeLength && tree._listeners) { + // + // If at the end of the event(s) list and the tree has listeners + // invoke those listeners. + // + if (typeof tree._listeners === 'function') { + handlers && handlers.push(tree._listeners); + return [tree]; + } else { + for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { + handlers && handlers.push(tree._listeners[leaf]); + } + return [tree]; + } + } -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + if ((currentType === '*' || currentType === '**') || tree[currentType]) { + // + // If the event emitted is '*' at this part + // or there is a concrete match at this patch + // + if (currentType === '*') { + for (branch in tree) { + if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); + } + } + return listeners; + } else if(currentType === '**') { + endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); + if(endReached && tree._listeners) { + // The next element has a _listeners, add it to the handlers. + listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); + } - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} + for (branch in tree) { + if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { + if(branch === '*' || branch === '**') { + if(tree[branch]._listeners && !endReached) { + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); + } + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); + } else if(branch === nextType) { + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); + } else { + // No match on this one, shift into the tree but not in the type array. + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); + } + } + } + return listeners; + } + listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); + } -function stylizeNoColor(str, styleType) { - return str; -} + xTree = tree['*']; + if (xTree) { + // + // If the listener tree will allow any match for this part, + // then recursively explore all branches of the tree + // + searchListenerTree(handlers, type, xTree, i+1); + } + xxTree = tree['**']; + if(xxTree) { + if(i < typeLength) { + if(xxTree._listeners) { + // If we have a listener on a '**', it will catch all, so add its handler. + searchListenerTree(handlers, type, xxTree, typeLength); + } -function arrayToHash(array) { - var hash = {}; + // Build arrays of matching next branches and others. + for(branch in xxTree) { + if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { + if(branch === nextType) { + // We know the next element will match, so jump twice. + searchListenerTree(handlers, type, xxTree[branch], i+2); + } else if(branch === currentType) { + // Current node matches, move into the tree. + searchListenerTree(handlers, type, xxTree[branch], i+1); + } else { + isolatedBranch = {}; + isolatedBranch[branch] = xxTree[branch]; + searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); + } + } + } + } else if(xxTree._listeners) { + // We have reached the end and still on a '**' + searchListenerTree(handlers, type, xxTree, typeLength); + } else if(xxTree['*'] && xxTree['*']._listeners) { + searchListenerTree(handlers, type, xxTree['*'], typeLength); + } + } - shims.forEach(array, function(val, idx) { - hash[val] = true; - }); + return listeners; + } - return hash; -} + function growListenerTree(type, listener) { + type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); + // + // Looks for two consecutive '**', if so, don't add the event at all. + // + for(var i = 0, len = type.length; i+1 < len; i++) { + if(type[i] === '**' && type[i+1] === '**') { + return; + } } - return ret; - } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + var tree = this.listenerTree; + var name = type.shift(); - // Look up the keys of the object. - var keys = shims.keys(value); - var visibleKeys = arrayToHash(keys); + while (name) { - if (ctx.showHidden) { - keys = shims.getOwnPropertyNames(value); - } + if (!tree[name]) { + tree[name] = {}; + } - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } + tree = tree[name]; - var base = '', array = false, braces = ['{', '}']; + if (type.length === 0) { - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } + if (!tree._listeners) { + tree._listeners = listener; + } + else if(typeof tree._listeners === 'function') { + tree._listeners = [tree._listeners, listener]; + } + else if (isArray(tree._listeners)) { - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + tree._listeners.push(listener); - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + if (!tree._listeners.warned) { - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + var m = defaultMaxListeners; - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + if (typeof this._events.maxListeners !== 'undefined') { + m = this._events.maxListeners; + } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + if (m > 0 && tree._listeners.length > m) { - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); + tree._listeners.warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + tree._listeners.length); + console.trace(); + } + } + } + return true; + } + name = type.shift(); } + return true; } - ctx.seen.push(value); + // 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. + // + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } + EventEmitter.prototype.delimiter = '.'; - ctx.seen.pop(); + EventEmitter.prototype.setMaxListeners = function(n) { + this._events || init.call(this); + this._events.maxListeners = n; + if (!this._conf) this._conf = {}; + this._conf.maxListeners = n; + }; - return reduceToSingleString(output, base, braces); -} + EventEmitter.prototype.event = ''; + EventEmitter.prototype.once = function(event, fn) { + this.many(event, 1, fn); + return this; + }; -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} + EventEmitter.prototype.many = function(event, ttl, fn) { + var self = this; + if (typeof fn !== 'function') { + throw new Error('many only accepts instances of Function'); + } -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} + function listener() { + if (--ttl === 0) { + self.off(event, listener); + } + fn.apply(this, arguments); + } + listener._origin = fn; -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } + this.on(event, listener); - shims.forEach(keys, function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} + return self; + }; + + EventEmitter.prototype.emit = function() { + + this._events || init.call(this); + var type = arguments[0]; -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = shims.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); + if (type === 'newListener' && !this.newListener) { + if (!this._events.newListener) { return false; } } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (shims.indexOf(ctx.seen, desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); + // Loop through the *_all* functions and invoke them. + if (this._all) { + var l = arguments.length; + var args = new Array(l - 1); + for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; + for (i = 0, l = this._all.length; i < l; i++) { + this.event = type; + this._all[i].apply(this, args); } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); + } + + // If there is no 'error' event listener then throw. + if (type === 'error') { + + if (!this._all && + !this._events.error && + !(this.wildcard && this.listenerTree.error)) { + + if (arguments[1] instanceof Error) { + throw arguments[1]; // Unhandled 'error' event } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); + throw new Error("Uncaught, unspecified 'error' event."); } + return false; } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); } - } - - return name + ': ' + str; -} + var handler; -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = shims.reduce(output, function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); + if(this.wildcard) { + handler = []; + var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + searchListenerTree.call(this, handler, ns, this.listenerTree, 0); + } + else { + handler = this._events[type]; + } - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } + if (typeof handler === 'function') { + this.event = type; + if (arguments.length === 1) { + handler.call(this); + } + else if (arguments.length > 1) + switch (arguments.length) { + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + var l = arguments.length; + var args = new Array(l - 1); + for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; + handler.apply(this, args); + } + return true; + } + else if (handler) { + var l = arguments.length; + var args = new Array(l - 1); + for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} + var listeners = handler.slice(); + for (var i = 0, l = listeners.length; i < l; i++) { + this.event = type; + listeners[i].apply(this, args); + } + return (listeners.length > 0) || !!this._all; + } + else { + return !!this._all; + } + }; -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return shims.isArray(ar); -} -exports.isArray = isArray; + EventEmitter.prototype.on = function(type, listener) { -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; + if (typeof type === 'function') { + this.onAny(type); + return this; + } -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + if (typeof listener !== 'function') { + throw new Error('on only accepts instances of Function'); + } + this._events || init.call(this); -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; + // To avoid recursion in the case that type == "newListeners"! Before + // adding it to the listeners, first emit "newListeners". + this.emit('newListener', type, listener); -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; + if(this.wildcard) { + growListenerTree.call(this, type, listener); + return this; + } -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; + if (!this._events[type]) { + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + } + else if(typeof this._events[type] === 'function') { + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + } + else if (isArray(this._events[type])) { + // If we've already got an array, just append. + this._events[type].push(listener); -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; + // Check for listener leak + if (!this._events[type].warned) { -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; + var m = defaultMaxListeners; -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; + if (typeof this._events.maxListeners !== 'undefined') { + m = this._events.maxListeners; + } -function isObject(arg) { - return typeof arg === 'object' && arg; -} -exports.isObject = isObject; + if (m > 0 && this._events[type].length > m) { -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + console.trace(); + } + } + } + return this; + }; -function isError(e) { - return isObject(e) && objectToString(e) === '[object Error]'; -} -exports.isError = isError; + EventEmitter.prototype.onAny = function(fn) { -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; + if (typeof fn !== 'function') { + throw new Error('onAny only accepts instances of Function'); + } -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; + if(!this._all) { + this._all = []; + } -function isBuffer(arg) { - return arg instanceof Buffer; -} -exports.isBuffer = isBuffer; + // Add the function to the event listener collection. + this._all.push(fn); + return this; + }; -function objectToString(o) { - return Object.prototype.toString.call(o); -} + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + EventEmitter.prototype.off = function(type, listener) { + if (typeof listener !== 'function') { + throw new Error('removeListener only takes instances of Function'); + } -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} + var handlers,leafs=[]; + if(this.wildcard) { + var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); + } + else { + // does not use listeners(), so no side effect of creating _events[type] + if (!this._events[type]) return this; + handlers = this._events[type]; + leafs.push({_listeners:handlers}); + } -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + for (var iLeaf=0; iLeaf 0) { + fns = this._all; + for(i = 0, l = fns.length; i < l; i++) { + if(fn === fns[i]) { + fns.splice(i, 1); + return this; + } + } + } else { + this._all = []; + } + return this; + }; -},{"_shims":5}]},{},[]) -;;module.exports=require("buffer-browserify") + EventEmitter.prototype.removeListener = EventEmitter.prototype.off; -},{}],47:[function(require,module,exports){ -// shim for using process in browser + EventEmitter.prototype.removeAllListeners = function(type) { + if (arguments.length === 0) { + !this._events || init.call(this); + return this; + } -var process = module.exports = {}; + if(this.wildcard) { + var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); -process.nextTick = (function () { - var canSetImmediate = typeof window !== 'undefined' - && window.setImmediate; - var canPost = typeof window !== 'undefined' - && window.postMessage && window.addEventListener - ; + for (var iLeaf=0; iLeaf 0) { - var fn = queue.shift(); - fn(); - } - } - }, true); + this._events || init.call(this); - return function nextTick(fn) { - queue.push(fn); - window.postMessage('process-tick', '*'); - }; + if (!this._events[type]) this._events[type] = []; + if (!isArray(this._events[type])) { + this._events[type] = [this._events[type]]; } + return this._events[type]; + }; - return function nextTick(fn) { - setTimeout(fn, 0); - }; -})(); + EventEmitter.prototype.listenersAny = function() { -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; + if(this._all) { + return this._all; + } + else { + return []; + } -process.binding = function (name) { - throw new Error('process.binding is not supported'); -} + }; -// TODO(shtylman) -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(function() { + return EventEmitter; + }); + } else if (typeof exports === 'object') { + // CommonJS + exports.EventEmitter2 = EventEmitter; + } + else { + // Browser global. + window.EventEmitter2 = EventEmitter; + } +}(); -},{}],48:[function(require,module,exports){ +},{}],36:[function(require,module,exports){ //! moment.js //! version : 2.5.1 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors @@ -12838,11 +10100,11 @@ process.chdir = function (dir) { } }).call(this); -},{}],49:[function(require,module,exports){ +},{}],37:[function(require,module,exports){ module.exports = require('./lib/'); -},{"./lib/":50}],50:[function(require,module,exports){ +},{"./lib/":38}],38:[function(require,module,exports){ /** * Module dependencies. @@ -12931,7 +10193,7 @@ exports.connect = lookup; exports.Manager = require('./manager'); exports.Socket = require('./socket'); -},{"./manager":51,"./socket":53,"./url":54,"debug":57,"socket.io-parser":88}],51:[function(require,module,exports){ +},{"./manager":39,"./socket":41,"./url":42,"debug":45,"socket.io-parser":76}],39:[function(require,module,exports){ /** * Module dependencies. @@ -13391,7 +10653,7 @@ Manager.prototype.onreconnect = function(){ this.emitAll('reconnect', attempt); }; -},{"./on":52,"./socket":53,"./url":54,"component-bind":55,"component-emitter":56,"debug":57,"engine.io-client":58,"object-component":85,"socket.io-parser":88}],52:[function(require,module,exports){ +},{"./on":40,"./socket":41,"./url":42,"component-bind":43,"component-emitter":44,"debug":45,"engine.io-client":46,"object-component":73,"socket.io-parser":76}],40:[function(require,module,exports){ /** * Module exports. @@ -13417,7 +10679,7 @@ function on(obj, ev, fn) { }; } -},{}],53:[function(require,module,exports){ +},{}],41:[function(require,module,exports){ /** * Module dependencies. @@ -13797,8 +11059,9 @@ Socket.prototype.disconnect = function(){ return this; }; -},{"./on":52,"component-bind":55,"component-emitter":56,"debug":57,"has-binary":82,"indexof":84,"socket.io-parser":88,"to-array":92}],54:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; +},{"./on":40,"component-bind":43,"component-emitter":44,"debug":45,"has-binary":70,"indexof":72,"socket.io-parser":76,"to-array":80}],42:[function(require,module,exports){ +(function (global){ + /** * Module dependencies. */ @@ -13870,7 +11133,8 @@ function url(uri, loc){ return obj; } -},{"debug":57,"parseuri":86}],55:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"debug":45,"parseuri":74}],43:[function(require,module,exports){ /** * Slice reference. */ @@ -13895,7 +11159,7 @@ module.exports = function(obj, fn){ } }; -},{}],56:[function(require,module,exports){ +},{}],44:[function(require,module,exports){ /** * Expose `Emitter`. @@ -14061,7 +11325,7 @@ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; -},{}],57:[function(require,module,exports){ +},{}],45:[function(require,module,exports){ /** * Expose `debug()` as the module. @@ -14200,11 +11464,11 @@ try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} -},{}],58:[function(require,module,exports){ +},{}],46:[function(require,module,exports){ module.exports = require('./lib/'); -},{"./lib/":59}],59:[function(require,module,exports){ +},{"./lib/":47}],47:[function(require,module,exports){ module.exports = require('./socket'); @@ -14216,8 +11480,9 @@ module.exports = require('./socket'); */ module.exports.parser = require('engine.io-parser'); -},{"./socket":60,"engine.io-parser":69}],60:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{"./socket":48,"engine.io-parser":57}],48:[function(require,module,exports){ +(function (global){ +/** * Module dependencies. */ @@ -14866,7 +12131,8 @@ Socket.prototype.filterUpgrades = function (upgrades) { return filteredUpgrades; }; -},{"./transport":61,"./transports":62,"component-emitter":56,"debug":57,"engine.io-parser":69,"indexof":84,"parsejson":78,"parseqs":79,"parseuri":80}],61:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./transport":49,"./transports":50,"component-emitter":44,"debug":45,"engine.io-parser":57,"indexof":72,"parsejson":66,"parseqs":67,"parseuri":68}],49:[function(require,module,exports){ /** * Module dependencies. */ @@ -15018,8 +12284,9 @@ Transport.prototype.onClose = function () { this.emit('close'); }; -},{"component-emitter":56,"engine.io-parser":69}],62:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{"component-emitter":44,"engine.io-parser":57}],50:[function(require,module,exports){ +(function (global){ +/** * Module dependencies */ @@ -15073,8 +12340,10 @@ function polling(opts){ } } -},{"./polling-jsonp":63,"./polling-xhr":64,"./websocket":66,"xmlhttprequest":67}],63:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./polling-jsonp":51,"./polling-xhr":52,"./websocket":54,"xmlhttprequest":55}],51:[function(require,module,exports){ +(function (global){ + /** * Module requirements. */ @@ -15307,8 +12576,10 @@ JSONPPolling.prototype.doWrite = function (data, fn) { } }; -},{"./polling":65,"component-inherit":68}],64:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./polling":53,"component-inherit":56}],52:[function(require,module,exports){ +(function (global){ +/** * Module requirements. */ @@ -15660,7 +12931,8 @@ function unloadHandler() { } } -},{"./polling":65,"component-emitter":56,"component-inherit":68,"debug":57,"xmlhttprequest":67}],65:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./polling":53,"component-emitter":44,"component-inherit":56,"debug":45,"xmlhttprequest":55}],53:[function(require,module,exports){ /** * Module dependencies. */ @@ -15907,7 +13179,7 @@ Polling.prototype.uri = function(){ return schema + '://' + this.hostname + port + this.path + query; }; -},{"../transport":61,"component-inherit":68,"debug":57,"engine.io-parser":69,"parseqs":79,"xmlhttprequest":67}],66:[function(require,module,exports){ +},{"../transport":49,"component-inherit":56,"debug":45,"engine.io-parser":57,"parseqs":67,"xmlhttprequest":55}],54:[function(require,module,exports){ /** * Module dependencies. */ @@ -16138,7 +13410,7 @@ WS.prototype.check = function(){ return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name); }; -},{"../transport":61,"component-inherit":68,"debug":57,"engine.io-parser":69,"parseqs":79,"ws":81}],67:[function(require,module,exports){ +},{"../transport":49,"component-inherit":56,"debug":45,"engine.io-parser":57,"parseqs":67,"ws":69}],55:[function(require,module,exports){ // browser shim for xmlhttprequest module var hasCORS = require('has-cors'); @@ -16176,7 +13448,7 @@ module.exports = function(opts) { } } -},{"has-cors":76}],68:[function(require,module,exports){ +},{"has-cors":64}],56:[function(require,module,exports){ module.exports = function(a, b){ var fn = function(){}; @@ -16184,8 +13456,9 @@ module.exports = function(a, b){ a.prototype = new fn; a.prototype.constructor = a; }; -},{}],69:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{}],57:[function(require,module,exports){ +(function (global){ +/** * Module dependencies. */ @@ -16752,7 +14025,8 @@ exports.decodePayloadAsBinary = function (data, binaryType, callback) { }); }; -},{"./keys":70,"after":71,"arraybuffer.slice":72,"base64-arraybuffer":73,"blob":74,"utf8":75}],70:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./keys":58,"after":59,"arraybuffer.slice":60,"base64-arraybuffer":61,"blob":62,"utf8":63}],58:[function(require,module,exports){ /** * Gets the keys for an object. @@ -16773,7 +14047,7 @@ module.exports = Object.keys || function keys (obj){ return arr; }; -},{}],71:[function(require,module,exports){ +},{}],59:[function(require,module,exports){ module.exports = after function after(count, callback, err_cb) { @@ -16803,7 +14077,7 @@ function after(count, callback, err_cb) { function noop() {} -},{}],72:[function(require,module,exports){ +},{}],60:[function(require,module,exports){ /** * An abstraction for slicing an arraybuffer even when * ArrayBuffer.prototype.slice is not supported @@ -16834,7 +14108,7 @@ module.exports = function(arraybuffer, start, end) { return result.buffer; }; -},{}],73:[function(require,module,exports){ +},{}],61:[function(require,module,exports){ /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer @@ -16895,8 +14169,9 @@ module.exports = function(arraybuffer, start, end) { }; })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); -},{}],74:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{}],62:[function(require,module,exports){ +(function (global){ +/** * Create a blob builder even when vendor prefixes exist */ @@ -16946,8 +14221,10 @@ module.exports = (function() { } })(); -},{}],75:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/*! http://mths.be/utf8js v2.0.0 by @mathias */ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],63:[function(require,module,exports){ +(function (global){ +/*! http://mths.be/utf8js v2.0.0 by @mathias */ ;(function(root) { // Detect free variables `exports` @@ -17187,7 +14464,8 @@ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? }(this)); -},{}],76:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],64:[function(require,module,exports){ /** * Module dependencies. @@ -17212,7 +14490,7 @@ try { module.exports = false; } -},{"global":77}],77:[function(require,module,exports){ +},{"global":65}],65:[function(require,module,exports){ /** * Returns `this`. Execute this without a "context" (i.e. without it being @@ -17222,8 +14500,9 @@ try { module.exports = (function () { return this; })(); -},{}],78:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{}],66:[function(require,module,exports){ +(function (global){ +/** * JSON parse. * * @see Based on jQuery#parseJSON (MIT) and JSON2 @@ -17255,7 +14534,8 @@ module.exports = function parsejson(data) { return (new Function('return ' + data))(); } }; -},{}],79:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],67:[function(require,module,exports){ /** * Compiles a querystring * Returns string representation of the object @@ -17294,7 +14574,7 @@ exports.decode = function(qs){ return qry; }; -},{}],80:[function(require,module,exports){ +},{}],68:[function(require,module,exports){ /** * Parses an URI * @@ -17335,7 +14615,7 @@ module.exports = function parseuri(str) { return uri; }; -},{}],81:[function(require,module,exports){ +},{}],69:[function(require,module,exports){ /** * Module dependencies. @@ -17380,8 +14660,9 @@ function ws(uri, protocols, opts) { if (WebSocket) ws.prototype = WebSocket.prototype; -},{}],82:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; +},{}],70:[function(require,module,exports){ +(function (global){ + /* * Module requirements. */ @@ -17440,12 +14721,13 @@ function hasBinary(data) { return _hasBinary(data); } -},{"isarray":83}],83:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"isarray":71}],71:[function(require,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; -},{}],84:[function(require,module,exports){ +},{}],72:[function(require,module,exports){ var indexOf = [].indexOf; @@ -17456,7 +14738,7 @@ module.exports = function(arr, obj){ } return -1; }; -},{}],85:[function(require,module,exports){ +},{}],73:[function(require,module,exports){ /** * HOP ref. @@ -17541,7 +14823,7 @@ exports.length = function(obj){ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; -},{}],86:[function(require,module,exports){ +},{}],74:[function(require,module,exports){ /** * Parses an URI * @@ -17568,8 +14850,9 @@ module.exports = function parseuri(str) { return uri; }; -},{}],87:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/*global Blob,File*/ +},{}],75:[function(require,module,exports){ +(function (global){ +/*global Blob,File*/ /** * Module requirements @@ -17711,7 +14994,8 @@ exports.removeBlobs = function(data, callback) { } }; -},{"./is-buffer":89,"isarray":90}],88:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./is-buffer":77,"isarray":78}],76:[function(require,module,exports){ /** * Module dependencies. @@ -18109,8 +15393,9 @@ function error(data){ }; } -},{"./binary":87,"./is-buffer":89,"component-emitter":56,"debug":57,"isarray":90,"json3":91}],89:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; +},{"./binary":75,"./is-buffer":77,"component-emitter":44,"debug":45,"isarray":78,"json3":79}],77:[function(require,module,exports){ +(function (global){ + module.exports = isBuf; /** @@ -18124,9 +15409,10 @@ function isBuf(obj) { (global.ArrayBuffer && obj instanceof ArrayBuffer); } -},{}],90:[function(require,module,exports){ -module.exports=require(83) -},{}],91:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],78:[function(require,module,exports){ +module.exports=require(71) +},{}],79:[function(require,module,exports){ /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */ ;(function (window) { // Convenience aliases. @@ -18989,7 +16275,7 @@ module.exports=require(83) } }(this)); -},{}],92:[function(require,module,exports){ +},{}],80:[function(require,module,exports){ module.exports = toArray function toArray(list, index) { @@ -19004,7 +16290,7 @@ function toArray(list, index) { return array } -},{}],93:[function(require,module,exports){ +},{}],81:[function(require,module,exports){ // Underscore.js 1.5.2 // http://underscorejs.org // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors @@ -20282,11 +17568,11 @@ function toArray(list, index) { }).call(this); -},{}],94:[function(require,module,exports){ +},{}],82:[function(require,module,exports){ module.exports={ "name": "joola.sdk", "preferGlobal": false, - "version": "0.7.13", + "version": "0.7.14", "author": "Joola ", "description": "joola's software development kit (SDK)", "engine": "node >= 0.10.x", @@ -20342,7 +17628,7 @@ module.exports={ "license": "GPL-3.0" } -},{}],95:[function(require,module,exports){ +},{}],83:[function(require,module,exports){ /** * @title joola/lib/sdk/common/api * @copyright (c) Joola Smart Solutions, Ltd. @@ -20648,7 +17934,7 @@ joola.events.on('rpc:done', function () { joola.usage = {currentCalls: 0}; joola.usage.currentCalls--; }); -},{"../index":102,"http":28,"https":12,"querystring":13,"url":17}],96:[function(require,module,exports){ +},{"../index":90,"http":11,"https":15,"querystring":21,"url":30}],84:[function(require,module,exports){ /** * joola * @@ -20774,7 +18060,7 @@ dispatch.buildstub = function (callback) { }; -},{"../index":102,"cloneextend":1,"url":17}],97:[function(require,module,exports){ +},{"../index":90,"cloneextend":33,"url":30}],85:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -20794,8 +18080,9 @@ var _events = new EventEmitter2({wildcard: true, newListener: true}); _events._id = 'events'; module.exports = exports = _events; -},{"../index":102,"eventemitter2":3}],98:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{"../index":90,"eventemitter2":35}],86:[function(require,module,exports){ +(function (global){ +/** * @title joola * @overview the open-source data analytics framework * @copyright Joola Smart Solutions, Ltd. @@ -20821,8 +18108,10 @@ joola.timezone = function (tz) { return offset; }; -},{"../index":102}],99:[function(require,module,exports){ -var Buffer=require("__browserify_Buffer").Buffer;/*jshint -W083 */ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../index":90}],87:[function(require,module,exports){ +(function (Buffer){ +/*jshint -W083 */ /** * @title joola @@ -21004,7 +18293,8 @@ common.ensureLength = function (string, length) { } return string; }; -},{"../index":102,"./modifiers":101,"__browserify_Buffer":46,"cloneextend":1,"crypto":23,"deep-extend":2,"underscore":93,"util":18}],100:[function(require,module,exports){ +}).call(this,require("buffer").Buffer) +},{"../index":90,"./modifiers":89,"buffer":1,"cloneextend":33,"crypto":5,"deep-extend":34,"underscore":81,"util":32}],88:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -21075,7 +18365,7 @@ logger.error = function (message, callback) { return this._log('error', message, callback); }; -},{"../index":102}],101:[function(require,module,exports){ +},{"../index":90}],89:[function(require,module,exports){ /** * @title joola/lib/common/modifiers * @overview Includes different prototype modifiers used by joola @@ -21230,8 +18520,9 @@ Array.prototype.equals = function (array) { return true; }; -},{}],102:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{}],90:[function(require,module,exports){ +(function (global){ +/** * @title joola * @overview the open-source data analytics framework * @copyright Joola Smart Solutions, Ltd. @@ -21593,7 +18884,8 @@ joola.set = function (key, value, callback) { joola.get = function (key) { return joola.options[key]; }; -},{"./../../package.json":94,"./common/api":95,"./common/dispatch":96,"./common/events":97,"./common/globals":98,"./common/index":99,"./common/logger":100,"./viz/index":117,"querystring":13,"socket.io-client":49,"url":17}],103:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./../../package.json":82,"./common/api":83,"./common/dispatch":84,"./common/events":85,"./common/globals":86,"./common/index":87,"./common/logger":88,"./viz/index":105,"querystring":21,"socket.io-client":37,"url":30}],91:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -21964,7 +19256,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":102,"./_proto":116,"underscore":93}],104:[function(require,module,exports){ +},{"../index":90,"./_proto":104,"underscore":81}],92:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -22205,7 +19497,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":102,"./_proto":116,"cloneextend":1,"eventemitter2":3,"underscore":93}],105:[function(require,module,exports){ +},{"../index":90,"./_proto":104,"cloneextend":33,"eventemitter2":35,"underscore":81}],93:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -23203,7 +20495,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":102,"./_proto":116,"underscore":93}],106:[function(require,module,exports){ +},{"../index":90,"./_proto":104,"underscore":81}],94:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -23600,7 +20892,7 @@ DimensionPicker.meta = { } } }; -},{"./_proto":116,"cloneextend":1,"eventemitter2":3}],107:[function(require,module,exports){ +},{"./_proto":104,"cloneextend":33,"eventemitter2":35}],95:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -23740,7 +21032,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":102,"./_proto":116}],108:[function(require,module,exports){ +},{"../index":90,"./_proto":104}],96:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -24078,7 +21370,7 @@ Metric.meta = { } } }; -},{"../index":102,"./_proto":116,"cloneextend":1}],109:[function(require,module,exports){ +},{"../index":90,"./_proto":104,"cloneextend":33}],97:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -24474,7 +21766,7 @@ MetricPicker.meta = { } } }; -},{"./_proto":116,"cloneextend":1,"eventemitter2":3}],110:[function(require,module,exports){ +},{"./_proto":104,"cloneextend":33,"eventemitter2":35}],98:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -24776,7 +22068,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":102,"./_proto":116,"underscore":93}],111:[function(require,module,exports){ +},{"../index":90,"./_proto":104,"underscore":81}],99:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -25109,7 +22401,7 @@ Pie.meta = { } } }; -},{"../index":102,"./_proto":116,"underscore":93}],112:[function(require,module,exports){ +},{"../index":90,"./_proto":104,"underscore":81}],100:[function(require,module,exports){ /*jshint -W083 */ /** @@ -25336,7 +22628,7 @@ joola.events.on('core.init.finish', function () { }); -},{"../index":102,"./_proto":116,"underscore":93}],113:[function(require,module,exports){ +},{"../index":90,"./_proto":104,"underscore":81}],101:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -25598,7 +22890,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":102,"./_proto":116}],114:[function(require,module,exports){ +},{"../index":90,"./_proto":104}],102:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -26104,7 +23396,7 @@ Table.meta = { } } }; -},{"../index":102,"./_proto":116,"underscore":93}],115:[function(require,module,exports){ +},{"../index":90,"./_proto":104,"underscore":81}],103:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -26634,7 +23926,7 @@ Timeline.meta = { chartProvider: 'highcharts', license: 'MIT' }; -},{"../index":102,"./_proto":116,"moment":48,"underscore":93}],116:[function(require,module,exports){ +},{"../index":90,"./_proto":104,"moment":36,"underscore":81}],104:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -26929,7 +24221,7 @@ proto.find = function (obj) { }; -},{"../index":102,"cloneextend":1,"moment":48,"underscore":93}],117:[function(require,module,exports){ +},{"../index":90,"cloneextend":33,"moment":36,"underscore":81}],105:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -26971,5 +24263,4 @@ viz.stam = function (callback) { return viz.pickers.init(callback); }; -},{"../index":102,"./BarTable":103,"./Canvas":104,"./DatePicker":105,"./DimensionPicker":106,"./Geo":107,"./Metric":108,"./MetricPicker":109,"./MiniTable":110,"./Pie":111,"./PunchCard":112,"./Sparkline":113,"./Table":114,"./Timeline":115}]},{},[102]) -; \ No newline at end of file +},{"../index":90,"./BarTable":91,"./Canvas":92,"./DatePicker":93,"./DimensionPicker":94,"./Geo":95,"./Metric":96,"./MetricPicker":97,"./MiniTable":98,"./Pie":99,"./PunchCard":100,"./Sparkline":101,"./Table":102,"./Timeline":103}]},{},[90]) \ No newline at end of file diff --git a/build/release/joola.min.css b/build/release/joola.min.css index 7c0ca0c..51ace26 100644 --- a/build/release/joola.min.css +++ b/build/release/joola.min.css @@ -1,2 +1,2 @@ -/*! joola.sdk - v0.7.13 - 2014-10-01 */ +/*! joola.sdk - v0.7.14 - 2014-10-12 */ [jio-domain=joola] .btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}[jio-domain=joola] .btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.428571429;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;background-image:none;border:1px solid transparent;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;color:#333;background-color:#fff;border-color:#ccc}[jio-domain=joola] .btn:hover,.btn:focus{color:#333;text-decoration:none}[jio-domain=joola] .btn:active,.btn.active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}[jio-domain=joola] .btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{color:#333;background-color:#ebebeb;border-color:#adadad}[jio-domain=joola] .btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{color:#333;background-color:#ebebeb;border-color:#adadad}[jio-domain=joola] .btn-default:active,.btn-default.active,.open .dropdown-toggle.btn-default{background-image:none}[jio-domain=joola] .btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}[jio-domain=joola] .btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}[jio-domain=joola] .btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}[jio-domain=joola] .btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}[jio-domain=joola] .btn-group>.btn:first-child{margin-left:0}[jio-domain=joola] .btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}[jio-type=datepicker]{float:right}[jio-type=datepicker] a{color:#428bca;text-decoration:none}[jio-type=datepicker] .jcontainer{background-color:#fff;border:1px solid #EFEFEF;cursor:pointer;position:relative;z-index:19;border-radius:5px;-moz-border-radius:5px;-webkit-border-radius:5px}[jio-type=datepicker] .jcontainer:hover{border:1px solid #CCC}[jio-type=datepicker] .expanded{border:1px solid #CCC;border-bottom:1px solid #fff;border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;-webkit-border-top-left-radius:5px;-webkit-border-top-right-radius:5px;-webkit-border-bottom-left-radius:0;-webkit-border-bottom-right-radius:0}[jio-type=datepicker] .picker.compare{margin-top:17px}[jio-type=datepicker] .datetable{border-collapse:collapse}[jio-type=datepicker] .datetable .dates{padding:5px;padding-right:20px}[jio-type=datepicker] .datetable .dates .datelabel{color:#1C2E3D}[jio-type=datepicker] .datetable .dates .compare{color:#999;font-size:13px}[jio-type=datepicker] .datetable .dates .compare .datelabel.fromdate,[jio-type=datepicker] .datetable .dates .compare .datelabel.todate{font-size:13px;color:#333}[jio-type=datepicker] .datebox .dropdownmarker-wrapper{width:25px;background-color:#f5f5f5}[jio-type=datepicker] .datetable .dropdownmarker{position:absolute;top:12px;right:8px;display:block;width:0;height:0;content:"";border:5px solid;border-right-color:transparent;border-left-color:transparent;border-bottom-color:transparent;border-top-color:inherit}[jio-type=datepicker] .datebox.expanded .datetable .dropdownmarker{top:5px;border-right-color:transparent;border-left-color:transparent;border-top-color:transparent;border-bottom-color:inherit}[jio-type=datepicker] .picker{position:absolute;background-color:#F7F7F7;border:1px solid #CCC;margin-left:1px;margin-top:-1px;padding:10px;white-space:nowrap;z-index:1000;border-radius:5px 0 5px 5px;-moz-border-radius:5px 0 5px 5px;-webkit-border-bottom-left-radius:5px;-webkit-border-bottom-right-radius:5px}[jio-type=datepicker] .picker .wrapper .control{padding:0 10px;white-space:nowrap;vertical-align:top}[jio-type=datepicker] .picker .wrapper .control .optionscontainer{display:block;clear:both;padding:5px;font-size:75%}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .customdate{font-weight:700;margin-bottom:3px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .customdate select{border:#9A9A9A solid 1px;background-color:#fff;color:#000}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .customdate select.selector{width:auto;height:auto;padding:1px;margin-bottom:5px;margin-left:6px;width:120px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .compareoption span{top:-2px;position:relative}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .daterange .dateoption{border:#dedede solid 3px;cursor:pointer;width:8em;padding:2px;padding-left:5px;padding-right:5px;margin-top:0;margin-bottom:4px;margin-left:4px;margin-right:4px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .daterange .dateoption.active{border:#07C solid 3px;margin-top:0;margin-bottom:4px;margin-left:4px;margin-right:4px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .comparerange .dateoption.active{border:#86BE2B solid 3px;margin-bottom:4px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .daterange .dateoption.invalid{border:#B00 solid 3px;margin-bottom:4px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .compareoption{padding:3px;white-space:nowrap;padding-right:22px;display:none;font-weight:700;margin-bottom:3px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .compareoption .checker{}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .compareoption.visible{display:block}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .divider{border-top:#666 dotted 1px;margin-top:3px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .buttons{padding-top:15px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .apply{margin-top:-15px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer .cancel{text-decoration:underline;color:#24B;cursor:pointer;padding-left:10px}[jio-type=datepicker] .picker .wrapper .calendars{white-space:nowrap;margin:2px;width:405px}[jio-type=datepicker] .picker .wrapper .calendars table{border-collapse:collapse}[jio-type=datepicker] .picker .wrapper .calendars .datetable-prev,[jio-type=datepicker] .picker .wrapper .calendars .datetable-next{vertical-align:top}[jio-type=datepicker] .picker .wrapper .calendars .datetable-prev div,[jio-type=datepicker] .picker .wrapper .calendars .datetable-next div{border:#CCC solid 1px;background-color:#DDD;cursor:pointer}[jio-type=datepicker] .picker .wrapper .calendars .datetable-prev div{border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;-webkit-border-top-left-radius:3px;-webkit-border-top-right-radius:0;-webkit-border-bottom-left-radius:3px;-webkit-border-bottom-right-radius:0}[jio-type=datepicker] .picker .wrapper .calendars .datetable-next div{border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;-webkit-border-top-left-radius:0;-webkit-border-top-right-radius:3px;-webkit-border-bottom-left-radius:0;-webkit-border-bottom-right-radius:3px}[jio-type=datepicker] .picker .wrapper .calendars .datetable-prev div div.inline-block,[jio-type=datepicker] .picker .wrapper .calendars .datetable-next div div.inline-block{height:9px;padding:0;width:4px}[jio-type=datepicker] .picker .wrapper .calendars .datetable-prev div div.inline-block{display:block;width:0;height:0;content:"";border:5px solid;border-left-color:transparent;border-top-color:transparent;border-bottom-color:transparent;margin-right:6px;margin-top:-2px}[jio-type=datepicker] .picker .wrapper .calendars .datetable-next div div.inline-block{display:block;width:0;height:0;content:"";border:5px solid;border-right-color:transparent;border-top-color:transparent;border-bottom-color:transparent;margin-left:6px;margin-top:-2px}[jio-type=datepicker] .picker .wrapper .control .optionscontainer input,[jio-type=datepicker] .picker .wrapper .control .optionscontainer textarea{-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:none;-moz-transition:border linear .1s,box-shadow linear .1s;-ms-transition:border linear .1s,box-shadow linear .1s;-o-transition:border linear .1s,box-shadow linear .1s;transition:border linear .1s,box-shadow linear .1s}[jio-type=datepicker] .picker .wrapper .calendars .ui-datepicker-prev,[jio-type=datepicker] .picker .wrapper .calendars .ui-datepicker-next{display:none}[jio-type=datepicker] .ui-datepicker-calendar td{border-bottom:#F7F7F7 solid 1px;border-right:#F7F7F7 solid 1px;background-color:#fff}[jio-type=datepicker] .ui-datepicker-title{text-align:center;background-color:#DDD;font-size:85%;color:#07C;cursor:default;border-bottom:#CCC solid 1px;height:18px}[jio-type=datepicker] .daycell{text-align:center;padding:2px 3px;vertical-align:middle;font-size:72%;cursor:pointer}[jio-type=datepicker] .daycell a{text-decoration:none}[jio-type=datepicker] .daycell:hover{background-color:#FC3}[jio-type=datepicker] .daycell.disabled,[jio-type=datepicker] .daycell.ui-state-disabled{cursor:default;color:#DDD;font-weight:400;background-color:#fff}[jio-type=datepicker] .daycell.inrange{background-color:#07C}[jio-type=datepicker] .daycell.inrange:hover{background-color:#FC3}[jio-type=datepicker] .daycell.inrange a{color:#fff}[jio-type=datepicker] .daycell.compare.disabled{cursor:default;color:#DDD;font-weight:400;background-color:#fff}[jio-type=datepicker] .daycell.compare.inrange{background-color:#86BE2B}[jio-type=datepicker] .daycell.basencompare.inrange{background-color:#00B1AB}[jio-type=datepicker] .daycell.compare.inrange:hover{background-color:#FC3}[jio-type=datepicker] .ui-datepicker-calendar th{text-align:center;padding:2px 3px;vertical-align:middle;font-size:80%;border-bottom:#F7F7F7 solid 1px;border-right:#F7F7F7 solid 1px;background-color:#fff;cursor:default;border-bottom:#CCC solid 1px}[jio-domain=joola] .unselectable{-moz-user-select:-moz-none;-khtml-user-select:none;-webkit-user-select:none;-o-user-select:none;user-select:none}[jio-domain=joola] .line-separator{height:1px}[jio-domain=joola] [jio-type=bartable] .table{margin-bottom:10px;width:100%}[jio-domain=joola] [jio-type=bartable] .table tr{vertical-align:top}[jio-domain=joola] [jio-type=bartable] .table td{padding-top:8px;padding-bottom:5px}[jio-domain=joola] [jio-type=bartable] .table tr:first-of-type td{text-overflow:ellipsis;padding-top:5px;padding-bottom:5px;white-space:nowrap;overflow:hidden}[jio-domain=joola] [jio-type=bartable] .table td .caption{text-overflow:ellipsis;line-height:17px;color:#666;font-weight:500;text-transform:uppercase;white-space:nowrap;overflow:hidden}[jio-domain=joola] [jio-type=bartable] .table td .subcaption{color:#999;font-size:12px;font-weight:400;line-height:1;text-transform:uppercase;margin-top:2px}[jio-domain=joola] [jio-type=bartable] .table.table-striped tbody>tr:nth-child(even)>td{background-color:#fff}[jio-domain=joola] [jio-type=bartable] .barwrapper{width:100px}[jio-domain=joola] [jio-type=bartable] .bartable-caption{line-height:1.2857142857em;margin:0 0 10px;padding:0;text-transform:uppercase;font-size:18px;font-weight:400;color:#333;text-align:center;margin-bottom:20px}[jio-domain=joola]{margin:0;padding:0} \ No newline at end of file diff --git a/build/release/joola.min.js b/build/release/joola.min.js index 8c4ccea..7f1a8c3 100644 --- a/build/release/joola.min.js +++ b/build/release/joola.min.js @@ -1,12 +1,12 @@ -/*! joola.sdk 2014-09-24 */ +/*! joola.sdk 2014-10-12 */ !function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;gh;h++)g[h]=d.isBuffer(a)?a.readUInt8(h):a[h];else if("string"===e)g.write(a,0,b);else if("number"===e&&!d._useTypedArrays&&!c)for(h=0;f>h;h++)g[h]=0;return g}function e(a,b,c,e){c=Number(c)||0;var f=a.length-c;e?(e=Number(e),e>f&&(e=f)):e=f;var g=b.length;R(g%2===0,"Invalid hex string"),e>g/2&&(e=g/2);for(var h=0;e>h;h++){var i=parseInt(b.substr(2*h,2),16);R(!isNaN(i),"Invalid hex string"),a[c+h]=i}return d._charsWritten=2*h,h}function f(a,b,c,e){var f=d._charsWritten=M(I(b),a,c,e);return f}function g(a,b,c,e){var f=d._charsWritten=M(J(b),a,c,e);return f}function h(a,b,c,d){return g(a,b,c,d)}function i(a,b,c,e){var f=d._charsWritten=M(L(b),a,c,e);return f}function j(a,b,c,e){var f=d._charsWritten=M(K(b),a,c,e);return f}function k(a,b,c){return S.fromByteArray(0===b&&c===a.length?a:a.slice(b,c))}function l(a,b,c){var d="",e="";c=Math.min(a.length,c);for(var f=b;c>f;f++)a[f]<=127?(d+=N(e)+String.fromCharCode(a[f]),e=""):e+="%"+a[f].toString(16);return d+N(e)}function m(a,b,c){var d="";c=Math.min(a.length,c);for(var e=b;c>e;e++)d+=String.fromCharCode(a[e]);return d}function n(a,b,c){return m(a,b,c)}function o(a,b,c){var d=a.length;(!b||0>b)&&(b=0),(!c||0>c||c>d)&&(c=d);for(var e="",f=b;c>f;f++)e+=H(a[f]);return e}function p(a,b,c){for(var d=a.slice(b,c),e="",f=0;f=e)){var f;return c?(f=a[b],e>b+1&&(f|=a[b+1]<<8)):(f=a[b]<<8,e>b+1&&(f|=a[b+1])),f}}function r(a,b,c,d){d||(R("boolean"==typeof c,"missing or invalid endian"),R(void 0!==b&&null!==b,"missing offset"),R(b+3=e)){var f;return c?(e>b+2&&(f=a[b+2]<<16),e>b+1&&(f|=a[b+1]<<8),f|=a[b],e>b+3&&(f+=a[b+3]<<24>>>0)):(e>b+1&&(f=a[b+1]<<16),e>b+2&&(f|=a[b+2]<<8),e>b+3&&(f|=a[b+3]),f+=a[b]<<24>>>0),f}}function s(a,b,c,d){d||(R("boolean"==typeof c,"missing or invalid endian"),R(void 0!==b&&null!==b,"missing offset"),R(b+1=e)){var f=q(a,b,c,!0),g=32768&f;return g?-1*(65535-f+1):f}}function t(a,b,c,d){d||(R("boolean"==typeof c,"missing or invalid endian"),R(void 0!==b&&null!==b,"missing offset"),R(b+3=e)){var f=r(a,b,c,!0),g=2147483648&f;return g?-1*(4294967295-f+1):f}}function u(a,b,c,d){return d||(R("boolean"==typeof c,"missing or invalid endian"),R(b+3=f))for(var g=0,h=Math.min(f-c,2);h>g;g++)a[c+g]=(b&255<<8*(d?g:1-g))>>>8*(d?g:1-g)}function x(a,b,c,d,e){e||(R(void 0!==b&&null!==b,"missing value"),R("boolean"==typeof d,"missing or invalid endian"),R(void 0!==c&&null!==c,"missing offset"),R(c+3=f))for(var g=0,h=Math.min(f-c,4);h>g;g++)a[c+g]=b>>>8*(d?g:3-g)&255}function y(a,b,c,d,e){e||(R(void 0!==b&&null!==b,"missing value"),R("boolean"==typeof d,"missing or invalid endian"),R(void 0!==c&&null!==c,"missing offset"),R(c+1=f||(b>=0?w(a,b,c,d,e):w(a,65535+b+1,c,d,e))}function z(a,b,c,d,e){e||(R(void 0!==b&&null!==b,"missing value"),R("boolean"==typeof d,"missing or invalid endian"),R(void 0!==c&&null!==c,"missing offset"),R(c+3=f||(b>=0?x(a,b,c,d,e):x(a,4294967295+b+1,c,d,e))}function A(a,b,c,d,e){e||(R(void 0!==b&&null!==b,"missing value"),R("boolean"==typeof d,"missing or invalid endian"),R(void 0!==c&&null!==c,"missing offset"),R(c+3=f||T.write(a,b,c,d,23,4)}function B(a,b,c,d,e){e||(R(void 0!==b&&null!==b,"missing value"),R("boolean"==typeof d,"missing or invalid endian"),R(void 0!==c&&null!==c,"missing offset"),R(c+7=f||T.write(a,b,c,d,52,8)}function C(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")}function D(a,b,c){return"number"!=typeof a?c:(a=~~a,a>=b?b:a>=0?a:(a+=b,a>=0?a:0))}function E(a){return a=~~Math.ceil(+a),0>a?0:a}function F(a){return(Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)})(a)}function G(a){return F(a)||d.isBuffer(a)||a&&"object"==typeof a&&"number"==typeof a.length}function H(a){return 16>a?"0"+a.toString(16):a.toString(16)}function I(a){for(var b=[],c=0;c=d)b.push(a.charCodeAt(c));else{var e=c;d>=55296&&57343>=d&&c++;for(var f=encodeURIComponent(a.slice(e,c+1)).substr(1).split("%"),g=0;g>8,d=b%256,e.push(d),e.push(c);return e}function L(a){return S.toByteArray(a)}function M(a,b,c,d){for(var e=0;d>e&&!(e+c>=b.length||e>=a.length);e++)b[e+c]=a[e];return e}function N(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}function O(a,b){R("number"==typeof a,"cannot write a non-number as a number"),R(a>=0,"specified a negative value for writing an unsigned value"),R(b>=a,"value is larger than maximum value for type"),R(Math.floor(a)===a,"value has a fractional component")}function P(a,b,c){R("number"==typeof a,"cannot write a non-number as a number"),R(b>=a,"value larger than maximum allowed value"),R(a>=c,"value smaller than minimum allowed value"),R(Math.floor(a)===a,"value has a fractional component")}function Q(a,b,c){R("number"==typeof a,"cannot write a non-number as a number"),R(b>=a,"value larger than maximum allowed value"),R(a>=c,"value smaller than minimum allowed value")}function R(a,b){if(!a)throw new Error(b||"Failed assertion")}var S=a("base64-js"),T=a("ieee754");c.Buffer=d,c.SlowBuffer=d,c.INSPECT_MAX_BYTES=50,d.poolSize=8192,d._useTypedArrays=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);return b.foo=function(){return 42},42===b.foo()&&"function"==typeof b.subarray}catch(c){return!1}}(),d.isEncoding=function(a){switch(String(a).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},d.isBuffer=function(a){return!(null===a||void 0===a||!a._isBuffer)},d.byteLength=function(a,b){var c;switch(a+="",b||"utf8"){case"hex":c=a.length/2;break;case"utf8":case"utf-8":c=I(a).length;break;case"ascii":case"binary":case"raw":c=a.length;break;case"base64":c=L(a).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":c=2*a.length;break;default:throw new Error("Unknown encoding")}return c},d.concat=function(a,b){if(R(F(a),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===a.length)return new d(0);if(1===a.length)return a[0];var c;if("number"!=typeof b)for(b=0,c=0;cl&&(c=l)):c=l,d=String(d||"utf8").toLowerCase();var m;switch(d){case"hex":m=e(this,a,b,c);break;case"utf8":case"utf-8":m=f(this,a,b,c);break;case"ascii":m=g(this,a,b,c);break;case"binary":m=h(this,a,b,c);break;case"base64":m=i(this,a,b,c);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":m=j(this,a,b,c);break;default:throw new Error("Unknown encoding")}return m},d.prototype.toString=function(a,b,c){var d=this;if(a=String(a||"utf8").toLowerCase(),b=Number(b)||0,c=void 0!==c?Number(c):c=d.length,c===b)return"";var e;switch(a){case"hex":e=o(d,b,c);break;case"utf8":case"utf-8":e=l(d,b,c);break;case"ascii":e=m(d,b,c);break;case"binary":e=n(d,b,c);break;case"base64":e=k(d,b,c);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":e=p(d,b,c);break;default:throw new Error("Unknown encoding")}return e},d.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},d.prototype.copy=function(a,b,c,e){var f=this;if(c||(c=0),e||0===e||(e=this.length),b||(b=0),e!==c&&0!==a.length&&0!==f.length){R(e>=c,"sourceEnd < sourceStart"),R(b>=0&&b=0&&c=0&&e<=f.length,"sourceEnd out of bounds"),e>this.length&&(e=this.length),a.length-bg||!d._useTypedArrays)for(var h=0;g>h;h++)a[h+b]=this[h+c];else a._set(this.subarray(c,c+g),b)}},d.prototype.slice=function(a,b){var c=this.length;if(a=D(a,c,0),b=D(b,c,c),d._useTypedArrays)return d._augment(this.subarray(a,b));for(var e=b-a,f=new d(e,void 0,!0),g=0;e>g;g++)f[g]=this[g+a];return f},d.prototype.get=function(a){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(a)},d.prototype.set=function(a,b){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(a,b)},d.prototype.readUInt8=function(a,b){return b||(R(void 0!==a&&null!==a,"missing offset"),R(a=this.length?void 0:this[a]},d.prototype.readUInt16LE=function(a,b){return q(this,a,!0,b)},d.prototype.readUInt16BE=function(a,b){return q(this,a,!1,b)},d.prototype.readUInt32LE=function(a,b){return r(this,a,!0,b)},d.prototype.readUInt32BE=function(a,b){return r(this,a,!1,b)},d.prototype.readInt8=function(a,b){if(b||(R(void 0!==a&&null!==a,"missing offset"),R(a=this.length)){var c=128&this[a];return c?-1*(255-this[a]+1):this[a]}},d.prototype.readInt16LE=function(a,b){return s(this,a,!0,b)},d.prototype.readInt16BE=function(a,b){return s(this,a,!1,b)},d.prototype.readInt32LE=function(a,b){return t(this,a,!0,b)},d.prototype.readInt32BE=function(a,b){return t(this,a,!1,b)},d.prototype.readFloatLE=function(a,b){return u(this,a,!0,b)},d.prototype.readFloatBE=function(a,b){return u(this,a,!1,b)},d.prototype.readDoubleLE=function(a,b){return v(this,a,!0,b)},d.prototype.readDoubleBE=function(a,b){return v(this,a,!1,b)},d.prototype.writeUInt8=function(a,b,c){c||(R(void 0!==a&&null!==a,"missing value"),R(void 0!==b&&null!==b,"missing offset"),R(b=this.length||(this[b]=a)},d.prototype.writeUInt16LE=function(a,b,c){w(this,a,b,!0,c)},d.prototype.writeUInt16BE=function(a,b,c){w(this,a,b,!1,c)},d.prototype.writeUInt32LE=function(a,b,c){x(this,a,b,!0,c)},d.prototype.writeUInt32BE=function(a,b,c){x(this,a,b,!1,c)},d.prototype.writeInt8=function(a,b,c){c||(R(void 0!==a&&null!==a,"missing value"),R(void 0!==b&&null!==b,"missing offset"),R(b=this.length||(a>=0?this.writeUInt8(a,b,c):this.writeUInt8(255+a+1,b,c))},d.prototype.writeInt16LE=function(a,b,c){y(this,a,b,!0,c)},d.prototype.writeInt16BE=function(a,b,c){y(this,a,b,!1,c)},d.prototype.writeInt32LE=function(a,b,c){z(this,a,b,!0,c)},d.prototype.writeInt32BE=function(a,b,c){z(this,a,b,!1,c)},d.prototype.writeFloatLE=function(a,b,c){A(this,a,b,!0,c)},d.prototype.writeFloatBE=function(a,b,c){A(this,a,b,!1,c)},d.prototype.writeDoubleLE=function(a,b,c){B(this,a,b,!0,c)},d.prototype.writeDoubleBE=function(a,b,c){B(this,a,b,!1,c)},d.prototype.fill=function(a,b,c){if(a||(a=0),b||(b=0),c||(c=this.length),"string"==typeof a&&(a=a.charCodeAt(0)),R("number"==typeof a&&!isNaN(a),"value is not a number"),R(c>=b,"end < start"),c!==b&&0!==this.length){R(b>=0&&b=0&&c<=this.length,"end out of bounds");for(var d=b;c>d;d++)this[d]=a}},d.prototype.inspect=function(){for(var a=[],b=this.length,d=0;b>d;d++)if(a[d]=H(this[d]),d===c.INSPECT_MAX_BYTES){a[d+1]="...";break}return""},d.prototype.toArrayBuffer=function(){if("undefined"!=typeof Uint8Array){if(d._useTypedArrays)return new d(this).buffer;for(var a=new Uint8Array(this.length),b=0,c=a.length;c>b;b+=1)a[b]=this[b];return a.buffer}throw new Error("Buffer.toArrayBuffer not supported in this browser")};var U=d.prototype;d._augment=function(a){return a._isBuffer=!0,a._get=a.get,a._set=a.set,a.get=U.get,a.set=U.set,a.write=U.write,a.toString=U.toString,a.toLocaleString=U.toString,a.toJSON=U.toJSON,a.copy=U.copy,a.slice=U.slice,a.readUInt8=U.readUInt8,a.readUInt16LE=U.readUInt16LE,a.readUInt16BE=U.readUInt16BE,a.readUInt32LE=U.readUInt32LE,a.readUInt32BE=U.readUInt32BE,a.readInt8=U.readInt8,a.readInt16LE=U.readInt16LE,a.readInt16BE=U.readInt16BE,a.readInt32LE=U.readInt32LE,a.readInt32BE=U.readInt32BE,a.readFloatLE=U.readFloatLE,a.readFloatBE=U.readFloatBE,a.readDoubleLE=U.readDoubleLE,a.readDoubleBE=U.readDoubleBE,a.writeUInt8=U.writeUInt8,a.writeUInt16LE=U.writeUInt16LE,a.writeUInt16BE=U.writeUInt16BE,a.writeUInt32LE=U.writeUInt32LE,a.writeUInt32BE=U.writeUInt32BE,a.writeInt8=U.writeInt8,a.writeInt16LE=U.writeInt16LE,a.writeInt16BE=U.writeInt16BE,a.writeInt32LE=U.writeInt32LE,a.writeInt32BE=U.writeInt32BE,a.writeFloatLE=U.writeFloatLE,a.writeFloatBE=U.writeFloatBE,a.writeDoubleLE=U.writeDoubleLE,a.writeDoubleBE=U.writeDoubleBE,a.fill=U.fill,a.inspect=U.inspect,a.toArrayBuffer=U.toArrayBuffer,a}},{"base64-js":2,ieee754:3}],2:[function(a,b,c){var d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";!function(a){"use strict";function b(a){var b=a.charCodeAt(0);return b===g?62:b===h?63:i>b?-1:i+10>b?b-i+26+26:k+26>b?b-k:j+26>b?b-j+26:void 0}function c(a){function c(a){j[l++]=a}var d,e,g,h,i,j;if(a.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var k=a.length;i="="===a.charAt(k-2)?2:"="===a.charAt(k-1)?1:0,j=new f(3*a.length/4-i),g=i>0?a.length-4:a.length;var l=0;for(d=0,e=0;g>d;d+=4,e+=3)h=b(a.charAt(d))<<18|b(a.charAt(d+1))<<12|b(a.charAt(d+2))<<6|b(a.charAt(d+3)),c((16711680&h)>>16),c((65280&h)>>8),c(255&h);return 2===i?(h=b(a.charAt(d))<<2|b(a.charAt(d+1))>>4,c(255&h)):1===i&&(h=b(a.charAt(d))<<10|b(a.charAt(d+1))<<4|b(a.charAt(d+2))>>2,c(h>>8&255),c(255&h)),j}function e(a){function b(a){return d.charAt(a)}function c(a){return b(a>>18&63)+b(a>>12&63)+b(a>>6&63)+b(63&a)}var e,f,g,h=a.length%3,i="";for(e=0,g=a.length-h;g>e;e+=3)f=(a[e]<<16)+(a[e+1]<<8)+a[e+2],i+=c(f);switch(h){case 1:f=a[a.length-1],i+=b(f>>2),i+=b(f<<4&63),i+="==";break;case 2:f=(a[a.length-2]<<8)+a[a.length-1],i+=b(f>>10),i+=b(f>>4&63),i+=b(f<<2&63),i+="="}return i}var f="undefined"!=typeof Uint8Array?Uint8Array:Array,g="+".charCodeAt(0),h="/".charCodeAt(0),i="0".charCodeAt(0),j="a".charCodeAt(0),k="A".charCodeAt(0);a.toByteArray=c,a.fromByteArray=e}("undefined"==typeof c?this.base64js={}:c)},{}],3:[function(a,b,c){c.read=function(a,b,c,d,e){var f,g,h=8*e-d-1,i=(1<>1,k=-7,l=c?e-1:0,m=c?-1:1,n=a[b+l];for(l+=m,f=n&(1<<-k)-1,n>>=-k,k+=h;k>0;f=256*f+a[b+l],l+=m,k-=8);for(g=f&(1<<-k)-1,f>>=-k,k+=d;k>0;g=256*g+a[b+l],l+=m,k-=8);if(0===f)f=1-j;else{if(f===i)return g?0/0:1/0*(n?-1:1);g+=Math.pow(2,d),f-=j}return(n?-1:1)*g*Math.pow(2,f-d)},c.write=function(a,b,c,d,e,f){var g,h,i,j=8*f-e-1,k=(1<>1,m=23===e?Math.pow(2,-24)-Math.pow(2,-77):0,n=d?0:f-1,o=d?1:-1,p=0>b||0===b&&0>1/b?1:0;for(b=Math.abs(b),isNaN(b)||1/0===b?(h=isNaN(b)?1:0,g=k):(g=Math.floor(Math.log(b)/Math.LN2),b*(i=Math.pow(2,-g))<1&&(g--,i*=2),b+=g+l>=1?m/i:m*Math.pow(2,1-l),b*i>=2&&(g++,i/=2),g+l>=k?(h=0,g=k):g+l>=1?(h=(b*i-1)*Math.pow(2,e),g+=l):(h=b*Math.pow(2,l-1)*Math.pow(2,e),g=0));e>=8;a[c+n]=255&h,n+=o,h/=256,e-=8);for(g=g<0;a[c+n]=255&g,n+=o,g/=256,j-=8);a[c+n-o]|=128*p}},{}],4:[function(a,b){function c(a,b){if(a.length%g!==0){var c=a.length+(g-a.length%g);a=f.concat([a,h],c)}for(var d=[],e=b?a.readInt32BE:a.readInt32LE,i=0;in?b=a(b):b.lengthf;f++)d[f]=54^b[f],e[f]=92^b[f];var g=a(h.concat([d,c]));return a(h.concat([e,g]))}function e(a,b){a=a||"sha1";var c=m[a],e=[],g=0;return c||f("algorithm:",a,"is not yet supported"),{update:function(a){return h.isBuffer(a)||(a=new h(a)),e.push(a),g+=a.length,this},digest:function(a){var f=h.concat(e),g=b?d(c,b,f):c(f);return e=null,a?g.toString(a):g}}}function f(){var a=[].slice.call(arguments).join(" ");throw new Error([a,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join("\n"))}function g(a,b){for(var c in a)b(a[c],c)}var h=a("buffer").Buffer,i=a("./sha"),j=a("./sha256"),k=a("./rng"),l=a("./md5"),m={sha1:i,sha256:j,md5:l},n=64,o=new h(n);o.fill(0),c.createHash=function(a){return e(a)},c.createHmac=function(a,b){return e(a,b)},c.randomBytes=function(a,b){if(!b||!b.call)return new h(k(a));try{b.call(this,void 0,new h(k(a)))}catch(c){b(c)}},g(["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],function(a){c[a]=function(){f("sorry,",a,"is not implemented yet")}})},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:1}],6:[function(a,b){function c(a,b){a[b>>5]|=128<>>9<<4)+14]=b;for(var c=1732584193,d=-271733879,j=-1732584194,k=271733878,l=0;l>16)+(b>>16)+(c>>16);return d<<16|65535&c}function j(a,b){return a<>>32-b}var k=a("./helpers");b.exports=function(a){return k.hash(a,c,16)}},{"./helpers":4}],7:[function(a,b){!function(){var a,c,d=this;a=function(a){for(var b,b,c=new Array(a),d=0;a>d;d++)0==(3&d)&&(b=4294967296*Math.random()),c[d]=b>>>((3&d)<<3)&255;return c},d.crypto&&crypto.getRandomValues&&(c=function(a){var b=new Uint8Array(a);return crypto.getRandomValues(b),b}),b.exports=c||a}()},{}],8:[function(a,b){function c(a,b){a[b>>5]|=128<<24-b%32,a[(b+64>>9<<4)+15]=b;for(var c=Array(80),h=1732584193,i=-271733879,j=-1732584194,k=271733878,l=-1009589776,m=0;ms;s++){c[s]=16>s?a[m+s]:g(c[s-3]^c[s-8]^c[s-14]^c[s-16],1);var t=f(f(g(h,5),d(s,i,j,k)),f(f(l,c[s]),e(s)));l=k,k=j,j=g(i,30),i=h,h=t}h=f(h,n),i=f(i,o),j=f(j,p),k=f(k,q),l=f(l,r)}return Array(h,i,j,k,l)}function d(a,b,c,d){return 20>a?b&c|~b&d:40>a?b^c^d:60>a?b&c|b&d|c&d:b^c^d}function e(a){return 20>a?1518500249:40>a?1859775393:60>a?-1894007588:-899497514}function f(a,b){var c=(65535&a)+(65535&b),d=(a>>16)+(b>>16)+(c>>16);return d<<16|65535&c}function g(a,b){return a<>>32-b}var h=a("./helpers");b.exports=function(a){return h.hash(a,c,20,!0)}},{"./helpers":4}],9:[function(a,b){var c=a("./helpers"),d=function(a,b){var c=(65535&a)+(65535&b),d=(a>>16)+(b>>16)+(c>>16);return d<<16|65535&c},e=function(a,b){return a>>>b|a<<32-b},f=function(a,b){return a>>>b},g=function(a,b,c){return a&b^~a&c},h=function(a,b,c){return a&b^a&c^b&c},i=function(a){return e(a,2)^e(a,13)^e(a,22)},j=function(a){return e(a,6)^e(a,11)^e(a,25)},k=function(a){return e(a,7)^e(a,18)^f(a,3)},l=function(a){return e(a,17)^e(a,19)^f(a,10)},m=function(a,b){var c,e,f,m,n,o,p,q,r,s,t,u,v=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),w=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),x=new Array(64);a[b>>5]|=128<<24-b%32,a[(b+64>>9<<4)+15]=b;for(var r=0;rs;s++)x[s]=16>s?a[s+r]:d(d(d(l(x[s-2]),x[s-7]),k(x[s-15])),x[s-16]),t=d(d(d(d(q,j(n)),g(n,o,p)),v[s]),x[s]),u=d(i(c),h(c,e,f)),q=p,p=o,o=n,n=d(m,t),m=f,f=e,e=c,c=d(t,u);w[0]=d(c,w[0]),w[1]=d(e,w[1]),w[2]=d(f,w[2]),w[3]=d(m,w[3]),w[4]=d(n,w[4]),w[5]=d(o,w[5]),w[6]=d(p,w[6]),w[7]=d(q,w[7])}return w};b.exports=function(a){return c.hash(a,m,32,!0)}},{"./helpers":4}],10:[function(a,b){function c(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function d(a){return"function"==typeof a}function e(a){return"number"==typeof a}function f(a){return"object"==typeof a&&null!==a}function g(a){return void 0===a}b.exports=c,c.EventEmitter=c,c.prototype._events=void 0,c.prototype._maxListeners=void 0,c.defaultMaxListeners=10,c.prototype.setMaxListeners=function(a){if(!e(a)||0>a||isNaN(a))throw TypeError("n must be a positive number");return this._maxListeners=a,this},c.prototype.emit=function(a){var b,c,e,h,i,j;if(this._events||(this._events={}),"error"===a&&(!this._events.error||f(this._events.error)&&!this._events.error.length)){if(b=arguments[1],b instanceof Error)throw b;throw TypeError('Uncaught, unspecified "error" event.')}if(c=this._events[a],g(c))return!1;if(d(c))switch(arguments.length){case 1:c.call(this);break;case 2:c.call(this,arguments[1]);break;case 3:c.call(this,arguments[1],arguments[2]);break;default:for(e=arguments.length,h=new Array(e-1),i=1;e>i;i++)h[i-1]=arguments[i];c.apply(this,h)}else if(f(c)){for(e=arguments.length,h=new Array(e-1),i=1;e>i;i++)h[i-1]=arguments[i];for(j=c.slice(),e=j.length,i=0;e>i;i++)j[i].apply(this,h)}return!0},c.prototype.addListener=function(a,b){var e;if(!d(b))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",a,d(b.listener)?b.listener:b),this._events[a]?f(this._events[a])?this._events[a].push(b):this._events[a]=[this._events[a],b]:this._events[a]=b,f(this._events[a])&&!this._events[a].warned){var e;e=g(this._maxListeners)?c.defaultMaxListeners:this._maxListeners,e&&e>0&&this._events[a].length>e&&(this._events[a].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[a].length),"function"==typeof console.trace&&console.trace())}return this},c.prototype.on=c.prototype.addListener,c.prototype.once=function(a,b){function c(){this.removeListener(a,c),e||(e=!0,b.apply(this,arguments))}if(!d(b))throw TypeError("listener must be a function");var e=!1;return c.listener=b,this.on(a,c),this},c.prototype.removeListener=function(a,b){var c,e,g,h;if(!d(b))throw TypeError("listener must be a function");if(!this._events||!this._events[a])return this;if(c=this._events[a],g=c.length,e=-1,c===b||d(c.listener)&&c.listener===b)delete this._events[a],this._events.removeListener&&this.emit("removeListener",a,b);else if(f(c)){for(h=g;h-->0;)if(c[h]===b||c[h].listener&&c[h].listener===b){e=h;break}if(0>e)return this;1===c.length?(c.length=0,delete this._events[a]):c.splice(e,1),this._events.removeListener&&this.emit("removeListener",a,b)}return this},c.prototype.removeAllListeners=function(a){var b,c;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[a]&&delete this._events[a],this;if(0===arguments.length){for(b in this._events)"removeListener"!==b&&this.removeAllListeners(b);return this.removeAllListeners("removeListener"),this._events={},this}if(c=this._events[a],d(c))this.removeListener(a,c);else for(;c.length;)this.removeListener(a,c[c.length-1]);return delete this._events[a],this},c.prototype.listeners=function(a){var b;return b=this._events&&this._events[a]?d(this._events[a])?[this._events[a]]:this._events[a].slice():[]},c.listenerCount=function(a,b){var c;return c=a._events&&a._events[b]?d(a._events[b])?1:a._events[b].length:0}},{}],11:[function(a,b){var c=b.exports,d=(a("events").EventEmitter,a("./lib/request")),e=a("url");c.request=function(a,b){"string"==typeof a&&(a=e.parse(a)),a||(a={}),a.host||a.port||(a.port=parseInt(window.location.port,10)),!a.host&&a.hostname&&(a.host=a.hostname),a.scheme||(a.scheme=window.location.protocol.split(":")[0]),a.host||(a.host=window.location.hostname||window.location.host),/:/.test(a.host)&&(a.port||(a.port=a.host.split(":")[1]),a.host=a.host.split(":")[0]),a.port||(a.port="https"==a.scheme?443:80);var c=new d(new f,a);return b&&c.on("response",b),c},c.get=function(a,b){a.method="GET";var d=c.request(a,b);return d.end(),d},c.Agent=function(){},c.Agent.defaultMaxSockets=4;var f=function(){if("undefined"==typeof window)throw new Error("no window object present");if(window.XMLHttpRequest)return window.XMLHttpRequest;if(window.ActiveXObject){for(var a=["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.3.0","Microsoft.XMLHTTP"],b=0;bthis.offset&&(this.emit("data",b.slice(this.offset)),this.offset=b.length))};var h=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)}},{stream:23,util:32}],14:[function(a,b,c){!function(){function a(a){this.message=a}var b="undefined"!=typeof c?c:this,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";a.prototype=new Error,a.prototype.name="InvalidCharacterError",b.btoa||(b.btoa=function(b){for(var c,e,f=0,g=d,h="";b.charAt(0|f)||(g="=",f%1);h+=g.charAt(63&c>>8-f%1*8)){if(e=b.charCodeAt(f+=.75),e>255)throw new a("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");c=c<<8|e}return h}),b.atob||(b.atob=function(b){if(b=b.replace(/=+$/,""),b.length%4==1)throw new a("'atob' failed: The string to be decoded is not correctly encoded.");for(var c,e,f=0,g=0,h="";e=b.charAt(g++);~e&&(c=f%4?64*c+e:e,f++%4)?h+=String.fromCharCode(255&c>>(-2*f&6)):0)e=d.indexOf(e);return h})}()},{}],15:[function(a,b){var c=a("http"),d=b.exports;for(var e in c)c.hasOwnProperty(e)&&(d[e]=c[e]);d.request=function(a,b){return a||(a={}),a.scheme="https",c.request.call(this,a,b)}},{http:11}],16:[function(a,b){b.exports="function"==typeof Object.create?function(a,b){a.super_=b,a.prototype=Object.create(b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}})}:function(a,b){a.super_=b;var c=function(){};c.prototype=b.prototype,a.prototype=new c,a.prototype.constructor=a}},{}],17:[function(a,b){function c(){}var d=b.exports={};d.nextTick=function(){var a="undefined"!=typeof window&&window.setImmediate,b="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(a)return function(a){return window.setImmediate(a)};if(b){var c=[];return window.addEventListener("message",function(a){var b=a.source;if((b===window||null===b)&&"process-tick"===a.data&&(a.stopPropagation(),c.length>0)){var d=c.shift();d()}},!0),function(a){c.push(a),window.postMessage("process-tick","*")}}return function(a){setTimeout(a,0)}}(),d.title="browser",d.browser=!0,d.env={},d.argv=[],d.on=c,d.addListener=c,d.once=c,d.off=c,d.removeListener=c,d.removeAllListeners=c,d.emit=c,d.binding=function(){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(){throw new Error("process.chdir is not supported")}},{}],18:[function(a,b,c){(function(a){!function(d){function e(a){throw RangeError(H[a])}function f(a,b){for(var c=a.length;c--;)a[c]=b(a[c]);return a}function g(a,b){return f(a.split(G),b).join(".")}function h(a){for(var b,c,d=[],e=0,f=a.length;f>e;)b=a.charCodeAt(e++),b>=55296&&56319>=b&&f>e?(c=a.charCodeAt(e++),56320==(64512&c)?d.push(((1023&b)<<10)+(1023&c)+65536):(d.push(b),e--)):d.push(b);return d}function i(a){return f(a,function(a){var b="";return a>65535&&(a-=65536,b+=K(a>>>10&1023|55296),a=56320|1023&a),b+=K(a)}).join("")}function j(a){return 10>a-48?a-22:26>a-65?a-65:26>a-97?a-97:w}function k(a,b){return a+22+75*(26>a)-((0!=b)<<5)}function l(a,b,c){var d=0;for(a=c?J(a/A):a>>1,a+=J(a/b);a>I*y>>1;d+=w)a=J(a/I);return J(d+(I+1)*a/(a+z))}function m(a){var b,c,d,f,g,h,k,m,n,o,p=[],q=a.length,r=0,s=C,t=B;for(c=a.lastIndexOf(D),0>c&&(c=0),d=0;c>d;++d)a.charCodeAt(d)>=128&&e("not-basic"),p.push(a.charCodeAt(d));for(f=c>0?c+1:0;q>f;){for(g=r,h=1,k=w;f>=q&&e("invalid-input"),m=j(a.charCodeAt(f++)),(m>=w||m>J((v-r)/h))&&e("overflow"),r+=m*h,n=t>=k?x:k>=t+y?y:k-t,!(n>m);k+=w)o=w-n,h>J(v/o)&&e("overflow"),h*=o;b=p.length+1,t=l(r-g,b,0==g),J(r/b)>v-s&&e("overflow"),s+=J(r/b),r%=b,p.splice(r++,0,s)}return i(p)}function n(a){var b,c,d,f,g,i,j,m,n,o,p,q,r,s,t,u=[];for(a=h(a),q=a.length,b=C,c=0,g=B,i=0;q>i;++i)p=a[i],128>p&&u.push(K(p));for(d=f=u.length,f&&u.push(D);q>d;){for(j=v,i=0;q>i;++i)p=a[i],p>=b&&j>p&&(j=p);for(r=d+1,j-b>J((v-c)/r)&&e("overflow"),c+=(j-b)*r,b=j,i=0;q>i;++i)if(p=a[i],b>p&&++c>v&&e("overflow"),p==b){for(m=c,n=w;o=g>=n?x:n>=g+y?y:n-g,!(o>m);n+=w)t=m-o,s=w-o,u.push(K(k(o+t%s,0))),m=J(t/s);u.push(K(k(m,0))),g=l(c,r,d==f),c=0,++d}++c,++b}return u.join("")}function o(a){return g(a,function(a){return E.test(a)?m(a.slice(4).toLowerCase()):a})}function p(a){return g(a,function(a){return F.test(a)?"xn--"+n(a):a})}var q="object"==typeof c&&c,r="object"==typeof b&&b&&b.exports==q&&b,s="object"==typeof a&&a;(s.global===s||s.window===s)&&(d=s);var t,u,v=2147483647,w=36,x=1,y=26,z=38,A=700,B=72,C=128,D="-",E=/^xn--/,F=/[^ -~]/,G=/\x2E|\u3002|\uFF0E|\uFF61/g,H={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},I=w-x,J=Math.floor,K=String.fromCharCode;if(t={version:"1.2.4",ucs2:{decode:h,encode:i},decode:m,encode:n,toASCII:p,toUnicode:o},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return t});else if(q&&!q.nodeType)if(r)r.exports=t;else for(u in t)t.hasOwnProperty(u)&&(q[u]=t[u]);else d.punycode=t}(this)}).call(this,"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],19:[function(a,b){"use strict";function c(a,b){return Object.prototype.hasOwnProperty.call(a,b)}b.exports=function(a,b,e,f){b=b||"&",e=e||"=";var g={};if("string"!=typeof a||0===a.length)return g;var h=/\+/g;a=a.split(b);var i=1e3;f&&"number"==typeof f.maxKeys&&(i=f.maxKeys);var j=a.length;i>0&&j>i&&(j=i);for(var k=0;j>k;++k){var l,m,n,o,p=a[k].replace(h,"%20"),q=p.indexOf(e);q>=0?(l=p.substr(0,q),m=p.substr(q+1)):(l=p,m=""),n=decodeURIComponent(l),o=decodeURIComponent(m),c(g,n)?d(g[n])?g[n].push(o):g[n]=[g[n],o]:g[n]=o}return g};var d=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)}},{}],20:[function(a,b){"use strict";function c(a,b){if(a.map)return a.map(b);for(var c=[],d=0;d0)){var d=c.shift();d()}},!0),function(a){c.push(a),window.postMessage("process-tick","*")}}return function(a){setTimeout(a,0)}}(),c.title="browser",c.browser=!0,c.env={},c.argv=[],c.binding=function(){throw new Error("process.binding is not supported")},c.cwd=function(){return"/"},c.chdir=function(){throw new Error("process.chdir is not supported")}},{}],25:[function(a,b){function c(a){return this instanceof c?void d.call(this,a):new c(a)}b.exports=c;var d=a("./transform.js"),e=a("inherits");e(c,d),c.prototype._transform=function(a,b,c){c(null,a)}},{"./transform.js":27,inherits:16}],26:[function(a,b){(function(c){function d(b){b=b||{};var c=b.highWaterMark;this.highWaterMark=c||0===c?c:16384,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=!1,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.calledRead=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.objectMode=!!b.objectMode,this.defaultEncoding=b.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,b.encoding&&(x||(x=a("string_decoder").StringDecoder),this.decoder=new x(b.encoding),this.encoding=b.encoding)}function e(a){return this instanceof e?(this._readableState=new d(a,this),this.readable=!0,void z.call(this)):new e(a)}function f(a,b,c,d,e){var f=j(b,c);if(f)a.emit("error",f);else if(null===c||void 0===c)b.reading=!1,b.ended||k(a,b);else if(b.objectMode||c&&c.length>0)if(b.ended&&!e){var h=new Error("stream.push() after EOF");a.emit("error",h)}else if(b.endEmitted&&e){var h=new Error("stream.unshift() after end event");a.emit("error",h)}else!b.decoder||e||d||(c=b.decoder.write(c)),b.length+=b.objectMode?1:c.length,e?b.buffer.unshift(c):(b.reading=!1,b.buffer.push(c)),b.needReadable&&l(a),n(a,b);else e||(b.reading=!1);return g(b)}function g(a){return!a.ended&&(a.needReadable||a.length=D)a=D;else{a--;for(var b=1;32>b;b<<=1)a|=a>>b;a++}return a}function i(a,b){return 0===b.length&&b.ended?0:b.objectMode?0===a?0:1:isNaN(a)||null===a?b.flowing&&b.buffer.length?b.buffer[0].length:b.length:0>=a?0:(a>b.highWaterMark&&(b.highWaterMark=h(a)),a>b.length?b.ended?b.length:(b.needReadable=!0,0):a)}function j(a,b){var c=null;return A.isBuffer(b)||"string"==typeof b||null===b||void 0===b||a.objectMode||c||(c=new TypeError("Invalid non-string/buffer chunk")),c}function k(a,b){if(b.decoder&&!b.ended){var c=b.decoder.end();c&&c.length&&(b.buffer.push(c),b.length+=b.objectMode?1:c.length)}b.ended=!0,b.length>0?l(a):u(a)}function l(a){var b=a._readableState;b.needReadable=!1,b.emittedReadable||(b.emittedReadable=!0,b.sync?B(function(){m(a)}):m(a))}function m(a){a.emit("readable")}function n(a,b){b.readingMore||(b.readingMore=!0,B(function(){o(a,b)}))}function o(a,b){for(var c=b.length;!b.reading&&!b.flowing&&!b.ended&&b.length0)return;return 0===d.pipesCount?(d.flowing=!1,void(y.listenerCount(a,"data")>0&&s(a))):void(d.ranOut=!0)}function r(){this._readableState.ranOut&&(this._readableState.ranOut=!1,q(this))}function s(a,b){var c=a._readableState;if(c.flowing)throw new Error("Cannot switch to old mode now.");var d=b||!1,e=!1;a.readable=!0,a.pipe=z.prototype.pipe,a.on=a.addListener=z.prototype.on,a.on("readable",function(){e=!0;for(var b;!d&&null!==(b=a.read());)a.emit("data",b);null===b&&(e=!1,a._readableState.needReadable=!0)}),a.pause=function(){d=!0,this.emit("pause")},a.resume=function(){d=!1,e?B(function(){a.emit("readable")}):this.read(0),this.emit("resume")},a.emit("readable")}function t(a,b){var c,d=b.buffer,e=b.length,f=!!b.decoder,g=!!b.objectMode;if(0===d.length)return null;if(0===e)c=null;else if(g)c=d.shift();else if(!a||a>=e)c=f?d.join(""):A.concat(d,e),d.length=0;else if(aj&&a>i;j++){var h=d[0],l=Math.min(a-i,h.length);f?c+=h.slice(0,l):h.copy(c,i,0,l),l0)throw new Error("endReadable called on non-empty stream");!b.endEmitted&&b.calledRead&&(b.ended=!0,B(function(){b.endEmitted||0!==b.length||(b.endEmitted=!0,a.readable=!1,a.emit("end"))}))}function v(a,b){for(var c=0,d=a.length;d>c;c++)b(a[c],c)}function w(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1}b.exports=e,e.ReadableState=d;var x,y=a("events").EventEmitter,z=a("./index.js"),A=a("buffer").Buffer,B=a("process/browser.js").nextTick,C=a("inherits");C(e,z),e.prototype.push=function(a,b){var c=this._readableState;return"string"!=typeof a||c.objectMode||(b=b||c.defaultEncoding,b!==c.encoding&&(a=new A(a,b),b="")),f(this,c,a,b,!1)},e.prototype.unshift=function(a){var b=this._readableState;return f(this,b,a,"",!0)},e.prototype.setEncoding=function(b){x||(x=a("string_decoder").StringDecoder),this._readableState.decoder=new x(b),this._readableState.encoding=b};var D=8388608;e.prototype.read=function(a){var b=this._readableState;b.calledRead=!0;var c=a;if(("number"!=typeof a||a>0)&&(b.emittedReadable=!1),0===a&&b.needReadable&&(b.length>=b.highWaterMark||b.ended))return l(this),null;if(a=i(a,b),0===a&&b.ended)return 0===b.length&&u(this),null;var d=b.needReadable;b.length-a<=b.highWaterMark&&(d=!0),(b.ended||b.reading)&&(d=!1),d&&(b.reading=!0,b.sync=!0,0===b.length&&(b.needReadable=!0),this._read(b.highWaterMark),b.sync=!1),d&&!b.reading&&(a=i(c,b));var e;return e=a>0?t(a,b):null,null===e&&(b.needReadable=!0,a=0),b.length-=a,0!==b.length||b.ended||(b.needReadable=!0),b.ended&&!b.endEmitted&&0===b.length&&u(this),e},e.prototype._read=function(){this.emit("error",new Error("not implemented"))},e.prototype.pipe=function(a,b){function d(a){a===k&&f()}function e(){a.end()}function f(){a.removeListener("close",h),a.removeListener("finish",i),a.removeListener("drain",o),a.removeListener("error",g),a.removeListener("unpipe",d),k.removeListener("end",e),k.removeListener("end",f),(!a._writableState||a._writableState.needDrain)&&o()}function g(b){j(),0===s&&0===y.listenerCount(a,"error")&&a.emit("error",b)}function h(){a.removeListener("finish",i),j()}function i(){a.removeListener("close",h),j()}function j(){k.unpipe(a)}var k=this,l=this._readableState;switch(l.pipesCount){case 0:l.pipes=a;break;case 1:l.pipes=[l.pipes,a];break;default:l.pipes.push(a)}l.pipesCount+=1;var m=(!b||b.end!==!1)&&a!==c.stdout&&a!==c.stderr,n=m?e:f;l.endEmitted?B(n):k.once("end",n),a.on("unpipe",d);var o=p(k);a.on("drain",o);var s=y.listenerCount(a,"error");return a.once("error",g),a.once("close",h),a.once("finish",i),a.emit("pipe",k),l.flowing||(this.on("readable",r),l.flowing=!0,B(function(){q(k)})),a},e.prototype.unpipe=function(a){var b=this._readableState;if(0===b.pipesCount)return this;if(1===b.pipesCount)return a&&a!==b.pipes?this:(a||(a=b.pipes),b.pipes=null,b.pipesCount=0,this.removeListener("readable",r),b.flowing=!1,a&&a.emit("unpipe",this),this);if(!a){var c=b.pipes,d=b.pipesCount;b.pipes=null,b.pipesCount=0,this.removeListener("readable",r),b.flowing=!1;for(var e=0;d>e;e++)c[e].emit("unpipe",this);return this}var e=w(b.pipes,a);return-1===e?this:(b.pipes.splice(e,1),b.pipesCount-=1,1===b.pipesCount&&(b.pipes=b.pipes[0]),a.emit("unpipe",this),this)},e.prototype.on=function(a,b){var c=z.prototype.on.call(this,a,b);if("data"!==a||this._readableState.flowing||s(this),"readable"===a&&this.readable){var d=this._readableState;d.readableListening||(d.readableListening=!0,d.emittedReadable=!1,d.needReadable=!0,d.reading?d.length&&l(this,d):this.read(0))}return c},e.prototype.addListener=e.prototype.on,e.prototype.resume=function(){s(this),this.read(0),this.emit("resume")},e.prototype.pause=function(){s(this,!0),this.emit("pause")},e.prototype.wrap=function(a){var b=this._readableState,c=!1,d=this;a.on("end",function(){if(b.decoder&&!b.ended){var a=b.decoder.end();a&&a.length&&d.push(a)}d.push(null)}),a.on("data",function(e){if(b.decoder&&(e=b.decoder.write(e)),e&&(b.objectMode||e.length)){var f=d.push(e);f||(c=!0,a.pause())}});for(var e in a)"function"==typeof a[e]&&"undefined"==typeof this[e]&&(this[e]=function(b){return function(){return a[b].apply(a,arguments)}}(e));var f=["error","close","destroy","pause","resume"];return v(f,function(b){a.on(b,function(a){return d.emit.apply(d,b,a)})}),d._read=function(){c&&(c=!1,a.resume())},d},e._fromList=t}).call(this,a("FWaASH"))},{"./index.js":23,FWaASH:17,buffer:1,events:10,inherits:16,"process/browser.js":24,string_decoder:29}],27:[function(a,b){function c(a,b){this.afterTransform=function(a,c){return d(b,a,c)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null}function d(a,b,c){var d=a._transformState;d.transforming=!1;var e=d.writecb;if(!e)return a.emit("error",new Error("no writecb in Transform class"));d.writechunk=null,d.writecb=null,null!==c&&void 0!==c&&a.push(c),e&&e(b);var f=a._readableState;f.reading=!1,(f.needReadable||f.length=this.charLength-this.charReceived?this.charLength-this.charReceived:a.length;if(a.copy(this.charBuffer,this.charReceived,c,d),this.charReceived+=d-c,c=d,this.charReceived=55296&&56319>=e)){if(this.charReceived=this.charLength=0,d==a.length)return b;a=a.slice(d,a.length);break}this.charLength+=this.surrogateSize,b=""}var f=this.detectIncompleteChar(a),g=a.length;this.charLength&&(a.copy(this.charBuffer,0,a.length-f,g),this.charReceived=f,g-=f),b+=a.toString(this.encoding,0,g);var g=b.length-1,e=b.charCodeAt(g);if(e>=55296&&56319>=e){var h=this.surrogateSize;return this.charLength+=h,this.charReceived+=h,this.charBuffer.copy(this.charBuffer,h,0,h),this.charBuffer.write(b.charAt(b.length-1),this.encoding),b.substring(0,g)}return b},i.prototype.detectIncompleteChar=function(a){for(var b=a.length>=3?3:a.length;b>0;b--){var c=a[a.length-b];if(1==b&&c>>5==6){this.charLength=2;break}if(2>=b&&c>>4==14){this.charLength=3;break}if(3>=b&&c>>3==30){this.charLength=4;break}}return b},i.prototype.end=function(a){var b="";if(a&&a.length&&(b=this.write(a)),this.charReceived){var c=this.charReceived,d=this.charBuffer,e=this.encoding;b+=d.slice(0,c).toString(e)}return b}},{buffer:1}],30:[function(a,b,c){function d(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function e(a,b,c){if(a&&j(a)&&a instanceof d)return a;var e=new d;return e.parse(a,b,c),e}function f(a){return i(a)&&(a=e(a)),a instanceof d?a.format():d.prototype.format.call(a)}function g(a,b){return e(a,!1,!0).resolve(b)}function h(a,b){return a?e(a,!1,!0).resolveObject(b):b}function i(a){return"string"==typeof a}function j(a){return"object"==typeof a&&null!==a}function k(a){return null===a}function l(a){return null==a}var m=a("punycode");c.parse=e,c.resolve=g,c.resolveObject=h,c.format=f,c.Url=d;var n=/^([a-z0-9.+-]+:)/i,o=/:[0-9]*$/,p=["<",">",'"',"`"," ","\r","\n"," "],q=["{","}","|","\\","^","`"].concat(p),r=["'"].concat(q),s=["%","/","?",";","#"].concat(r),t=["/","?","#"],u=255,v=/^[a-z0-9A-Z_-]{0,63}$/,w=/^([a-z0-9A-Z_-]{0,63})(.*)$/,x={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},z={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},A=a("querystring");d.prototype.parse=function(a,b,c){if(!i(a))throw new TypeError("Parameter 'url' must be a string, not "+typeof a);var d=a;d=d.trim();var e=n.exec(d);if(e){e=e[0];var f=e.toLowerCase();this.protocol=f,d=d.substr(e.length)}if(c||e||d.match(/^\/\/[^@\/]+@[^@\/]+/)){var g="//"===d.substr(0,2);!g||e&&y[e]||(d=d.substr(2),this.slashes=!0)}if(!y[e]&&(g||e&&!z[e])){for(var h=-1,j=0;jk)&&(h=k)}var l,o;o=-1===h?d.lastIndexOf("@"):d.lastIndexOf("@",h),-1!==o&&(l=d.slice(0,o),d=d.slice(o+1),this.auth=decodeURIComponent(l)),h=-1;for(var j=0;jk)&&(h=k)}-1===h&&(h=d.length),this.host=d.slice(0,h),d=d.slice(h),this.parseHost(),this.hostname=this.hostname||"";var p="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!p)for(var q=this.hostname.split(/\./),j=0,B=q.length;B>j;j++){var C=q[j];if(C&&!C.match(v)){for(var D="",E=0,F=C.length;F>E;E++)D+=C.charCodeAt(E)>127?"x":C[E];if(!D.match(v)){var G=q.slice(0,j),H=q.slice(j+1),I=C.match(w);I&&(G.push(I[1]),H.unshift(I[2])),H.length&&(d="/"+H.join(".")+d),this.hostname=G.join(".");break}}}if(this.hostname=this.hostname.length>u?"":this.hostname.toLowerCase(),!p){for(var J=this.hostname.split("."),K=[],j=0;jj;j++){var O=r[j],P=encodeURIComponent(O);P===O&&(P=escape(O)),d=d.split(O).join(P)}var Q=d.indexOf("#");-1!==Q&&(this.hash=d.substr(Q),d=d.slice(0,Q));var R=d.indexOf("?");if(-1!==R?(this.search=d.substr(R),this.query=d.substr(R+1),b&&(this.query=A.parse(this.query)),d=d.slice(0,R)):b&&(this.search="",this.query={}),d&&(this.pathname=d),z[f]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var M=this.pathname||"",L=this.search||"";this.path=M+L}return this.href=this.format(),this},d.prototype.format=function(){var a=this.auth||"";a&&(a=encodeURIComponent(a),a=a.replace(/%3A/i,":"),a+="@");var b=this.protocol||"",c=this.pathname||"",d=this.hash||"",e=!1,f="";this.host?e=a+this.host:this.hostname&&(e=a+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(e+=":"+this.port)),this.query&&j(this.query)&&Object.keys(this.query).length&&(f=A.stringify(this.query)); var g=this.search||f&&"?"+f||"";return b&&":"!==b.substr(-1)&&(b+=":"),this.slashes||(!b||z[b])&&e!==!1?(e="//"+(e||""),c&&"/"!==c.charAt(0)&&(c="/"+c)):e||(e=""),d&&"#"!==d.charAt(0)&&(d="#"+d),g&&"?"!==g.charAt(0)&&(g="?"+g),c=c.replace(/[?#]/g,function(a){return encodeURIComponent(a)}),g=g.replace("#","%23"),b+e+c+g+d},d.prototype.resolve=function(a){return this.resolveObject(e(a,!1,!0)).format()},d.prototype.resolveObject=function(a){if(i(a)){var b=new d;b.parse(a,!1,!0),a=b}var c=new d;if(Object.keys(this).forEach(function(a){c[a]=this[a]},this),c.hash=a.hash,""===a.href)return c.href=c.format(),c;if(a.slashes&&!a.protocol)return Object.keys(a).forEach(function(b){"protocol"!==b&&(c[b]=a[b])}),z[c.protocol]&&c.hostname&&!c.pathname&&(c.path=c.pathname="/"),c.href=c.format(),c;if(a.protocol&&a.protocol!==c.protocol){if(!z[a.protocol])return Object.keys(a).forEach(function(b){c[b]=a[b]}),c.href=c.format(),c;if(c.protocol=a.protocol,a.host||y[a.protocol])c.pathname=a.pathname;else{for(var e=(a.pathname||"").split("/");e.length&&!(a.host=e.shift()););a.host||(a.host=""),a.hostname||(a.hostname=""),""!==e[0]&&e.unshift(""),e.length<2&&e.unshift(""),c.pathname=e.join("/")}if(c.search=a.search,c.query=a.query,c.host=a.host||"",c.auth=a.auth,c.hostname=a.hostname||a.host,c.port=a.port,c.pathname||c.search){var f=c.pathname||"",g=c.search||"";c.path=f+g}return c.slashes=c.slashes||a.slashes,c.href=c.format(),c}var h=c.pathname&&"/"===c.pathname.charAt(0),j=a.host||a.pathname&&"/"===a.pathname.charAt(0),m=j||h||c.host&&a.pathname,n=m,o=c.pathname&&c.pathname.split("/")||[],e=a.pathname&&a.pathname.split("/")||[],p=c.protocol&&!z[c.protocol];if(p&&(c.hostname="",c.port=null,c.host&&(""===o[0]?o[0]=c.host:o.unshift(c.host)),c.host="",a.protocol&&(a.hostname=null,a.port=null,a.host&&(""===e[0]?e[0]=a.host:e.unshift(a.host)),a.host=null),m=m&&(""===e[0]||""===o[0])),j)c.host=a.host||""===a.host?a.host:c.host,c.hostname=a.hostname||""===a.hostname?a.hostname:c.hostname,c.search=a.search,c.query=a.query,o=e;else if(e.length)o||(o=[]),o.pop(),o=o.concat(e),c.search=a.search,c.query=a.query;else if(!l(a.search)){if(p){c.hostname=c.host=o.shift();var q=c.host&&c.host.indexOf("@")>0?c.host.split("@"):!1;q&&(c.auth=q.shift(),c.host=c.hostname=q.shift())}return c.search=a.search,c.query=a.query,k(c.pathname)&&k(c.search)||(c.path=(c.pathname?c.pathname:"")+(c.search?c.search:"")),c.href=c.format(),c}if(!o.length)return c.pathname=null,c.path=c.search?"/"+c.search:null,c.href=c.format(),c;for(var r=o.slice(-1)[0],s=(c.host||a.host)&&("."===r||".."===r)||""===r,t=0,u=o.length;u>=0;u--)r=o[u],"."==r?o.splice(u,1):".."===r?(o.splice(u,1),t++):t&&(o.splice(u,1),t--);if(!m&&!n)for(;t--;t)o.unshift("..");!m||""===o[0]||o[0]&&"/"===o[0].charAt(0)||o.unshift(""),s&&"/"!==o.join("/").substr(-1)&&o.push("");var v=""===o[0]||o[0]&&"/"===o[0].charAt(0);if(p){c.hostname=c.host=v?"":o.length?o.shift():"";var q=c.host&&c.host.indexOf("@")>0?c.host.split("@"):!1;q&&(c.auth=q.shift(),c.host=c.hostname=q.shift())}return m=m||c.host&&o.length,m&&!v&&o.unshift(""),o.length?c.pathname=o.join("/"):(c.pathname=null,c.path=null),k(c.pathname)&&k(c.search)||(c.path=(c.pathname?c.pathname:"")+(c.search?c.search:"")),c.auth=a.auth||c.auth,c.slashes=c.slashes||a.slashes,c.href=c.format(),c},d.prototype.parseHost=function(){var a=this.host,b=o.exec(a);b&&(b=b[0],":"!==b&&(this.port=b.substr(1)),a=a.substr(0,a.length-b.length)),a&&(this.hostname=a)}},{punycode:18,querystring:21}],31:[function(a,b){b.exports=function(a){return a&&"object"==typeof a&&"function"==typeof a.copy&&"function"==typeof a.fill&&"function"==typeof a.readUInt8}},{}],32:[function(a,b,c){(function(b,d){function e(a,b){var d={seen:[],stylize:g};return arguments.length>=3&&(d.depth=arguments[2]),arguments.length>=4&&(d.colors=arguments[3]),p(b)?d.showHidden=b:b&&c._extend(d,b),v(d.showHidden)&&(d.showHidden=!1),v(d.depth)&&(d.depth=2),v(d.colors)&&(d.colors=!1),v(d.customInspect)&&(d.customInspect=!0),d.colors&&(d.stylize=f),i(d,a,d.depth)}function f(a,b){var c=e.styles[b];return c?"["+e.colors[c][0]+"m"+a+"["+e.colors[c][1]+"m":a}function g(a){return a}function h(a){var b={};return a.forEach(function(a){b[a]=!0}),b}function i(a,b,d){if(a.customInspect&&b&&A(b.inspect)&&b.inspect!==c.inspect&&(!b.constructor||b.constructor.prototype!==b)){var e=b.inspect(d,a);return t(e)||(e=i(a,e,d)),e}var f=j(a,b);if(f)return f;var g=Object.keys(b),p=h(g);if(a.showHidden&&(g=Object.getOwnPropertyNames(b)),z(b)&&(g.indexOf("message")>=0||g.indexOf("description")>=0))return k(b);if(0===g.length){if(A(b)){var q=b.name?": "+b.name:"";return a.stylize("[Function"+q+"]","special")}if(w(b))return a.stylize(RegExp.prototype.toString.call(b),"regexp");if(y(b))return a.stylize(Date.prototype.toString.call(b),"date");if(z(b))return k(b)}var r="",s=!1,u=["{","}"];if(o(b)&&(s=!0,u=["[","]"]),A(b)){var v=b.name?": "+b.name:"";r=" [Function"+v+"]"}if(w(b)&&(r=" "+RegExp.prototype.toString.call(b)),y(b)&&(r=" "+Date.prototype.toUTCString.call(b)),z(b)&&(r=" "+k(b)),0===g.length&&(!s||0==b.length))return u[0]+r+u[1];if(0>d)return w(b)?a.stylize(RegExp.prototype.toString.call(b),"regexp"):a.stylize("[Object]","special");a.seen.push(b);var x;return x=s?l(a,b,d,p,g):g.map(function(c){return m(a,b,d,p,c,s)}),a.seen.pop(),n(x,r,u)}function j(a,b){if(v(b))return a.stylize("undefined","undefined");if(t(b)){var c="'"+JSON.stringify(b).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return a.stylize(c,"string")}return s(b)?a.stylize(""+b,"number"):p(b)?a.stylize(""+b,"boolean"):q(b)?a.stylize("null","null"):void 0}function k(a){return"["+Error.prototype.toString.call(a)+"]"}function l(a,b,c,d,e){for(var f=[],g=0,h=b.length;h>g;++g)f.push(F(b,String(g))?m(a,b,c,d,String(g),!0):"");return e.forEach(function(e){e.match(/^\d+$/)||f.push(m(a,b,c,d,e,!0))}),f}function m(a,b,c,d,e,f){var g,h,j;if(j=Object.getOwnPropertyDescriptor(b,e)||{value:b[e]},j.get?h=j.set?a.stylize("[Getter/Setter]","special"):a.stylize("[Getter]","special"):j.set&&(h=a.stylize("[Setter]","special")),F(d,e)||(g="["+e+"]"),h||(a.seen.indexOf(j.value)<0?(h=q(c)?i(a,j.value,null):i(a,j.value,c-1),h.indexOf("\n")>-1&&(h=f?h.split("\n").map(function(a){return" "+a}).join("\n").substr(2):"\n"+h.split("\n").map(function(a){return" "+a}).join("\n"))):h=a.stylize("[Circular]","special")),v(g)){if(f&&e.match(/^\d+$/))return h;g=JSON.stringify(""+e),g.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(g=g.substr(1,g.length-2),g=a.stylize(g,"name")):(g=g.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),g=a.stylize(g,"string"))}return g+": "+h}function n(a,b,c){var d=0,e=a.reduce(function(a,b){return d++,b.indexOf("\n")>=0&&d++,a+b.replace(/\u001b\[\d\d?m/g,"").length+1},0);return e>60?c[0]+(""===b?"":b+"\n ")+" "+a.join(",\n ")+" "+c[1]:c[0]+b+" "+a.join(", ")+" "+c[1]}function o(a){return Array.isArray(a)}function p(a){return"boolean"==typeof a}function q(a){return null===a}function r(a){return null==a}function s(a){return"number"==typeof a}function t(a){return"string"==typeof a}function u(a){return"symbol"==typeof a}function v(a){return void 0===a}function w(a){return x(a)&&"[object RegExp]"===C(a)}function x(a){return"object"==typeof a&&null!==a}function y(a){return x(a)&&"[object Date]"===C(a)}function z(a){return x(a)&&("[object Error]"===C(a)||a instanceof Error)}function A(a){return"function"==typeof a}function B(a){return null===a||"boolean"==typeof a||"number"==typeof a||"string"==typeof a||"symbol"==typeof a||"undefined"==typeof a}function C(a){return Object.prototype.toString.call(a)}function D(a){return 10>a?"0"+a.toString(10):a.toString(10)}function E(){var a=new Date,b=[D(a.getHours()),D(a.getMinutes()),D(a.getSeconds())].join(":");return[a.getDate(),J[a.getMonth()],b].join(" ")}function F(a,b){return Object.prototype.hasOwnProperty.call(a,b)}var G=/%[sdj%]/g;c.format=function(a){if(!t(a)){for(var b=[],c=0;c=f)return a;switch(a){case"%s":return String(d[c++]);case"%d":return Number(d[c++]);case"%j":try{return JSON.stringify(d[c++])}catch(b){return"[Circular]"}default:return a}}),h=d[c];f>c;h=d[++c])g+=q(h)||!x(h)?" "+h:" "+e(h);return g},c.deprecate=function(a,e){function f(){if(!g){if(b.throwDeprecation)throw new Error(e);b.traceDeprecation?console.trace(e):console.error(e),g=!0}return a.apply(this,arguments)}if(v(d.process))return function(){return c.deprecate(a,e).apply(this,arguments)};if(b.noDeprecation===!0)return a;var g=!1;return f};var H,I={};c.debuglog=function(a){if(v(H)&&(H=b.env.NODE_DEBUG||""),a=a.toUpperCase(),!I[a])if(new RegExp("\\b"+a+"\\b","i").test(H)){var d=b.pid;I[a]=function(){var b=c.format.apply(c,arguments);console.error("%s %d: %s",a,d,b)}}else I[a]=function(){};return I[a]},c.inspect=e,e.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},e.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},c.isArray=o,c.isBoolean=p,c.isNull=q,c.isNullOrUndefined=r,c.isNumber=s,c.isString=t,c.isSymbol=u,c.isUndefined=v,c.isRegExp=w,c.isObject=x,c.isDate=y,c.isError=z,c.isFunction=A,c.isPrimitive=B,c.isBuffer=a("./support/isBuffer");var J=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];c.log=function(){console.log("%s - %s",E(),c.format.apply(c,arguments))},c.inherits=a("inherits"),c._extend=function(a,b){if(!b||!x(b))return a;for(var c=Object.keys(b),d=c.length;d--;)a[c[d]]=b[c[d]];return a}}).call(this,a("FWaASH"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":31,FWaASH:17,inherits:16}],33:[function(a,b,c){function d(a,b){if(!b)return a;var c;for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}function e(a,b){if(!b)return a;var c;for(c in b)b.hasOwnProperty(c)&&("undefined"==typeof a[c]||null===a[c])&&(a[c]=b[c]);return a}function f(a,b,c,d,e,g,h){if(a==b)return a;if(!b)return a;var i,j,k=!1;if(h||(e={a:a},g="a"),c||(k=!0,c=[],d=[]),j=c.indexOf(b),-1!=j)return d[j][0][d[j][1]];c.push(b),d.push([e,g]);for(i in b)b.hasOwnProperty(i)&&("undefined"==typeof a[i]?"object"==typeof b[i]?b[i]instanceof Array?a[i]=f([],b[i],c,d,a,i,!0):null===b[i]?a[i]=null:b[i]instanceof Date?(a[i]=new b[i].constructor,a[i].setTime(b[i].getTime())):a[i]=f({},b[i],c,d,a,i,!0):a[i]=b[i]:a[i]="object"==typeof a[i]&&null!==a[i]?f(a[i],b[i],c,d,a,i,!0):b[i]);return k&&(c=null,d=null),h?a:(e=null,a)}function g(a,b,c,d,e,f,h,i){if(a==b)return a;if(!b)return a;var j,k=!1;if(i||(f={a:a},h="a"),d||(k=!0,d=[],e=[]),b_pos=d.indexOf(b),-1!=b_pos)return e[b_pos][0][e[b_pos][1]];d.push(b),e.push([f,h]);for(j in b)b.hasOwnProperty(j)&&("undefined"==typeof a[j]?"object"==typeof b[j]&&c>0?b[j]instanceof Array?a[j]=g([],b[j],c-1,d,e,a,j,!0):null===b[j]?a[j]=null:b[j]instanceof Date?(a[j]=new b[j].constructor,a[j].setTime(b[j].getTime())):a[j]=g({},b[j],c-1,d,e,a,j,!0):a[j]=b[j]:a[j]="object"==typeof a[j]&&null!==a[j]&&c>0?g(a[j],b[j],c-1,d,e,a,j,!0):b[j]);return k&&(d=null,e=null),i?a:(f=null,a)}function h(a){if("object"==typeof a){if(null===a)return null;if(a instanceof Array)return f([],a);if(a instanceof Date){var b=new a.constructor;return b.setTime(a.getTime()),b}return f({},a)}return a}function i(a,b){return"object"==typeof a?null===a?null:f(h(a),b):a}function j(a,b){return"object"==typeof a?null===a?null:a instanceof Array?g([],a,b):g({},a,b):a}function k(a,b,c){if(a){if("object"==typeof a&&a instanceof Array)return a.forEach(a,b,c);if(a)for(var d in a)if(a.hasOwnProperty(d)&&b.call(c,a[d],d,a)===!1)break}}c.replace=d,c.add=e,c.extend=f,c.extenduptolevel=g,c.clone=h,c.cloneextend=i,c.cloneuptolevel=j,c.foreach=k},{}],34:[function(a,b){(function(a){var c=b.exports=function(){if(arguments.length<1||"object"!=typeof arguments[0])return!1;if(arguments.length<2)return arguments[0];var b,d,e,f,g,h=arguments[0],i=Array.prototype.slice.call(arguments,1);return i.forEach(function(i){if("object"==typeof i)for(b in i)b in i&&(e=h[b],d=i[b],d!==h&&("object"==typeof d&&null!==d?d instanceof a?(g=new a(d.length),d.copy(g),h[b]=g):d instanceof Date?h[b]=new Date(d.getTime()):"object"==typeof e&&null!==e?(f=Array.isArray(d)?Array.isArray(e)?e:[]:Array.isArray(e)?{}:e,h[b]=c(f,d)):(f=Array.isArray(d)?[]:{},h[b]=c(f,d)):h[b]=d))}),h}}).call(this,a("buffer").Buffer)},{buffer:1}],35:[function(a,b,c){!function(){function a(){this._events={},this._conf&&b.call(this,this._conf)}function b(a){a&&(this._conf=a,a.delimiter&&(this.delimiter=a.delimiter),a.maxListeners&&(this._events.maxListeners=a.maxListeners),a.wildcard&&(this.wildcard=a.wildcard),a.newListener&&(this.newListener=a.newListener),this.wildcard&&(this.listenerTree={}))}function d(a){this._events={},this.newListener=!1,b.call(this,a)}function e(a,b,c,d){if(!c)return[];var f,g,h,i,j,k,l,m=[],n=b.length,o=b[d],p=b[d+1];if(d===n&&c._listeners){if("function"==typeof c._listeners)return a&&a.push(c._listeners),[c];for(f=0,g=c._listeners.length;g>f;f++)a&&a.push(c._listeners[f]);return[c]}if("*"===o||"**"===o||c[o]){if("*"===o){for(h in c)"_listeners"!==h&&c.hasOwnProperty(h)&&(m=m.concat(e(a,b,c[h],d+1)));return m}if("**"===o){l=d+1===n||d+2===n&&"*"===p,l&&c._listeners&&(m=m.concat(e(a,b,c,n)));for(h in c)"_listeners"!==h&&c.hasOwnProperty(h)&&("*"===h||"**"===h?(c[h]._listeners&&!l&&(m=m.concat(e(a,b,c[h],n))),m=m.concat(e(a,b,c[h],d))):m=m.concat(h===p?e(a,b,c[h],d+2):e(a,b,c[h],d)));return m}m=m.concat(e(a,b,c[o],d+1))}if(i=c["*"],i&&e(a,b,i,d+1),j=c["**"])if(n>d){j._listeners&&e(a,b,j,n);for(h in j)"_listeners"!==h&&j.hasOwnProperty(h)&&(h===p?e(a,b,j[h],d+2):h===o?e(a,b,j[h],d+1):(k={},k[h]=j[h],e(a,b,{"**":k},d+1)))}else j._listeners?e(a,b,j,n):j["*"]&&j["*"]._listeners&&e(a,b,j["*"],n);return m}function f(a,b){a="string"==typeof a?a.split(this.delimiter):a.slice();for(var c=0,d=a.length;d>c+1;c++)if("**"===a[c]&&"**"===a[c+1])return;for(var e=this.listenerTree,f=a.shift();f;){if(e[f]||(e[f]={}),e=e[f],0===a.length){if(e._listeners){if("function"==typeof e._listeners)e._listeners=[e._listeners,b];else if(g(e._listeners)&&(e._listeners.push(b),!e._listeners.warned)){var i=h;"undefined"!=typeof this._events.maxListeners&&(i=this._events.maxListeners),i>0&&e._listeners.length>i&&(e._listeners.warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",e._listeners.length),console.trace())}}else e._listeners=b;return!0}f=a.shift()}return!0}var g=Array.isArray?Array.isArray:function(a){return"[object Array]"===Object.prototype.toString.call(a)},h=10;d.prototype.delimiter=".",d.prototype.setMaxListeners=function(b){this._events||a.call(this),this._events.maxListeners=b,this._conf||(this._conf={}),this._conf.maxListeners=b},d.prototype.event="",d.prototype.once=function(a,b){return this.many(a,1,b),this},d.prototype.many=function(a,b,c){function d(){0===--b&&e.off(a,d),c.apply(this,arguments)}var e=this;if("function"!=typeof c)throw new Error("many only accepts instances of Function");return d._origin=c,this.on(a,d),e},d.prototype.emit=function(){this._events||a.call(this);var b=arguments[0];if("newListener"===b&&!this.newListener&&!this._events.newListener)return!1;if(this._all){for(var c=arguments.length,d=new Array(c-1),f=1;c>f;f++)d[f-1]=arguments[f];for(f=0,c=this._all.length;c>f;f++)this.event=b,this._all[f].apply(this,d)}if("error"===b&&!(this._all||this._events.error||this.wildcard&&this.listenerTree.error))throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");var g;if(this.wildcard){g=[];var h="string"==typeof b?b.split(this.delimiter):b.slice();e.call(this,g,h,this.listenerTree,0)}else g=this._events[b];if("function"==typeof g){if(this.event=b,1===arguments.length)g.call(this);else if(arguments.length>1)switch(arguments.length){case 2:g.call(this,arguments[1]);break;case 3:g.call(this,arguments[1],arguments[2]);break;default:for(var c=arguments.length,d=new Array(c-1),f=1;c>f;f++)d[f-1]=arguments[f];g.apply(this,d)}return!0}if(g){for(var c=arguments.length,d=new Array(c-1),f=1;c>f;f++)d[f-1]=arguments[f];for(var i=g.slice(),f=0,c=i.length;c>f;f++)this.event=b,i[f].apply(this,d);return i.length>0||!!this._all}return!!this._all},d.prototype.on=function(b,c){if("function"==typeof b)return this.onAny(b),this;if("function"!=typeof c)throw new Error("on only accepts instances of Function");if(this._events||a.call(this),this.emit("newListener",b,c),this.wildcard)return f.call(this,b,c),this;if(this._events[b]){if("function"==typeof this._events[b])this._events[b]=[this._events[b],c];else if(g(this._events[b])&&(this._events[b].push(c),!this._events[b].warned)){var d=h;"undefined"!=typeof this._events.maxListeners&&(d=this._events.maxListeners),d>0&&this._events[b].length>d&&(this._events[b].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[b].length),console.trace())}}else this._events[b]=c;return this},d.prototype.onAny=function(a){if("function"!=typeof a)throw new Error("onAny only accepts instances of Function");return this._all||(this._all=[]),this._all.push(a),this},d.prototype.addListener=d.prototype.on,d.prototype.off=function(a,b){if("function"!=typeof b)throw new Error("removeListener only takes instances of Function");var c,d=[];if(this.wildcard){var f="string"==typeof a?a.split(this.delimiter):a.slice();d=e.call(this,null,f,this.listenerTree,0)}else{if(!this._events[a])return this;c=this._events[a],d.push({_listeners:c})}for(var h=0;hk;k++)if(c[k]===b||c[k].listener&&c[k].listener===b||c[k]._origin&&c[k]._origin===b){j=k;break}if(0>j)continue;return this.wildcard?i._listeners.splice(j,1):this._events[a].splice(j,1),0===c.length&&(this.wildcard?delete i._listeners:delete this._events[a]),this}(c===b||c.listener&&c.listener===b||c._origin&&c._origin===b)&&(this.wildcard?delete i._listeners:delete this._events[a])}return this},d.prototype.offAny=function(a){var b,c=0,d=0;if(a&&this._all&&this._all.length>0){for(b=this._all,c=0,d=b.length;d>c;c++)if(a===b[c])return b.splice(c,1),this}else this._all=[];return this},d.prototype.removeListener=d.prototype.off,d.prototype.removeAllListeners=function(b){if(0===arguments.length)return!this._events||a.call(this),this;if(this.wildcard)for(var c="string"==typeof b?b.split(this.delimiter):b.slice(),d=e.call(this,null,c,this.listenerTree,0),f=0;fa?Math.ceil(a):Math.floor(a)}function m(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.lengthd;d++)(c&&a[d]!==b[d]||!c&&u(a[d])!==u(b[d]))&&g++;return g+f}function r(a){if(a){var b=a.toLowerCase().replace(/(.)s$/,"$1");a=Vb[a]||Wb[b]||b}return a}function s(a){var b,c,d={};for(c in a)a.hasOwnProperty(c)&&(b=r(c),b&&(d[b]=a[c]));return d}function t(a){var b,d;if(0===a.indexOf("week"))b=7,d="day";else{if(0!==a.indexOf("month"))return;b=12,d="month"}fb[a]=function(e,f){var g,h,i=fb.fn._lang[a],j=[];if("number"==typeof e&&(f=e,e=c),h=function(a){var b=fb().utc().set(d,a);return i.call(fb.fn._lang,b,e||"")},null!=f)return h(f);for(g=0;b>g;g++)j.push(h(g));return j}}function u(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function v(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function w(a){return x(a)?366:365}function x(a){return a%4===0&&a%100!==0||a%400===0}function y(a){var b;a._a&&-2===a._pf.overflow&&(b=a._a[lb]<0||a._a[lb]>11?lb:a._a[mb]<1||a._a[mb]>v(a._a[kb],a._a[lb])?mb:a._a[nb]<0||a._a[nb]>23?nb:a._a[ob]<0||a._a[ob]>59?ob:a._a[pb]<0||a._a[pb]>59?pb:a._a[qb]<0||a._a[qb]>999?qb:-1,a._pf._overflowDayOfYear&&(kb>b||b>mb)&&(b=mb),a._pf.overflow=b)}function z(a){return null==a._isValid&&(a._isValid=!isNaN(a._d.getTime())&&a._pf.overflow<0&&!a._pf.empty&&!a._pf.invalidMonth&&!a._pf.nullInput&&!a._pf.invalidFormat&&!a._pf.userInvalidated,a._strict&&(a._isValid=a._isValid&&0===a._pf.charsLeftOver&&0===a._pf.unusedTokens.length)),a._isValid}function A(a){return a?a.toLowerCase().replace("_","-"):a}function B(a,b){return b._isUTC?fb(a).zone(b._offset||0):fb(a).local()}function C(a,b){return b.abbr=a,rb[a]||(rb[a]=new g),rb[a].set(b),rb[a]}function D(a){delete rb[a]}function E(b){var c,d,e,f,g=0,h=function(b){if(!rb[b]&&tb)try{a("./lang/"+b)}catch(c){}return rb[b]};if(!b)return fb.fn._lang;if(!o(b)){if(d=h(b))return d;b=[b]}for(;g0;){if(d=h(f.slice(0,c).join("-")))return d;if(e&&e.length>=c&&q(f,e,!0)>=c-1)break;c--}g++}return fb.fn._lang}function F(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function G(a){var b,c,d=a.match(xb);for(b=0,c=d.length;c>b;b++)d[b]=$b[d[b]]?$b[d[b]]:F(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function H(a,b){return a.isValid()?(b=I(b,a.lang()),Xb[b]||(Xb[b]=G(b)),Xb[b](a)):a.lang().invalidDate()}function I(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(yb.lastIndex=0;d>=0&&yb.test(a);)a=a.replace(yb,c),yb.lastIndex=0,d-=1;return a}function J(a,b){var c,d=b._strict;switch(a){case"DDDD":return Kb;case"YYYY":case"GGGG":case"gggg":return d?Lb:Bb;case"Y":case"G":case"g":return Nb;case"YYYYYY":case"YYYYY":case"GGGGG":case"ggggg":return d?Mb:Cb;case"S":if(d)return Ib;case"SS":if(d)return Jb;case"SSS":if(d)return Kb;case"DDD":return Ab;case"MMM":case"MMMM":case"dd":case"ddd":case"dddd":return Eb;case"a":case"A":return E(b._l)._meridiemParse;case"X":return Hb;case"Z":case"ZZ":return Fb;case"T":return Gb;case"SSSS":return Db;case"MM":case"DD":case"YY":case"GG":case"gg":case"HH":case"hh":case"mm":case"ss":case"ww":case"WW":return d?Jb:zb;case"M":case"D":case"d":case"H":case"h":case"m":case"s":case"w":case"W":case"e":case"E":return zb;default:return c=new RegExp(R(Q(a.replace("\\","")),"i"))}}function K(a){a=a||"";var b=a.match(Fb)||[],c=b[b.length-1]||[],d=(c+"").match(Sb)||["-",0,0],e=+(60*d[1])+u(d[2]);return"+"===d[0]?-e:e}function L(a,b,c){var d,e=c._a;switch(a){case"M":case"MM":null!=b&&(e[lb]=u(b)-1);break;case"MMM":case"MMMM":d=E(c._l).monthsParse(b),null!=d?e[lb]=d:c._pf.invalidMonth=b;break;case"D":case"DD":null!=b&&(e[mb]=u(b));break;case"DDD":case"DDDD":null!=b&&(c._dayOfYear=u(b));break;case"YY":e[kb]=u(b)+(u(b)>68?1900:2e3);break;case"YYYY":case"YYYYY":case"YYYYYY":e[kb]=u(b);break;case"a":case"A":c._isPm=E(c._l).isPM(b);break;case"H":case"HH":case"h":case"hh":e[nb]=u(b);break;case"m":case"mm":e[ob]=u(b);break;case"s":case"ss":e[pb]=u(b);break;case"S":case"SS":case"SSS":case"SSSS":e[qb]=u(1e3*("0."+b));break;case"X":c._d=new Date(1e3*parseFloat(b));break;case"Z":case"ZZ":c._useUTC=!0,c._tzm=K(b);break;case"w":case"ww":case"W":case"WW":case"d":case"dd":case"ddd":case"dddd":case"e":case"E":a=a.substr(0,1);case"gg":case"gggg":case"GG":case"GGGG":case"GGGGG":a=a.substr(0,2),b&&(c._w=c._w||{},c._w[a]=b)}}function M(a){var b,c,d,e,f,g,h,i,j,k,l=[];if(!a._d){for(d=O(a),a._w&&null==a._a[mb]&&null==a._a[lb]&&(f=function(b){var c=parseInt(b,10);return b?b.length<3?c>68?1900+c:2e3+c:c:null==a._a[kb]?fb().weekYear():a._a[kb]},g=a._w,null!=g.GG||null!=g.W||null!=g.E?h=_(f(g.GG),g.W||1,g.E,4,1):(i=E(a._l),j=null!=g.d?X(g.d,i):null!=g.e?parseInt(g.e,10)+i._week.dow:0,k=parseInt(g.w,10)||1,null!=g.d&&jw(e)&&(a._pf._overflowDayOfYear=!0),c=W(e,0,a._dayOfYear),a._a[lb]=c.getUTCMonth(),a._a[mb]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=l[b]=d[b];for(;7>b;b++)a._a[b]=l[b]=null==a._a[b]?2===b?1:0:a._a[b];l[nb]+=u((a._tzm||0)/60),l[ob]+=u((a._tzm||0)%60),a._d=(a._useUTC?W:V).apply(null,l)}}function N(a){var b;a._d||(b=s(a._i),a._a=[b.year,b.month,b.day,b.hour,b.minute,b.second,b.millisecond],M(a))}function O(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function P(a){a._a=[],a._pf.empty=!0;var b,c,d,e,f,g=E(a._l),h=""+a._i,i=h.length,j=0;for(d=I(a._f,g).match(xb)||[],b=0;b0&&a._pf.unusedInput.push(f),h=h.slice(h.indexOf(c)+c.length),j+=c.length),$b[e]?(c?a._pf.empty=!1:a._pf.unusedTokens.push(e),L(e,c,a)):a._strict&&!c&&a._pf.unusedTokens.push(e);a._pf.charsLeftOver=i-j,h.length>0&&a._pf.unusedInput.push(h),a._isPm&&a._a[nb]<12&&(a._a[nb]+=12),a._isPm===!1&&12===a._a[nb]&&(a._a[nb]=0),M(a),y(a)}function Q(a){return a.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e})}function R(a){return a.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function S(a){var b,c,e,f,g;if(0===a._f.length)return a._pf.invalidFormat=!0,void(a._d=new Date(0/0));for(f=0;fg)&&(e=g,c=b));j(a,c||b)}function T(a){var b,c,d=a._i,e=Ob.exec(d);if(e){for(a._pf.iso=!0,b=0,c=Qb.length;c>b;b++)if(Qb[b][1].exec(d)){a._f=Qb[b][0]+(e[6]||" ");break}for(b=0,c=Rb.length;c>b;b++)if(Rb[b][1].exec(d)){a._f+=Rb[b][0];break}d.match(Fb)&&(a._f+="Z"),P(a)}else a._d=new Date(d)}function U(a){var b=a._i,d=ub.exec(b);b===c?a._d=new Date:d?a._d=new Date(+d[1]):"string"==typeof b?T(a):o(b)?(a._a=b.slice(0),M(a)):p(b)?a._d=new Date(+b):"object"==typeof b?N(a):a._d=new Date(b)}function V(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function W(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function X(a,b){if("string"==typeof a)if(isNaN(a)){if(a=b.weekdaysParse(a),"number"!=typeof a)return null}else a=parseInt(a,10);return a}function Y(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function Z(a,b,c){var d=jb(Math.abs(a)/1e3),e=jb(d/60),f=jb(e/60),g=jb(f/24),h=jb(g/365),i=45>d&&["s",d]||1===e&&["m"]||45>e&&["mm",e]||1===f&&["h"]||22>f&&["hh",f]||1===g&&["d"]||25>=g&&["dd",g]||45>=g&&["M"]||345>g&&["MM",jb(g/30)]||1===h&&["y"]||["yy",h];return i[2]=b,i[3]=a>0,i[4]=c,Y.apply({},i)}function $(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=fb(a).add("d",f),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function _(a,b,c,d,e){var f,g,h=W(a,0,1).getUTCDay();return c=null!=c?c:e,f=e-h+(h>d?7:0)-(e>h?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:w(a-1)+g}}function ab(a){var b=a._i,c=a._f;return null===b?fb.invalid({nullInput:!0}):("string"==typeof b&&(a._i=b=E().preparse(b)),fb.isMoment(b)?(a=k(b),a._d=new Date(+b._d)):c?o(c)?S(a):P(a):U(a),new h(a))}function bb(a,b){fb.fn[a]=fb.fn[a+"s"]=function(a){var c=this._isUTC?"UTC":"";return null!=a?(this._d["set"+c+b](a),fb.updateOffset(this),this):this._d["get"+c+b]()}}function cb(a){fb.duration.fn[a]=function(){return this._data[a]}}function db(a,b){fb.duration.fn["as"+a]=function(){return+this/b}}function eb(a){var b=!1,c=fb;"undefined"==typeof ender&&(a?(ib.moment=function(){return!b&&console&&console.warn&&(b=!0,console.warn("Accessing Moment through the global scope is deprecated, and will be removed in an upcoming release.")),c.apply(null,arguments)},j(ib.moment,c)):ib.moment=fb)}for(var fb,gb,hb="2.5.1",ib=this,jb=Math.round,kb=0,lb=1,mb=2,nb=3,ob=4,pb=5,qb=6,rb={},sb={_isAMomentObject:null,_i:null,_f:null,_l:null,_strict:null,_isUTC:null,_offset:null,_pf:null,_lang:null},tb="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a,ub=/^\/?Date\((\-?\d+)/i,vb=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,wb=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/,xb=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g,yb=/(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g,zb=/\d\d?/,Ab=/\d{1,3}/,Bb=/\d{1,4}/,Cb=/[+\-]?\d{1,6}/,Db=/\d+/,Eb=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,Fb=/Z|[\+\-]\d\d:?\d\d/gi,Gb=/T/i,Hb=/[\+\-]?\d+(\.\d{1,3})?/,Ib=/\d/,Jb=/\d\d/,Kb=/\d{3}/,Lb=/\d{4}/,Mb=/[+-]?\d{6}/,Nb=/[+-]?\d+/,Ob=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Pb="YYYY-MM-DDTHH:mm:ssZ",Qb=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],Rb=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d{1,3}/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],Sb=/([\+\-]|\d\d)/gi,Tb="Date|Hours|Minutes|Seconds|Milliseconds".split("|"),Ub={Milliseconds:1,Seconds:1e3,Minutes:6e4,Hours:36e5,Days:864e5,Months:2592e6,Years:31536e6},Vb={ms:"millisecond",s:"second",m:"minute",h:"hour",d:"day",D:"date",w:"week",W:"isoWeek",M:"month",y:"year",DDD:"dayOfYear",e:"weekday",E:"isoWeekday",gg:"weekYear",GG:"isoWeekYear"},Wb={dayofyear:"dayOfYear",isoweekday:"isoWeekday",isoweek:"isoWeek",weekyear:"weekYear",isoweekyear:"isoWeekYear"},Xb={},Yb="DDD w W M D d".split(" "),Zb="M D H h m s w W".split(" "),$b={M:function(){return this.month()+1},MMM:function(a){return this.lang().monthsShort(this,a)},MMMM:function(a){return this.lang().months(this,a)},D:function(){return this.date()},DDD:function(){return this.dayOfYear()},d:function(){return this.day()},dd:function(a){return this.lang().weekdaysMin(this,a)},ddd:function(a){return this.lang().weekdaysShort(this,a) },dddd:function(a){return this.lang().weekdays(this,a)},w:function(){return this.week()},W:function(){return this.isoWeek()},YY:function(){return m(this.year()%100,2)},YYYY:function(){return m(this.year(),4)},YYYYY:function(){return m(this.year(),5)},YYYYYY:function(){var a=this.year(),b=a>=0?"+":"-";return b+m(Math.abs(a),6)},gg:function(){return m(this.weekYear()%100,2)},gggg:function(){return m(this.weekYear(),4)},ggggg:function(){return m(this.weekYear(),5)},GG:function(){return m(this.isoWeekYear()%100,2)},GGGG:function(){return m(this.isoWeekYear(),4)},GGGGG:function(){return m(this.isoWeekYear(),5)},e:function(){return this.weekday()},E:function(){return this.isoWeekday()},a:function(){return this.lang().meridiem(this.hours(),this.minutes(),!0)},A:function(){return this.lang().meridiem(this.hours(),this.minutes(),!1)},H:function(){return this.hours()},h:function(){return this.hours()%12||12},m:function(){return this.minutes()},s:function(){return this.seconds()},S:function(){return u(this.milliseconds()/100)},SS:function(){return m(u(this.milliseconds()/10),2)},SSS:function(){return m(this.milliseconds(),3)},SSSS:function(){return m(this.milliseconds(),3)},Z:function(){var a=-this.zone(),b="+";return 0>a&&(a=-a,b="-"),b+m(u(a/60),2)+":"+m(u(a)%60,2)},ZZ:function(){var a=-this.zone(),b="+";return 0>a&&(a=-a,b="-"),b+m(u(a/60),2)+m(u(a)%60,2)},z:function(){return this.zoneAbbr()},zz:function(){return this.zoneName()},X:function(){return this.unix()},Q:function(){return this.quarter()}},_b=["months","monthsShort","weekdays","weekdaysShort","weekdaysMin"];Yb.length;)gb=Yb.pop(),$b[gb+"o"]=f($b[gb],gb);for(;Zb.length;)gb=Zb.pop(),$b[gb+gb]=e($b[gb],2);for($b.DDDD=e($b.DDD,3),j(g.prototype,{set:function(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b},_months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),months:function(a){return this._months[a.month()]},_monthsShort:"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),monthsShort:function(a){return this._monthsShort[a.month()]},monthsParse:function(a){var b,c,d;for(this._monthsParse||(this._monthsParse=[]),b=0;12>b;b++)if(this._monthsParse[b]||(c=fb.utc([2e3,b]),d="^"+this.months(c,"")+"|^"+this.monthsShort(c,""),this._monthsParse[b]=new RegExp(d.replace(".",""),"i")),this._monthsParse[b].test(a))return b},_weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),weekdays:function(a){return this._weekdays[a.day()]},_weekdaysShort:"Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),weekdaysShort:function(a){return this._weekdaysShort[a.day()]},_weekdaysMin:"Su_Mo_Tu_We_Th_Fr_Sa".split("_"),weekdaysMin:function(a){return this._weekdaysMin[a.day()]},weekdaysParse:function(a){var b,c,d;for(this._weekdaysParse||(this._weekdaysParse=[]),b=0;7>b;b++)if(this._weekdaysParse[b]||(c=fb([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b},_longDateFormat:{LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D YYYY",LLL:"MMMM D YYYY LT",LLLL:"dddd, MMMM D YYYY LT"},longDateFormat:function(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b},isPM:function(a){return"p"===(a+"").toLowerCase().charAt(0)},_meridiemParse:/[ap]\.?m?\.?/i,meridiem:function(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"},_calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},calendar:function(a,b){var c=this._calendar[a];return"function"==typeof c?c.apply(b):c},_relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},relativeTime:function(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)},pastFuture:function(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)},ordinal:function(a){return this._ordinal.replace("%d",a)},_ordinal:"%d",preparse:function(a){return a},postformat:function(a){return a},week:function(a){return $(a,this._week.dow,this._week.doy).week},_week:{dow:0,doy:6},_invalidDate:"Invalid date",invalidDate:function(){return this._invalidDate}}),fb=function(a,b,e,f){var g;return"boolean"==typeof e&&(f=e,e=c),g={},g._isAMomentObject=!0,g._i=a,g._f=b,g._l=e,g._strict=f,g._isUTC=!1,g._pf=d(),ab(g)},fb.utc=function(a,b,e,f){var g;return"boolean"==typeof e&&(f=e,e=c),g={},g._isAMomentObject=!0,g._useUTC=!0,g._isUTC=!0,g._l=e,g._i=a,g._f=b,g._strict=f,g._pf=d(),ab(g).utc()},fb.unix=function(a){return fb(1e3*a)},fb.duration=function(a,b){var c,d,e,f=a,g=null;return fb.isDuration(a)?f={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(f={},b?f[b]=a:f.milliseconds=a):(g=vb.exec(a))?(c="-"===g[1]?-1:1,f={y:0,d:u(g[mb])*c,h:u(g[nb])*c,m:u(g[ob])*c,s:u(g[pb])*c,ms:u(g[qb])*c}):(g=wb.exec(a))&&(c="-"===g[1]?-1:1,e=function(a){var b=a&&parseFloat(a.replace(",","."));return(isNaN(b)?0:b)*c},f={y:e(g[2]),M:e(g[3]),d:e(g[4]),h:e(g[5]),m:e(g[6]),s:e(g[7]),w:e(g[8])}),d=new i(f),fb.isDuration(a)&&a.hasOwnProperty("_lang")&&(d._lang=a._lang),d},fb.version=hb,fb.defaultFormat=Pb,fb.updateOffset=function(){},fb.lang=function(a,b){var c;return a?(b?C(A(a),b):null===b?(D(a),a="en"):rb[a]||E(a),c=fb.duration.fn._lang=fb.fn._lang=E(a),c._abbr):fb.fn._lang._abbr},fb.langData=function(a){return a&&a._lang&&a._lang._abbr&&(a=a._lang._abbr),E(a)},fb.isMoment=function(a){return a instanceof h||null!=a&&a.hasOwnProperty("_isAMomentObject")},fb.isDuration=function(a){return a instanceof i},gb=_b.length-1;gb>=0;--gb)t(_b[gb]);for(fb.normalizeUnits=function(a){return r(a)},fb.invalid=function(a){var b=fb.utc(0/0);return null!=a?j(b._pf,a):b._pf.userInvalidated=!0,b},fb.parseZone=function(a){return fb(a).parseZone()},j(fb.fn=h.prototype,{clone:function(){return fb(this)},valueOf:function(){return+this._d+6e4*(this._offset||0)},unix:function(){return Math.floor(+this/1e3)},toString:function(){return this.clone().lang("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},toDate:function(){return this._offset?new Date(+this):this._d},toISOString:function(){var a=fb(this).utc();return 00:!1},parsingFlags:function(){return j({},this._pf)},invalidAt:function(){return this._pf.overflow},utc:function(){return this.zone(0)},local:function(){return this.zone(0),this._isUTC=!1,this},format:function(a){var b=H(this,a||fb.defaultFormat);return this.lang().postformat(b)},add:function(a,b){var c;return c="string"==typeof a?fb.duration(+b,a):fb.duration(a,b),n(this,c,1),this},subtract:function(a,b){var c;return c="string"==typeof a?fb.duration(+b,a):fb.duration(a,b),n(this,c,-1),this},diff:function(a,b,c){var d,e,f=B(a,this),g=6e4*(this.zone()-f.zone());return b=r(b),"year"===b||"month"===b?(d=432e5*(this.daysInMonth()+f.daysInMonth()),e=12*(this.year()-f.year())+(this.month()-f.month()),e+=(this-fb(this).startOf("month")-(f-fb(f).startOf("month")))/d,e-=6e4*(this.zone()-fb(this).startOf("month").zone()-(f.zone()-fb(f).startOf("month").zone()))/d,"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:l(e)},from:function(a,b){return fb.duration(this.diff(a)).lang(this.lang()._abbr).humanize(!b)},fromNow:function(a){return this.from(fb(),a)},calendar:function(){var a=B(fb(),this).startOf("day"),b=this.diff(a,"days",!0),c=-6>b?"sameElse":-1>b?"lastWeek":0>b?"lastDay":1>b?"sameDay":2>b?"nextDay":7>b?"nextWeek":"sameElse";return this.format(this.lang().calendar(c,this))},isLeapYear:function(){return x(this.year())},isDST:function(){return this.zone()+fb(a).startOf(b)},isBefore:function(a,b){return b="undefined"!=typeof b?b:"millisecond",+this.clone().startOf(b)<+fb(a).startOf(b)},isSame:function(a,b){return b=b||"ms",+this.clone().startOf(b)===+B(a,this).startOf(b)},min:function(a){return a=fb.apply(null,arguments),this>a?this:a},max:function(a){return a=fb.apply(null,arguments),a>this?this:a},zone:function(a){var b=this._offset||0;return null==a?this._isUTC?b:this._d.getTimezoneOffset():("string"==typeof a&&(a=K(a)),Math.abs(a)<16&&(a=60*a),this._offset=a,this._isUTC=!0,b!==a&&n(this,fb.duration(b-a,"m"),1,!0),this)},zoneAbbr:function(){return this._isUTC?"UTC":""},zoneName:function(){return this._isUTC?"Coordinated Universal Time":""},parseZone:function(){return this._tzm?this.zone(this._tzm):"string"==typeof this._i&&this.zone(this._i),this},hasAlignedHourOffset:function(a){return a=a?fb(a).zone():0,(this.zone()-a)%60===0},daysInMonth:function(){return v(this.year(),this.month())},dayOfYear:function(a){var b=jb((fb(this).startOf("day")-fb(this).startOf("year"))/864e5)+1;return null==a?b:this.add("d",a-b)},quarter:function(){return Math.ceil((this.month()+1)/3)},weekYear:function(a){var b=$(this,this.lang()._week.dow,this.lang()._week.doy).year;return null==a?b:this.add("y",a-b)},isoWeekYear:function(a){var b=$(this,1,4).year;return null==a?b:this.add("y",a-b)},week:function(a){var b=this.lang().week(this);return null==a?b:this.add("d",7*(a-b))},isoWeek:function(a){var b=$(this,1,4).week;return null==a?b:this.add("d",7*(a-b))},weekday:function(a){var b=(this.day()+7-this.lang()._week.dow)%7;return null==a?b:this.add("d",a-b)},isoWeekday:function(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)},get:function(a){return a=r(a),this[a]()},set:function(a,b){return a=r(a),"function"==typeof this[a]&&this[a](b),this},lang:function(a){return a===c?this._lang:(this._lang=E(a),this)}}),gb=0;gb0&&!this.encoding){var a=this.packetBuffer.shift();this.packet(a)}},c.prototype.cleanup=function(){for(var a;a=this.subs.shift();)a.destroy();this.packetBuffer=[],this.encoding=!1,this.decoder.destroy()},c.prototype.close=c.prototype.disconnect=function(){this.skipReconnect=!0,this.engine.close()},c.prototype.onclose=function(a){j("close"),this.cleanup(),this.readyState="closed",this.emit("close",a),this._reconnection&&!this.skipReconnect&&this.reconnect()},c.prototype.reconnect=function(){if(this.reconnecting)return this;var a=this;if(this.attempts++,this.attempts>this._reconnectionAttempts)j("reconnect failed"),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var b=this.attempts*this.reconnectionDelay();b=Math.min(b,this.reconnectionDelayMax()),j("will wait %dms before reconnect attempt",b),this.reconnecting=!0;var c=setTimeout(function(){j("attempting reconnect"),a.emitAll("reconnect_attempt",a.attempts),a.emitAll("reconnecting",a.attempts),a.open(function(b){b?(j("reconnect attempt error"),a.reconnecting=!1,a.reconnect(),a.emitAll("reconnect_error",b.data)):(j("reconnect success"),a.onreconnect())})},b);this.subs.push({destroy:function(){clearTimeout(c)}})}},c.prototype.onreconnect=function(){var a=this.attempts;this.attempts=0,this.reconnecting=!1,this.emitAll("reconnect",a)}},{"./on":40,"./socket":41,"./url":42,"component-bind":43,"component-emitter":44,debug:45,"engine.io-client":46,"object-component":73,"socket.io-parser":76}],40:[function(a,b){function c(a,b,c){return a.on(b,c),{destroy:function(){a.removeListener(b,c)}}}b.exports=c},{}],41:[function(a,b,c){function d(a,b){this.io=a,this.nsp=b,this.json=this,this.ids=0,this.acks={},this.io.autoConnect&&this.open(),this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.subEvents()}{var e=a("socket.io-parser"),f=a("component-emitter"),g=a("to-array"),h=a("./on"),i=a("component-bind"),j=a("debug")("socket.io-client:socket"),k=a("has-binary");a("indexof")}b.exports=c=d;var l={connect:1,connect_error:1,connect_timeout:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1},m=f.prototype.emit;f(d.prototype),d.prototype.subEvents=function(){var a=this.io;this.subs=[h(a,"open",i(this,"onopen")),h(a,"packet",i(this,"onpacket")),h(a,"close",i(this,"onclose"))]},d.prototype.open=d.prototype.connect=function(){return this.connected?this:(this.io.open(),"open"==this.io.readyState&&this.onopen(),this)},d.prototype.send=function(){var a=g(arguments);return a.unshift("message"),this.emit.apply(this,a),this},d.prototype.emit=function(a){if(l.hasOwnProperty(a))return m.apply(this,arguments),this;var b=g(arguments),c=e.EVENT;k(b)&&(c=e.BINARY_EVENT);var d={type:c,data:b};return"function"==typeof b[b.length-1]&&(j("emitting packet with ack id %d",this.ids),this.acks[this.ids]=b.pop(),d.id=this.ids++),this.connected?this.packet(d):this.sendBuffer.push(d),this},d.prototype.packet=function(a){a.nsp=this.nsp,this.io.packet(a)},d.prototype.onopen=function(){j("transport is open - connecting"),"/"!=this.nsp&&this.packet({type:e.CONNECT})},d.prototype.onclose=function(a){j("close (%s)",a),this.connected=!1,this.disconnected=!0,this.emit("disconnect",a)},d.prototype.onpacket=function(a){if(a.nsp==this.nsp)switch(a.type){case e.CONNECT:this.onconnect();break;case e.EVENT:this.onevent(a);break;case e.BINARY_EVENT:this.onevent(a);break;case e.ACK:this.onack(a);break;case e.BINARY_ACK:this.onack(a);break;case e.DISCONNECT:this.ondisconnect();break;case e.ERROR:this.emit("error",a.data)}},d.prototype.onevent=function(a){var b=a.data||[];j("emitting event %j",b),null!=a.id&&(j("attaching ack callback to event"),b.push(this.ack(a.id))),this.connected?m.apply(this,b):this.receiveBuffer.push(b)},d.prototype.ack=function(a){var b=this,c=!1;return function(){if(!c){c=!0;var d=g(arguments);j("sending ack %j",d);var f=k(d)?e.BINARY_ACK:e.ACK;b.packet({type:f,id:a,data:d})}}},d.prototype.onack=function(a){j("calling ack %s with %j",a.id,a.data);var b=this.acks[a.id];b.apply(this,a.data),delete this.acks[a.id]},d.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},d.prototype.emitBuffered=function(){var a;for(a=0;ad;++d)c[d].apply(this,b)}return this},c.prototype.listeners=function(a){return this._callbacks=this._callbacks||{},this._callbacks[a]||[]},c.prototype.hasListeners=function(a){return!!this.listeners(a).length}},{}],45:[function(a,b){function c(a){return c.enabled(a)?function(b){b=d(b);var e=new Date,f=e-(c[a]||e);c[a]=e,b=a+" "+b+" +"+c.humanize(f),window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}:function(){}}function d(a){return a instanceof Error?a.stack||a.message:a}b.exports=c,c.names=[],c.skips=[],c.enable=function(a){try{localStorage.debug=a}catch(b){}for(var d=(a||"").split(/[\s,]+/),e=d.length,f=0;e>f;f++)a=d[f].replace("*",".*?"),"-"===a[0]?c.skips.push(new RegExp("^"+a.substr(1)+"$")):c.names.push(new RegExp("^"+a+"$"))},c.disable=function(){c.enable("")},c.humanize=function(a){var b=1e3,c=6e4,d=60*c;return a>=d?(a/d).toFixed(1)+"h":a>=c?(a/c).toFixed(1)+"m":a>=b?(a/b|0)+"s":a+"ms"},c.enabled=function(a){for(var b=0,d=c.skips.length;d>b;b++)if(c.skips[b].test(a))return!1;for(var b=0,d=c.names.length;d>b;b++)if(c.names[b].test(a))return!0;return!1};try{window.localStorage&&c.enable(localStorage.debug)}catch(e){}},{}],46:[function(a,b){b.exports=a("./lib/")},{"./lib/":47}],47:[function(a,b){b.exports=a("./socket"),b.exports.parser=a("engine.io-parser")},{"./socket":48,"engine.io-parser":57}],48:[function(a,b){(function(c){function d(a,b){if(!(this instanceof d))return new d(a,b);if(b=b||{},a&&"object"==typeof a&&(b=a,a=null),a&&(a=k(a),b.host=a.host,b.secure="https"==a.protocol||"wss"==a.protocol,b.port=a.port,a.query&&(b.query=a.query)),this.secure=null!=b.secure?b.secure:c.location&&"https:"==location.protocol,b.host){var e=b.host.split(":");b.hostname=e.shift(),e.length&&(b.port=e.pop())}this.agent=b.agent||!1,this.hostname=b.hostname||(c.location?location.hostname:"localhost"),this.port=b.port||(c.location&&location.port?location.port:this.secure?443:80),this.query=b.query||{},"string"==typeof this.query&&(this.query=m.decode(this.query)),this.upgrade=!1!==b.upgrade,this.path=(b.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!b.forceJSONP,this.jsonp=!1!==b.jsonp,this.forceBase64=!!b.forceBase64,this.enablesXDR=!!b.enablesXDR,this.timestampParam=b.timestampParam||"t",this.timestampRequests=b.timestampRequests,this.transports=b.transports||["polling","websocket"],this.readyState="",this.writeBuffer=[],this.callbackBuffer=[],this.policyPort=b.policyPort||843,this.rememberUpgrade=b.rememberUpgrade||!1,this.open(),this.binaryType=null,this.onlyBinaryUpgrades=b.onlyBinaryUpgrades}function e(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}var f=a("./transports"),g=a("component-emitter"),h=a("debug")("engine.io-client:socket"),i=a("indexof"),j=a("engine.io-parser"),k=a("parseuri"),l=a("parsejson"),m=a("parseqs");b.exports=d,d.priorWebsocketSuccess=!1,g(d.prototype),d.protocol=j.protocol,d.Socket=d,d.Transport=a("./transport"),d.transports=a("./transports"),d.parser=a("engine.io-parser"),d.prototype.createTransport=function(a){h('creating transport "%s"',a);var b=e(this.query);b.EIO=j.protocol,b.transport=a,this.id&&(b.sid=this.id);var c=new f[a]({agent:this.agent,hostname:this.hostname,port:this.port,secure:this.secure,path:this.path,query:b,forceJSONP:this.forceJSONP,jsonp:this.jsonp,forceBase64:this.forceBase64,enablesXDR:this.enablesXDR,timestampRequests:this.timestampRequests,timestampParam:this.timestampParam,policyPort:this.policyPort,socket:this});return c},d.prototype.open=function(){var a;if(this.rememberUpgrade&&d.priorWebsocketSuccess&&-1!=this.transports.indexOf("websocket"))a="websocket";else{if(0==this.transports.length){var b=this;return void setTimeout(function(){b.emit("error","No transports available")},0)}a=this.transports[0]}this.readyState="opening";var a;try{a=this.createTransport(a)}catch(c){return this.transports.shift(),void this.open()}a.open(),this.setTransport(a)},d.prototype.setTransport=function(a){h("setting transport %s",a.name);var b=this;this.transport&&(h("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=a,a.on("drain",function(){b.onDrain()}).on("packet",function(a){b.onPacket(a)}).on("error",function(a){b.onError(a)}).on("close",function(){b.onClose("transport close")})},d.prototype.probe=function(a){function b(){if(m.onlyBinaryUpgrades){var b=!this.supportsBinary&&m.transport.supportsBinary;l=l||b}l||(h('probe transport "%s" opened',a),k.send([{type:"ping",data:"probe"}]),k.once("packet",function(b){if(!l)if("pong"==b.type&&"probe"==b.data)h('probe transport "%s" pong',a),m.upgrading=!0,m.emit("upgrading",k),d.priorWebsocketSuccess="websocket"==k.name,h('pausing current transport "%s"',m.transport.name),m.transport.pause(function(){l||"closed"!=m.readyState&&"closing"!=m.readyState&&(h("changing transport and sending upgrade packet"),j(),m.setTransport(k),k.send([{type:"upgrade"}]),m.emit("upgrade",k),k=null,m.upgrading=!1,m.flush())});else{h('probe transport "%s" failed',a);var c=new Error("probe error");c.transport=k.name,m.emit("upgradeError",c)}}))}function c(){l||(l=!0,j(),k.close(),k=null)}function e(b){var d=new Error("probe error: "+b);d.transport=k.name,c(),h('probe transport "%s" failed because of error: %s',a,b),m.emit("upgradeError",d)}function f(){e("transport closed")}function g(){e("socket closed")}function i(a){k&&a.name!=k.name&&(h('"%s" works - aborting "%s"',a.name,k.name),c())}function j(){k.removeListener("open",b),k.removeListener("error",e),k.removeListener("close",f),m.removeListener("close",g),m.removeListener("upgrading",i)}h('probing transport "%s"',a);var k=this.createTransport(a,{probe:1}),l=!1,m=this;d.priorWebsocketSuccess=!1,k.once("open",b),k.once("error",e),k.once("close",f),this.once("close",g),this.once("upgrading",i),k.open()},d.prototype.onOpen=function(){if(h("socket open"),this.readyState="open",d.priorWebsocketSuccess="websocket"==this.transport.name,this.emit("open"),this.flush(),"open"==this.readyState&&this.upgrade&&this.transport.pause){h("starting upgrade probes");for(var a=0,b=this.upgrades.length;b>a;a++)this.probe(this.upgrades[a])}},d.prototype.onPacket=function(a){if("opening"==this.readyState||"open"==this.readyState)switch(h('socket receive: type "%s", data "%s"',a.type,a.data),this.emit("packet",a),this.emit("heartbeat"),a.type){case"open":this.onHandshake(l(a.data));break;case"pong":this.setPing();break;case"error":var b=new Error("server error");b.code=a.data,this.emit("error",b);break;case"message":this.emit("data",a.data),this.emit("message",a.data)}else h('packet received with socket readyState "%s"',this.readyState)},d.prototype.onHandshake=function(a){this.emit("handshake",a),this.id=a.sid,this.transport.query.sid=a.sid,this.upgrades=this.filterUpgrades(a.upgrades),this.pingInterval=a.pingInterval,this.pingTimeout=a.pingTimeout,this.onOpen(),"closed"!=this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},d.prototype.onHeartbeat=function(a){clearTimeout(this.pingTimeoutTimer);var b=this;b.pingTimeoutTimer=setTimeout(function(){"closed"!=b.readyState&&b.onClose("ping timeout")},a||b.pingInterval+b.pingTimeout)},d.prototype.setPing=function(){var a=this;clearTimeout(a.pingIntervalTimer),a.pingIntervalTimer=setTimeout(function(){h("writing ping packet - expecting pong within %sms",a.pingTimeout),a.ping(),a.onHeartbeat(a.pingTimeout) },a.pingInterval)},d.prototype.ping=function(){this.sendPacket("ping")},d.prototype.onDrain=function(){for(var a=0;ac;c++)~i(this.transports,a[c])&&b.push(a[c]);return b}}).call(this,"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./transport":49,"./transports":50,"component-emitter":44,debug:45,"engine.io-parser":57,indexof:72,parsejson:66,parseqs:67,parseuri:68}],49:[function(a,b){function c(a){this.path=a.path,this.hostname=a.hostname,this.port=a.port,this.secure=a.secure,this.query=a.query,this.timestampParam=a.timestampParam,this.timestampRequests=a.timestampRequests,this.readyState="",this.agent=a.agent||!1,this.socket=a.socket,this.enablesXDR=a.enablesXDR}var d=a("engine.io-parser"),e=a("component-emitter");b.exports=c,e(c.prototype),c.timestamps=0,c.prototype.onError=function(a,b){var c=new Error(a);return c.type="TransportError",c.description=b,this.emit("error",c),this},c.prototype.open=function(){return("closed"==this.readyState||""==this.readyState)&&(this.readyState="opening",this.doOpen()),this},c.prototype.close=function(){return("opening"==this.readyState||"open"==this.readyState)&&(this.doClose(),this.onClose()),this},c.prototype.send=function(a){if("open"!=this.readyState)throw new Error("Transport not open");this.write(a)},c.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},c.prototype.onData=function(a){var b=d.decodePacket(a,this.socket.binaryType);this.onPacket(b)},c.prototype.onPacket=function(a){this.emit("packet",a)},c.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},{"component-emitter":44,"engine.io-parser":57}],50:[function(a,b,c){(function(b){function d(a){var c,d=!1,h=!1,i=!1!==a.jsonp;if(b.location){var j="https:"==location.protocol,k=location.port;k||(k=j?443:80),d=a.hostname!=location.hostname||k!=a.port,h=a.secure!=j}if(a.xdomain=d,a.xscheme=h,c=new e(a),"open"in c&&!a.forceJSONP)return new f(a);if(!i)throw new Error("JSONP disabled");return new g(a)}var e=a("xmlhttprequest"),f=a("./polling-xhr"),g=a("./polling-jsonp"),h=a("./websocket");c.polling=d,c.websocket=h}).call(this,"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./polling-jsonp":51,"./polling-xhr":52,"./websocket":54,xmlhttprequest:55}],51:[function(a,b){(function(c){function d(){}function e(a){f.call(this,a),this.query=this.query||{},h||(c.___eio||(c.___eio=[]),h=c.___eio),this.index=h.length;var b=this;h.push(function(a){b.onData(a)}),this.query.j=this.index,c.document&&c.addEventListener&&c.addEventListener("beforeunload",function(){b.script&&(b.script.onerror=d)})}var f=a("./polling"),g=a("component-inherit");b.exports=e;var h,i=/\n/g,j=/\\n/g;g(e,f),e.prototype.supportsBinary=!1,e.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null),f.prototype.doClose.call(this)},e.prototype.doPoll=function(){var a=this,b=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),b.async=!0,b.src=this.uri(),b.onerror=function(b){a.onError("jsonp poll error",b)};var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c),this.script=b;var d="undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent);d&&setTimeout(function(){var a=document.createElement("iframe");document.body.appendChild(a),document.body.removeChild(a)},100)},e.prototype.doWrite=function(a,b){function c(){d(),b()}function d(){if(e.iframe)try{e.form.removeChild(e.iframe)}catch(a){e.onError("jsonp polling iframe removal error",a)}try{var b='