From 35ca82b79a4d95c7556238e6a95bb49031dabcc4 Mon Sep 17 00:00:00 2001 From: Itay Weinberger Date: Tue, 18 Nov 2014 14:10:52 +0200 Subject: [PATCH] #29 updated bin --- build/release/joola.css | 11 +- build/release/joola.js | 16411 +++++++++++++------------------ build/release/joola.min.css | 2 +- build/release/joola.min.js | 8 +- build/release/joola.min.js.map | 2 +- build/temp/joola.css | 11 +- build/temp/joola.js | 810 +- 7 files changed, 6784 insertions(+), 10471 deletions(-) diff --git a/build/release/joola.css b/build/release/joola.css index 4edca1a..207b103 100644 --- a/build/release/joola.css +++ b/build/release/joola.css @@ -1,3 +1,8 @@ +[jio-domain="joola"] { + margin: 0; + padding: 0; +} + [jio-domain="joola"] .btn-group, .btn-group-vertical { position: relative; display: inline-block; @@ -567,8 +572,4 @@ 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.js b/build/release/joola.js index fe808aa..48ebf0f 100644 --- a/build/release/joola.js +++ b/build/release/joola.js @@ -1,2755 +1,3276 @@ -;(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 buffer module from node.js, for the browser. * - * 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 + * @author Feross Aboukhadijeh + * @license MIT */ -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 base64 = require('base64-js') +var ieee754 = require('ieee754') - var target = arguments[0]; +exports.Buffer = Buffer +exports.SlowBuffer = Buffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 - // convert arguments to array and cut off target object - var args = Array.prototype.slice.call(arguments, 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 + } +})() - var key, val, src, clone, tmpBuf; +/** + * 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) - args.forEach(function (obj) { - if (typeof obj !== 'object') return; + var type = typeof subject - for (key in obj) { - if ( ! (key in obj)) continue; + // 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 + '=' + } + } - src = target[key]; - val = obj[key]; + // 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.') - if (val === target) continue; + 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 (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; - } + return buf +} - if (typeof src !== 'object' || src === null) { - clone = (Array.isArray(val)) ? [] : {}; - target[key] = deepExtend(clone, val); - continue; - } +// STATIC METHODS +// ============== - if (Array.isArray(val)) { - clone = (Array.isArray(src)) ? src : []; - } else { - clone = (!Array.isArray(src)) ? src : {}; - } +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 + } +} - target[key] = deepExtend(clone, val); - } - }); +Buffer.isBuffer = function (b) { + return !!(b !== null && b !== undefined && b._isBuffer) +} - return target; +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 } -},{"__browserify_Buffer":47}],4:[function(require,module,exports){ -/*! - * EventEmitter2 - * https://github.com/hij1nx/EventEmitter2 - * - * Copyright (c) 2013 hij1nx - * Licensed under the MIT license. - */ -;!function(undefined) { +Buffer.concat = function (list, totalLength) { + assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' + + 'list should be an Array.') - var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { - return Object.prototype.toString.call(obj) === "[object Array]"; - }; - var defaultMaxListeners = 10; + if (list.length === 0) { + return new Buffer(0) + } else if (list.length === 1) { + return list[0] + } - function init() { - this._events = {}; - if (this._conf) { - configure.call(this, this._conf); + var i + if (typeof totalLength !== 'number') { + totalLength = 0 + for (i = 0; i < list.length; i++) { + totalLength += list[i].length } } - function configure(conf) { - if (conf) { - - this._conf = conf; + 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 +} - 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); +// BUFFER INSTANCE METHODS +// ======================= - if (this.wildcard) { - this.listenerTree = {}; - } +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 } } - function EventEmitter(conf) { - this._events = {}; - this.newListener = false; - configure.call(this, conf); + // 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 +} - // - // 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 _utf8Write (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(utf8ToBytes(string), buf, offset, length) + return charsWritten +} - 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)); - } +function _asciiWrite (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(asciiToBytes(string), buf, offset, length) + return charsWritten +} - 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; - } +function _binaryWrite (buf, string, offset, length) { + return _asciiWrite(buf, string, offset, length) +} - listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); +function _base64Write (buf, string, offset, length) { + var charsWritten = Buffer._charsWritten = + blitBuffer(base64ToBytes(string), buf, offset, length) + return charsWritten +} + +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 + } - 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); + 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() - 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); - } + 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 +} - // 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); - } - } +Buffer.prototype.toString = function (encoding, start, end) { + var self = this - return listeners; + 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 +} - function growListenerTree(type, listener) { +Buffer.prototype.toJSON = function () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} - type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function (target, target_start, start, end) { + var source = this - // - // 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; - } - } + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (!target_start) target_start = 0 - var tree = this.listenerTree; - var name = type.shift(); + // Copy 0 bytes; we're done + if (end === start) return + if (target.length === 0 || source.length === 0) return - while (name) { + // 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') - if (!tree[name]) { - tree[name] = {}; - } + // Are we oob? + if (end > this.length) + end = this.length + if (target.length - target_start < end - start) + end = target.length - target_start + start - tree = tree[name]; + var len = end - start - if (type.length === 0) { + 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) + } +} - if (!tree._listeners) { - tree._listeners = listener; - } - else if(typeof tree._listeners === 'function') { - tree._listeners = [tree._listeners, listener]; - } - else if (isArray(tree._listeners)) { +function _base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} - tree._listeners.push(listener); +function _utf8Slice (buf, start, end) { + var res = '' + var tmp = '' + end = Math.min(buf.length, end) - if (!tree._listeners.warned) { + 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) + } + } - var m = defaultMaxListeners; + return res + decodeUtf8Char(tmp) +} - if (typeof this._events.maxListeners !== 'undefined') { - m = this._events.maxListeners; - } +function _asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) - if (m > 0 && tree._listeners.length > m) { + for (var i = start; i < end; i++) + ret += String.fromCharCode(buf[i]) + return ret +} - 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(); +function _binarySlice (buf, start, end) { + return _asciiSlice(buf, start, end) +} + +function _hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out +} + +function _utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i+1] * 256) + } + return res +} + +Buffer.prototype.slice = function (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 true; + return newBuf } +} - // 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. +// `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) +} - EventEmitter.prototype.delimiter = '.'; +// `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) +} - EventEmitter.prototype.setMaxListeners = function(n) { - this._events || init.call(this); - this._events.maxListeners = n; - if (!this._conf) this._conf = {}; - this._conf.maxListeners = n; - }; +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') + } - EventEmitter.prototype.event = ''; + if (offset >= this.length) + return - EventEmitter.prototype.once = function(event, fn) { - this.many(event, 1, fn); - return this; - }; + return this[offset] +} - EventEmitter.prototype.many = function(event, ttl, fn) { - var self = this; +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') + } - if (typeof fn !== 'function') { - throw new Error('many only accepts instances of Function'); - } + var len = buf.length + if (offset >= len) + return - function listener() { - if (--ttl === 0) { - self.off(event, listener); - } - fn.apply(this, arguments); - } + 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 +} - listener._origin = fn; +Buffer.prototype.readUInt16LE = function (offset, noAssert) { + return _readUInt16(this, offset, true, noAssert) +} - this.on(event, listener); +Buffer.prototype.readUInt16BE = function (offset, noAssert) { + return _readUInt16(this, offset, false, noAssert) +} - return self; - }; +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') + } - EventEmitter.prototype.emit = function() { + var len = buf.length + if (offset >= len) + return - this._events || init.call(this); + 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 +} - var type = arguments[0]; +Buffer.prototype.readUInt32LE = function (offset, noAssert) { + return _readUInt32(this, offset, true, noAssert) +} - if (type === 'newListener' && !this.newListener) { - if (!this._events.newListener) { return false; } - } +Buffer.prototype.readUInt32BE = function (offset, noAssert) { + return _readUInt32(this, offset, false, noAssert) +} - // 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); - } - } +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') + } - // If there is no 'error' event listener then throw. - if (type === 'error') { + if (offset >= this.length) + return - if (!this._all && - !this._events.error && - !(this.wildcard && this.listenerTree.error)) { + var neg = this[offset] & 0x80 + if (neg) + return (0xff - this[offset] + 1) * -1 + else + return this[offset] +} - if (arguments[1] instanceof Error) { - throw arguments[1]; // Unhandled 'error' event - } else { - throw new Error("Uncaught, unspecified 'error' event."); - } - return false; - } - } +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') + } - var handler; + var len = buf.length + if (offset >= len) + return - 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]; - } + var val = _readUInt16(buf, offset, littleEndian, true) + var neg = val & 0x8000 + if (neg) + return (0xffff - val + 1) * -1 + else + return val +} - 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]; +Buffer.prototype.readInt16LE = function (offset, noAssert) { + return _readInt16(this, offset, true, noAssert) +} - 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; - } +Buffer.prototype.readInt16BE = function (offset, noAssert) { + return _readInt16(this, offset, false, noAssert) +} - }; +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') + } - EventEmitter.prototype.on = function(type, listener) { + var len = buf.length + if (offset >= len) + return - if (typeof type === 'function') { - this.onAny(type); - return this; - } + var val = _readUInt32(buf, offset, littleEndian, true) + var neg = val & 0x80000000 + if (neg) + return (0xffffffff - val + 1) * -1 + else + return val +} - if (typeof listener !== 'function') { - throw new Error('on only accepts instances of Function'); - } - this._events || init.call(this); +Buffer.prototype.readInt32LE = function (offset, noAssert) { + return _readInt32(this, offset, true, noAssert) +} - // To avoid recursion in the case that type == "newListeners"! Before - // adding it to the listeners, first emit "newListeners". - this.emit('newListener', type, listener); +Buffer.prototype.readInt32BE = function (offset, noAssert) { + return _readInt32(this, offset, false, noAssert) +} - if(this.wildcard) { - growListenerTree.call(this, type, listener); - return this; - } +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') + } - 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); + return ieee754.read(buf, offset, littleEndian, 23, 4) +} - // Check for listener leak - if (!this._events[type].warned) { +Buffer.prototype.readFloatLE = function (offset, noAssert) { + return _readFloat(this, offset, true, noAssert) +} - var m = defaultMaxListeners; +Buffer.prototype.readFloatBE = function (offset, noAssert) { + return _readFloat(this, offset, false, noAssert) +} - if (typeof this._events.maxListeners !== 'undefined') { - m = this._events.maxListeners; - } +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') + } - if (m > 0 && this._events[type].length > m) { + return ieee754.read(buf, offset, littleEndian, 52, 8) +} - 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; - }; +Buffer.prototype.readDoubleLE = function (offset, noAssert) { + return _readDouble(this, offset, true, noAssert) +} - EventEmitter.prototype.onAny = function(fn) { +Buffer.prototype.readDoubleBE = function (offset, noAssert) { + return _readDouble(this, offset, false, noAssert) +} - if (typeof fn !== 'function') { - throw new Error('onAny only accepts instances of Function'); - } +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) + } - if(!this._all) { - this._all = []; - } + if (offset >= this.length) return - // Add the function to the event listener collection. - this._all.push(fn); - return this; - }; + this[offset] = value +} - EventEmitter.prototype.addListener = EventEmitter.prototype.on; +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) + } - EventEmitter.prototype.off = function(type, listener) { - if (typeof listener !== 'function') { - throw new Error('removeListener only takes instances of Function'); - } + var len = buf.length + if (offset >= len) + return - var handlers,leafs=[]; + 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 + } +} - 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}); - } +Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) { + _writeUInt16(this, value, offset, true, noAssert) +} - for (var iLeaf=0; iLeaf= len) + return - if (position < 0) { - continue; - } + for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) { + buf[offset + i] = + (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} - if(this.wildcard) { - leaf._listeners.splice(position, 1); - } - else { - this._events[type].splice(position, 1); - } +Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) { + _writeUInt32(this, value, offset, true, noAssert) +} - if (handlers.length === 0) { - if(this.wildcard) { - delete leaf._listeners; - } - else { - delete this._events[type]; - } - } - return this; - } - else if (handlers === listener || - (handlers.listener && handlers.listener === listener) || - (handlers._origin && handlers._origin === listener)) { - if(this.wildcard) { - delete leaf._listeners; - } - else { - delete this._events[type]; - } - } - } +Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) { + _writeUInt32(this, value, offset, false, noAssert) +} - return this; - }; +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) + } - EventEmitter.prototype.offAny = function(fn) { - var i = 0, l = 0, fns; - if (fn && this._all && this._all.length > 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; - }; + if (offset >= this.length) + return - EventEmitter.prototype.removeListener = EventEmitter.prototype.off; + if (value >= 0) + this.writeUInt8(value, offset, noAssert) + else + this.writeUInt8(0xff + value + 1, offset, noAssert) +} - EventEmitter.prototype.removeAllListeners = function(type) { - if (arguments.length === 0) { - !this._events || init.call(this); - return this; - } +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) + } - if(this.wildcard) { - var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); - var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); + var len = buf.length + if (offset >= len) + return - for (var iLeaf=0; iLeaf= 0) + _writeUInt16(buf, value, offset, littleEndian, noAssert) + else + _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert) +} - EventEmitter.prototype.listeners = function(type) { - if(this.wildcard) { - var handlers = []; - var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); - searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); - return handlers; - } +Buffer.prototype.writeInt16LE = function (value, offset, noAssert) { + _writeInt16(this, value, offset, true, noAssert) +} - this._events || init.call(this); +Buffer.prototype.writeInt16BE = function (value, offset, noAssert) { + _writeInt16(this, value, offset, false, noAssert) +} - if (!this._events[type]) this._events[type] = []; - if (!isArray(this._events[type])) { - this._events[type] = [this._events[type]]; - } - return this._events[type]; - }; +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) + } - EventEmitter.prototype.listenersAny = function() { + var len = buf.length + if (offset >= len) + return - if(this._all) { - return this._all; - } - else { - return []; - } + if (value >= 0) + _writeUInt32(buf, value, offset, littleEndian, noAssert) + else + _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert) +} - }; +Buffer.prototype.writeInt32LE = function (value, offset, noAssert) { + _writeInt32(this, value, offset, true, noAssert) +} - 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; - } -}(); +Buffer.prototype.writeInt32BE = function (value, offset, noAssert) { + _writeInt32(this, value, offset, false, noAssert) +} -},{}],5:[function(require,module,exports){ +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) + } + var len = buf.length + if (offset >= len) + return -// -// 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. -// + ieee754.write(buf, value, offset, littleEndian, 23, 4) +} -var toString = Object.prototype.toString; -var hasOwnProperty = Object.prototype.hasOwnProperty; +Buffer.prototype.writeFloatLE = function (value, offset, noAssert) { + _writeFloat(this, value, offset, true, noAssert) +} -// Array.isArray is supported in IE9 -function isArray(xs) { - return toString.call(xs) === '[object Array]'; +Buffer.prototype.writeFloatBE = function (value, offset, noAssert) { + _writeFloat(this, value, offset, false, noAssert) } -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; +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) } - 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; -}; + var len = buf.length + if (offset >= len) + return -// 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); - } -}; + ieee754.write(buf, value, offset, littleEndian, 52, 8) +} -// 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); +Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) { + _writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) { + _writeDouble(this, value, offset, false, noAssert) +} + +// 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 + + if (typeof value === 'string') { + value = value.charCodeAt(0) } - 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; + assert(typeof value === 'number' && !isNaN(value), 'value is not a number') + assert(end >= start, 'end < start') + + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return + + assert(start >= 0 && start < this.length, 'start out of bounds') + assert(end >= 0 && end <= this.length, 'end out of bounds') - if (2 < arguments.length) { - value = opt_initialValue; - isValueSet = true; + for (var i = start; i < end; i++) { + this[i] = value } - 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; - } +} + +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 '' +} - return value; -}; +/** + * 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 +} -// 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; +// 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 +} - // call the original function - return str.substr(start, length); - }; -} else { - exports.substr = function (str, start, length) { - return str.substr(start, length); - }; +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 } -// String.prototype.trim is supported in IE9 -exports.trim = function (str) { - if (str.trim) return str.trim(); - return str.replace(/^\s+|\s+$/g, ''); -}; +function isArray (subject) { + return (Array.isArray || function (subject) { + return Object.prototype.toString.call(subject) === '[object Array]' + })(subject) +} -// 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)])); - }; -}; +function isArrayish (subject) { + return isArray(subject) || Buffer.isBuffer(subject) || + subject && typeof subject === 'object' && + typeof subject.length === 'number' +} -// 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\'' - ); +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++) { + 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)) } - var Type = function () {}; - Type.prototype = prototype; - object = new Type(); - object.__proto__ = prototype; - } - if (typeof properties !== 'undefined' && Object.defineProperties) { - Object.defineProperties(object, properties); } - return object; + return byteArray } -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 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 keysShim(object) { - if (notObject(object)) { - throw new TypeError("Object.keys called on a non-object"); +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 result = []; - for (var name in object) { - if (hasOwnProperty.call(object, name)) { - result.push(name); - } - } - return result; + return byteArray } -// 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"); - } +function base64ToBytes (str) { + return base64.toByteArray(str) +} - var result = keysShim(object); - if (exports.isArray(object) && exports.indexOf(object, 'length') === -1) { - result.push('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 result; + return i } -var keys = typeof Object.keys === 'function' ? Object.keys : keysShim; -var getOwnPropertyNames = typeof Object.getOwnPropertyNames === 'function' ? - Object.getOwnPropertyNames : propertyShim; +function decodeUtf8Char (str) { + try { + return decodeURIComponent(str) + } catch (err) { + return String.fromCharCode(0xFFFD) // UTF 8 invalid char + } +} -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; - }; +/* + * 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') +} - 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; +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') } -// Object.getOwnPropertyDescriptor - supported in IE8 but only on dom elements -function valueObject(value, key) { - return { value: value[key] }; +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') } -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; +function assert (test, message) { + if (!test) throw new Error(message || 'Failed assertion') } -},{}],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. +},{"base64-js":3,"ieee754":4}],3:[function(require,module,exports){ +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; -// 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 (exports) { + 'use strict'; -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'); + 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 + } -util.inherits(Duplex, Readable); + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr -shims.forEach(shims.keys(Writable.prototype), function(method) { - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; -}); + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); + // 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 - Readable.call(this, options); - Writable.call(this, options); + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) - if (options && options.readable === false) - this.readable = false; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length - if (options && options.writable === false) - this.writable = false; + var L = 0 - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; + function push (v) { + arr[L++] = v + } - this.once('end', onend); -} + 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) + } -// 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 (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) + } - // no more data can be written. - // But allow more writes to happen in this tick. - timers.setImmediate(shims.bind(this.end, this)); -} + return arr + } -},{"_shims":5,"_stream_readable":8,"_stream_writable":10,"timers":17,"util":19}],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 uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. + function encode (num) { + return lookup.charAt(num) + } -module.exports = PassThrough; + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } -var Transform = require('_stream_transform'); -var util = require('util'); -util.inherits(PassThrough, Transform); + // 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 PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); + // 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 + } - Transform.call(this, options); -} + return output + } -PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); -}; + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) -},{"_stream_transform":9,"util":19}],8:[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; +},{}],4:[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]; -util.inherits(Readable, Stream); + i += d; -function ReadableState(options, stream) { - options = options || {}; + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - // 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; + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + 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); +}; - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; +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; - // 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; + value = Math.abs(value); - // 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; + 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; + } - // 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 (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - // 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; + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - // 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'; + buffer[offset + i - d] |= s * 128; +}; - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; +},{}],5:[function(require,module,exports){ +var Buffer = require('buffer').Buffer; +var intSize = 4; +var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); +var chrsz = 8; - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; +function toArray(buf, bigEndian) { + if ((buf.length % intSize) !== 0) { + var len = buf.length + (intSize - (buf.length % intSize)); + buf = Buffer.concat([buf, zeroBuffer], len); + } - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + 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; +} - 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 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; } -function Readable(options) { - if (!(this instanceof Readable)) - return new Readable(options); +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); +} - this._readableState = new ReadableState(options, this); +module.exports = { hash: hash }; - // legacy - this.readable = true; +},{"buffer":2}],6:[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') - Stream.call(this); +var algorithms = { + sha1: sha, + sha256: sha256, + md5: md5 } -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; +var 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) - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } + if(key.length > blocksize) { + key = fn(key) + } else if(key.length < blocksize) { + key = Buffer.concat([key, zeroBuffer], blocksize) } - 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; + 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 } - return needMoreData(state); + var hash = fn(Buffer.concat([ipad, data])) + return fn(Buffer.concat([opad, hash])) } - - -// 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++; +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 + } } - 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; +function error () { + var m = [].slice.call(arguments).join(' ') + throw new Error([ + m, + 'we accept pull requests', + 'http://github.com/dominictarr/crypto-browserify' + ].join('\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'); +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)) } - return er; } +function each(a, f) { + for(var i in a) + f(a[i], i) +} -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; - } +// 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') } - 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; +},{"./md5":7,"./rng":8,"./sha":9,"./sha256":10,"buffer":2}],7:[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); +}; - state.emittedReadable = true; - if (state.sync) - timers.setImmediate(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); -} +},{"./helpers":5}],8:[function(require,module,exports){ +// Original code adapted from Robert Kieffer. +// details at https://github.com/broofa/node-uuid +(function() { + var _global = this; -function emitReadable_(stream) { - stream.emit('readable'); -} + var mathRNG, whatwgRNG; + // NOTE: Math.random() does not guarantee "cryptographic quality" + mathRNG = function(size) { + var bytes = new Array(size); + var r; -// 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); - }); - } -} + for (var i = 0, r; i < size; i++) { + if ((i & 0x03) == 0) r = Math.random() * 0x100000000; + bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; + } -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; + return bytes; } - 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; + if (_global.crypto && crypto.getRandomValues) { + whatwgRNG = function(size) { + var bytes = new Uint8Array(size); + crypto.getRandomValues(bytes); + return bytes; + } } - state.pipesCount += 1; - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; + module.exports = whatwgRNG || mathRNG; - 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(); - } +},{}],9:[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. + */ - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); +var helpers = require('./helpers'); - 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); +/* + * 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 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(); - } + var w = Array(80); + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + var e = -1009589776; - // 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); + for(var i = 0; i < x.length; i += 16) + { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + var olde = e; - // 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); + 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; + } - function unpipe() { - src.unpipe(dest); + 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); - // 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; -}; +/* + * 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; +} -function pipeOnDrain(src) { - return function() { - var dest = this; - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; +/* + * Determine the appropriate additive constant for the current iteration + */ +function sha1_kt(t) +{ + return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : + (t < 60) ? -1894007588 : -899497514; } -function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; +/* + * 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); +} - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } +/* + * Bitwise rotate a 32-bit number to the left. + */ +function rol(num, cnt) +{ + return (num << cnt) | (num >>> (32 - cnt)); +} - while (state.pipesCount && null !== (chunk = src.read())) { +module.exports = function sha1(buf) { + return helpers.hash(buf, core_sha1, 20, true); +}; - if (state.pipesCount === 1) - write(state.pipes, 0, null); - else - shims.forEach(state.pipes, write); +},{"./helpers":5}],10:[function(require,module,exports){ - src.emit('data', chunk); +/** + * 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 + * + */ - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } +var helpers = require('./helpers'); - // 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; +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); +}; - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } +var S = function(X, n) { + return (X >>> n) | (X << (32 - 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; -} +var R = function(X, n) { + return (X >>> n); +}; -function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } -} +var Ch = function(x, y, z) { + return ((x & y) ^ ((~x) & z)); +}; +var Maj = function(x, y, z) { + return ((x & y) ^ (x & z) ^ (y & z)); +}; -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; +var Sigma0256 = function(x) { + return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); +}; - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; +var Sigma1256 = function(x) { + return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); +}; - // 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; +var Gamma0256 = function(x) { + return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); +}; - if (!dest) - dest = state.pipes; +var Gamma1256 = function(x) { + return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); +}; - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; +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); + } + 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; +}; - // slow case. multiple pipe destinations. +module.exports = function sha256(buf) { + return helpers.hash(buf, core_sha256, 32, true); +}; - 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; +},{"./helpers":5}],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. - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; - // try to find the right one. - var i = shims.indexOf(state.pipes, dest); - if (i === -1) - return this; +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; - dest.emit('unpipe', this); +// 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; }; -// 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); +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); + if (!this._events) + this._events = {}; - 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); + // 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 res; -}; -Readable.prototype.addListener = Readable.prototype.on; + handler = this._events[type]; -// 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'); -}; + if (isUndefined(handler)) + return false; -Readable.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); + 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: + 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 (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; }; -function emitDataEvents(stream, startPaused) { - var state = stream._readableState; +EventEmitter.prototype.addListener = function(type, listener) { + var m; - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } + if (!isFunction(listener)) + throw TypeError('listener must be a function'); - var paused = startPaused || false; - var readable = false; + if (!this._events) + this._events = {}; - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream.prototype.pipe; - stream.on = stream.addListener = Stream.prototype.on; + // 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); - stream.on('readable', function() { - readable = true; + 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]; - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); + // 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 (c === null) { - readable = false; - stream._readableState.needReadable = true; + 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(); + } } - }); + } - stream.pause = function() { - paused = true; - this.emit('pause'); - }; + return this; +}; - stream.resume = function() { - paused = false; - if (readable) - timers.setImmediate(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; +EventEmitter.prototype.on = EventEmitter.prototype.addListener; - // now make it start, just in case it hadn't already. - stream.emit('readable'); -} +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); -// 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 fired = 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); + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); } + } - self.push(null); - }); + g.listener = listener; + this.on(type, g); - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); - if (!chunk || !state.objectMode && !chunk.length) - return; + return this; +}; - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; - // 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); + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } } - } - // 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)); - }); + if (position < 0) + return this; - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); } - }; - return self; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; }; +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + if (!this._events) + return this; -// exposed for testing purposes only. -Readable._fromList = fromList; + // 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; + } -// 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; + // 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; + } - // nothing in the list, definitely empty. - if (list.length === 0) - return null; + listeners = this._events[type]; - 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; + if (isFunction(listeners)) { + this.removeListener(type, listeners); } 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); + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); + return this; +}; - c += cpy; - } - } - } +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 isFunction(arg) { + return typeof arg === 'function'; } -function endReadable(stream) { - var state = stream._readableState; +function isNumber(arg) { + return typeof arg === 'number'; +} - // 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'); +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} - 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'); - } - }); - } +function isUndefined(arg) { + return arg === void 0; } -},{"__browserify_process":48,"_shims":5,"buffer":21,"events":12,"stream":15,"string_decoder":16,"timers":17,"util":19}],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. +},{}],12:[function(require,module,exports){ +var http = module.exports; +var EventEmitter = require('events').EventEmitter; +var Request = require('./lib/request'); +var url = require('url') -// 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; +http.request = function (params, cb) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params) params = {}; + if (!params.host && !params.port) { + params.port = parseInt(window.location.port, 10); + } + 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; +}; -var Duplex = require('_stream_duplex'); -var util = require('util'); -util.inherits(Transform, Duplex); +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; -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; +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'); + } +})(); - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} +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":13,"events":11,"url":31}],13:[function(require,module,exports){ +var Stream = require('stream'); +var Response = require('./response'); +var Base64 = require('Base64'); +var inherits = require('inherits'); -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; +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; + } - var cb = ts.writecb; + try { xhr.withCredentials = params.withCredentials } + catch (e) {} + + xhr.open( + params.method || 'GET', + self.uri, + true + ); - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); + 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)); + } - ts.writechunk = null; - ts.writecb = null; + 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 (data !== null && data !== undefined) - stream.push(data); +inherits(Request, Stream); - if (cb) - cb(er); +Request.prototype.setHeader = function (key, value) { + this._headers[key.toLowerCase()] = value +}; - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} +Request.prototype.getHeader = function (key) { + return this._headers[key.toLowerCase()] +}; +Request.prototype.removeHeader = function (key) { + delete this._headers[key.toLowerCase()] +}; -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); +Request.prototype.write = function (s) { + this.body.push(s); +}; - Duplex.call(this, options); +Request.prototype.destroy = function (s) { + this.xhr.__aborted = true; + this.xhr.abort(); + this.emit('close'); +}; - var ts = this._transformState = new TransformState(options, this); +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) + } - // when the writable side finishes, then flush out anything remaining. - var stream = this; + 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); + } +}; - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; +// 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" +]; - // 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; +Request.prototype.isSafeRequestHeader = function (headerName) { + if (!headerName) return false; + return indexOf(Request.unsafeHeaders, headerName.toLowerCase()) === -1; +}; - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); -} +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; -Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; }; -// 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 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; }; -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); - } +},{"./response":14,"Base64":15,"inherits":17,"stream":24}],14:[function(require,module,exports){ +var Stream = require('stream'); +var util = require('util'); + +var Response = module.exports = function (res) { + this.offset = 0; + this.readable = true; }; -// 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; +util.inherits(Response, Stream); - 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; - } +var capable = { + streaming : true, + status2 : true }; +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; +} -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; +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; +} - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); +Response.prototype.getHeader = function (key) { + return this.headers[key.toLowerCase()]; +}; - if (ts.transforming) - throw new Error('calling transform done when still transforming'); +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'); + } +}; - return stream.push(null); -} +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; + } +}; -},{"_stream_duplex":6,"util":19}],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. +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; -// A bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. +},{"stream":24,"util":33}],15:[function(require,module,exports){ +;(function () { -module.exports = Writable; -Writable.WritableState = WritableState; + var object = typeof exports != 'undefined' ? exports : this; // #8: web workers + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -var util = require('util'); -var Stream = require('stream'); -var timers = require('timers'); -var Buffer = require('buffer').Buffer; + function InvalidCharacterError(message) { + this.message = message; + } + InvalidCharacterError.prototype = new Error; + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; -util.inherits(Writable, Stream); + // 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; + }); -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} + // 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 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; +},{}],16:[function(require,module,exports){ +var http = require('http'); - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; +var https = module.exports; - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key]; +}; - 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; +https.request = function (params, cb) { + if (!params) params = {}; + params.scheme = 'https'; + return http.request.call(this, params, cb); +} - // 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; +},{"http":12}],17:[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 + } +} - // a flag to see when we're in the middle of a write. - this.writing = false; +},{}],18:[function(require,module,exports){ +// shim for using process in browser - // 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; +var process = module.exports = {}; - // 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; +process.nextTick = (function () { + var canSetImmediate = typeof window !== 'undefined' + && window.setImmediate; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; + if (canSetImmediate) { + return function (f) { return window.setImmediate(f) }; + } - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + 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); - // the amount that is being written when _write is called. - this.writelen = 0; + return function nextTick(fn) { + queue.push(fn); + window.postMessage('process-tick', '*'); + }; + } - this.buffer = []; -} + return function nextTick(fn) { + setTimeout(fn, 0); + }; +})(); -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); +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; - this._writableState = new WritableState(options, this); +function noop() {} - // legacy. - this.writable = true; +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; - Stream.call(this); +process.binding = function (name) { + throw new Error('process.binding is not supported'); } -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); +// TODO(shtylman) +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); }; +},{}],19:[function(require,module,exports){ +(function (global){ +/*! http://mths.be/punycode v1.2.4 by @mathias */ +;(function(root) { -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); - }); -} + /** 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; + } -// 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; -} + /** + * 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; -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; + /*--------------------------------------------------------------------------*/ - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + /** + * 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]); + } - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; + /** + * 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; + } - if (typeof cb !== 'function') - cb = function() {}; + /** + * 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('.'); + } - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); + /** + * 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; + } - return ret; -}; + /** + * 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(''); + } -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} + /** + * 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; + } -// 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; + /** + * 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); + } - state.length += len; + /** + * 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)); + } - var ret = state.length < state.highWaterMark; - state.needDrain = !ret; + /** + * 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; + } - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); + 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)); + } - return ret; -} + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. -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; -} + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { -function onwriteError(stream, state, sync, er, cb) { - if (sync) - timers.setImmediate(function() { - cb(er); - }); - else - cb(er); + // `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) { - stream.emit('error', er); -} + if (index >= inputLength) { + error('invalid-input'); + } -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} + digit = basicToDigit(input.charCodeAt(index++)); -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } - onwriteStateUpdate(state); + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - 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 (digit < t) { + break; + } - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } - if (sync) { - timers.setImmediate(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} + w *= baseMinusT; -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'); - } -} + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + // `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 there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; + n += floor(i / out); + i %= out; - 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; + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); - 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; - } - } + return ucs2encode(output); + } - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; -} + /** + * 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)); + } + } -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); -}; + handledCPCount = basicLength = output.length; -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); + // Main encoding loop: + while (handledCPCount < inputLength) { - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); -}; + // 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; + } + } + // 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'); + } -function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); -} + delta += (m - n) * handledCPCountPlusOne; + n = m; -function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; -} + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; -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; -} + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + 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; + + } + return output.join(''); + } + + /** + * 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; + }); + } + + /** + * 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; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** 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 + }; + + /** 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; + } + +}(this)); -},{"buffer":21,"stream":15,"timers":17,"util":19}],11:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],20:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -2771,302 +3292,71 @@ function endWritable(stream, state, cb) { // 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 - }); -} +'use strict'; -// 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); +// 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); } -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); +module.exports = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); + if (typeof qs !== 'string' || qs.length === 0) { + return obj; } -}; -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); + var regexp = /\+/g; + qs = qs.split(sep); -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; } -}; -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); + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; } -} -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; -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; + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; } - 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; - } + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); - 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; + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } } -} -// 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))); + return obj; }; -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; }; -assert.ifError = function(err) { if (err) {throw err;}}; -},{"_shims":5,"util":19}],12:[function(require,module,exports){ +},{}],21:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -3088,280 +3378,78 @@ assert.ifError = function(err) { if (err) {throw err;}}; // 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; -}; +'use strict'; -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); +var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; - 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]; + case 'boolean': + return v ? 'true' : 'false'; - // 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; - } + case 'number': + return isFinite(v) ? v : ''; - 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(); - } + default: + return ''; } - - 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); +module.exports = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; } - 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 (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])); } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } + }).join(sep); - if (this._events.removeListener) - this.emit('removeListener', type, listener); } - return this; + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); }; -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; - } +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; - // 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; +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; +} - listeners = this._events[type]; - - if (util.isFunction(listeners)) { - this.removeListener(type, listeners); - } else { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); +var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } - 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; + return res; }; -},{"util":19}],13:[function(require,module,exports){ -var http = require('http'); -var https = module.exports; +},{}],22:[function(require,module,exports){ +'use strict'; -for (var key in http) { - if (http.hasOwnProperty(key)) https[key] = http[key]; -}; +exports.decode = exports.parse = require('./decode'); +exports.encode = exports.stringify = require('./encode'); -https.request = function (params, cb) { - if (!params) params = {}; - params.scheme = 'https'; - return http.request.call(this, params, cb); -} -},{"http":29}],14:[function(require,module,exports){ +},{"./decode":20,"./encode":21}],23:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -3383,196 +3471,59 @@ https.request = function (params, cb) { // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -// Query String Utilities - -var QueryString = exports; -var util = require('util'); -var shims = require('_shims'); -var Buffer = require('buffer').Buffer; - -// 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); -} - - -function charCode(c) { - return c.charCodeAt(0); -} - - -// 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; - - 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; - - 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; - } - } - - // TODO support returning arbitrary buffers. - - return out.slice(0, outIndex - 1); -}; - - -QueryString.unescape = function(s, decodeSpaces) { - return QueryString.unescapeBuffer(s, decodeSpaces).toString(); -}; - - -QueryString.escape = function(str) { - return encodeURIComponent(str); -}; - -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 ''; -}; - - -QueryString.stringify = QueryString.encode = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (util.isNull(obj)) { - obj = undefined; - } - - 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); +// 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 inherits = require('inherits'); +var setImmediate = require('process/browser.js').nextTick; +var Readable = require('./readable.js'); +var Writable = require('./writable.js'); - if (!name) return ''; - return QueryString.escape(stringifyPrimitive(name)) + eq + - QueryString.escape(stringifyPrimitive(obj)); -}; +inherits(Duplex, Readable); -// Parse a key=val string. -QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; +Duplex.prototype.write = Writable.prototype.write; +Duplex.prototype.end = Writable.prototype.end; +Duplex.prototype._write = Writable.prototype._write; - if (!util.isString(qs) || qs.length === 0) { - return obj; - } +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); - var regexp = /\+/g; - qs = qs.split(sep); + Readable.call(this, options); + Writable.call(this, options); - var maxKeys = 1000; - if (options && util.isNumber(options.maxKeys)) { - maxKeys = options.maxKeys; - } + if (options && options.readable === false) + this.readable = false; - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } + if (options && options.writable === false) + this.writable = false; - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } + this.once('end', onend); +} - try { - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - } catch (e) { - k = QueryString.unescape(kstr, true); - v = QueryString.unescape(vstr, true); - } +// 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 (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (util.isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } + // no more data can be written. + // But allow more writes to happen in this tick. + var self = this; + setImmediate(function () { + self.end(); + }); +} - return obj; -}; -},{"_shims":5,"buffer":21,"util":19}],15:[function(require,module,exports){ +},{"./readable.js":27,"./writable.js":29,"inherits":17,"process/browser.js":25}],24:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -3597,14 +3548,14 @@ QueryString.parse = QueryString.decode = function(qs, sep, eq, options) { module.exports = Stream; var EE = require('events').EventEmitter; -var util = require('util'); +var inherits = require('inherits'); -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'); +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'); // Backwards-compat with node 0.4.x Stream.Stream = Stream; @@ -3701,7 +3652,62 @@ Stream.prototype.pipe = function(dest, options) { return dest; }; -},{"_stream_duplex":6,"_stream_passthrough":7,"_stream_readable":8,"_stream_transform":9,"_stream_writable":10,"events":12,"util":19}],16:[function(require,module,exports){ +},{"./duplex.js":23,"./passthrough.js":26,"./readable.js":27,"./transform.js":28,"./writable.js":29,"events":11,"inherits":17}],25:[function(require,module,exports){ +// shim for using process in browser + +var process = module.exports = {}; + +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 (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', '*'); + }; + } + + return function nextTick(fn) { + setTimeout(fn, 0); + }; +})(); + +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; + +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'); +}; + +},{}],26:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a @@ -3723,6722 +3729,3978 @@ Stream.prototype.pipe = function(dest, options) { // 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; +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. -function assertEncoding(encoding) { - if (encoding && !Buffer.isEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} +module.exports = PassThrough; -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; - } +var Transform = require('./transform.js'); +var inherits = require('inherits'); +inherits(PassThrough, Transform); - this.charBuffer = new Buffer(6); - this.charReceived = 0; - this.charLength = 0; -}; +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + Transform.call(this, options); +} -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - var offset = 0; +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; - // 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; +},{"./transform.js":28,"inherits":17}],27:[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. - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, offset, i); - this.charReceived += (i - offset); - offset = i; +module.exports = Readable; +Readable.ReadableState = ReadableState; - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } +var EE = require('events').EventEmitter; +var Stream = require('./index.js'); +var Buffer = require('buffer').Buffer; +var setImmediate = require('process/browser.js').nextTick; +var StringDecoder; - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); +var inherits = require('inherits'); +inherits(Readable, Stream); - // 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 ReadableState(options, stream) { + options = options || {}; - // if there are no more bytes in this buffer, just emit our char - if (i == buffer.length) return charStr; + // 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; - // otherwise cut off the characters end from the beginning of this buffer - buffer = buffer.slice(i, buffer.length); - break; - } + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - var lenIncomplete = this.detectIncompleteChar(buffer); + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = 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; - } + // 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; - charStr += buffer.toString(this.encoding, 0, end); + // 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; - 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); - } + // 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; - // or just emit the charStr - return charStr; -}; -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; + // 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; - // 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]; + // 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'; - // See http://en.wikipedia.org/wiki/UTF-8#Description + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } + // if true, a maybeReadMore has been scheduled + this.readingMore = false; - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } + 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; } +} - return i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); +function Readable(options) { + if (!(this instanceof Readable)) + return new Readable(options); - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } + this._readableState = new ReadableState(options, this); - return res; -}; + // legacy + this.readable = true; -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); + Stream.call(this); } -function utf16DetectIncompleteChar(buffer) { - var incomplete = this.charReceived = buffer.length % 2; - this.charLength = incomplete ? 2 : 0; - return incomplete; -} +// 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; -function base64DetectIncompleteChar(buffer) { - var incomplete = this.charReceived = buffer.length % 3; - this.charLength = incomplete ? 3 : 0; - return incomplete; -} + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } -},{"buffer":21}],17:[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); - }) - }; + return readableAddChunk(this, state, chunk, encoding, false); +}; - 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); - } +// 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 (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; + 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); } - } -} -exports.unref = function unref() {}; -exports.ref = function ref() {}; + if (state.needReadable) + emitReadable(stream); -if (!exports.setImmediate) { - var currentKey = 0, queue = {}, active = false; + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } - 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(); - } - } - } + return needMoreData(state); +} - 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); - 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; - }; - } - })(); - exports.clearImmediate = function clearImmediate(id) { - delete queue[id]; - }; +// 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); } -},{}],18:[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 punycode = { encode : function (s) { return s } }; -var util = require('util'); -var shims = require('_shims'); - -exports.parse = urlParse; -exports.resolve = urlResolve; -exports.resolveObject = urlResolveObject; -exports.format = urlFormat; - -exports.Url = Url; +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; +}; -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; +// 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; } -// Reference: RFC 3986, RFC 1808, RFC 2396 +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + 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]*$/, + if (state.objectMode) + return n === 0 ? 0 : 1; - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + 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; + } - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + if (n <= 0) + return 0; - // 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'); + // 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); -function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) return url; + // 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; + } - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; + return n; } -Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } - - var rest = url; +// 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; - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = shims.trim(rest); + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); + // 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; } - // 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; - } + 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; } - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { + // 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. - // 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 + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; - // 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; - } + // 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; - // 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); - } + 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; + } - // 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); - } - - // 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; + // 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); - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); + var ret; + if (n > 0) + ret = fromList(n, state); + else + ret = null; - // pull out port. - this.parseHost(); + if (ret === null) { + state.needReadable = true; + n = 0; + } - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; + state.length -= n; - // 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 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; - // 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; - } - } - } - } + // 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); - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } + return ret; +}; - 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('.'); - } +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; +} - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; - // 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; - } +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; - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { + // 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); +} - // 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); - } - } +// 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) + setImmediate(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); +} - // 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 = '/'; +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; + setImmediate(function() { + maybeReadMore_(stream, state); + }); } +} - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; +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; +} - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; +// 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')); }; -// 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(); -} +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; -Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; + 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 protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; - 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; - } + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + setImmediate(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); } - if (this.query && - util.isObject(this.query) && - shims.keys(this.query).length) { - query = querystring.stringify(this.query); + function onend() { + dest.end(); } - var search = this.search || (query && ('?' + query)) || ''; + // 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); - if (protocol && shims.substr(protocol, -1) !== ':') protocol += ':'; + 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); - // 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 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 (hash && hash.charAt(0) !== '#') hash = '#' + hash; - if (search && search.charAt(0) !== '?') search = '?' + search; + // 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); - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); + // 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); - return protocol + host + pathname + search + hash; -}; + function unpipe() { + src.unpipe(dest); + } -function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); -} + // tell the dest that it's being piped to + dest.emit('pipe', src); -Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); + // 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; + setImmediate(function() { + flow(src); + }); + } + + return dest; }; -function urlResolveObject(source, relative) { - if (!source) return relative; - return urlParse(source, false, true).resolveObject(relative); +function pipeOnDrain(src) { + return function() { + var dest = this; + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; } -Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; +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++; + } } - var result = new Url(); - shims.forEach(shims.keys(this), function(k) { - result[k] = this[k]; - }, this); + while (state.pipesCount && null !== (chunk = src.read())) { - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; + if (state.pipesCount === 1) + write(state.pipes, 0, null); + else + forEach(state.pipes, write); - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } + src.emit('data', chunk); - // 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]; - }); + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; + } - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } + // 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; - result.href = result.format(); - return result; + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; } - 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; - } + // 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; +} - 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; +function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); } +} - 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]; - // 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; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; - 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; - } + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return 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; - } + // 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 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 === ''); + if (!dest) + dest = state.pipes; - // 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--; - } + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; } - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } + // slow case. multiple pipe destinations. - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } + 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; - if (hasTrailingSlash && (shims.substr(srcPath.join('/'), -1) !== '/')) { - srcPath.push(''); + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; } - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; - // 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(); - } - } + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; - mustEndAbs = mustEndAbs || (result.host && srcPath.length); + dest.emit('unpipe', this); - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } + return this; +}; - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } +// 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); - //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; -}; + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); -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); + 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); + } } - host = host.substr(0, host.length - port.length); } - if (host) this.hostname = host; + + return res; }; -},{"_shims":5,"querystring":14,"util":19}],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. +Readable.prototype.addListener = Readable.prototype.on; -var shims = require('_shims'); +// 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'); +}; -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; +Readable.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); }; -/** - * 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 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.'); } - // 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; + var paused = startPaused || false; + var readable = false; -// 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] -}; + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream.prototype.pipe; + stream.on = stream.addListener = Stream.prototype.on; -// 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' -}; + stream.on('readable', function() { + readable = true; + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} + 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'); + }; -function stylizeNoColor(str, styleType) { - return str; + // 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; -function arrayToHash(array) { - var hash = {}; + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } - shims.forEach(array, function(val, idx) { - hash[val] = true; + self.push(null); }); - return hash; -} - + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); + if (!chunk || !state.objectMode && !chunk.length) + return; -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); + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); } - return ret; - } + }); - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; + // 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); + } } - // Look up the keys of the object. - var keys = shims.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = shims.getOwnPropertyNames(value); - } + // 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); + }); + }); - // 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); + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); } - } - - var base = '', array = false, braces = ['{', '}']; + }; - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } + return self; +}; - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } +// exposed for testing purposes only. +Readable._fromList = fromList; - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } +// 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; - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + // nothing in the list, definitely empty. + if (list.length === 0) + return null; - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + 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 { - return ctx.stylize('[Object]', 'special'); + // 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; + } } } - ctx.seen.push(value); + return ret; +} - 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); - }); - } +function endReadable(stream) { + var state = stream._readableState; - ctx.seen.pop(); + // 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'); - return reduceToSingleString(output, base, braces); + 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'); + } + }); + } } +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} -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'); +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; } - 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'); + return -1; } +}).call(this,require("FWaASH")) +},{"./index.js":24,"FWaASH":18,"buffer":2,"events":11,"inherits":17,"process/browser.js":25,"string_decoder":30}],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. + +// 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('./duplex.js'); +var inherits = require('inherits'); +inherits(Transform, Duplex); -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; + +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; -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(''); - } + 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); } +} - shims.forEach(keys, function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } + +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); }); - return output; } +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; -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'); - } - } +// 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'); +}; - 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 { - 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'); - } +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); } +}; - return name + ': ' + str; -} - - -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); +// 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 (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; + 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; } +}; - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} +function done(stream, er) { + if (er) + return stream.emit('error', er); -// 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; + // 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; -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + if (ts.transforming) + throw new Error('calling transform done when still transforming'); -function isNullOrUndefined(arg) { - return arg == null; + return stream.push(null); } -exports.isNullOrUndefined = isNullOrUndefined; -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; +},{"./duplex.js":23,"inherits":17}],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. -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; +module.exports = Writable; +Writable.WritableState = WritableState; -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; +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' + } +; -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; +var inherits = require('inherits'); +var Stream = require('./index.js'); +var setImmediate = require('process/browser.js').nextTick; +var Buffer = require('buffer').Buffer; -function isObject(arg) { - return typeof arg === 'object' && arg; -} -exports.isObject = isObject; +inherits(Writable, Stream); -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; } -exports.isDate = isDate; -function isError(e) { - return isObject(e) && objectToString(e) === '[object Error]'; -} -exports.isError = isError; +function WritableState(options, stream) { + options = options || {}; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; + // 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; -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; + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; -function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.binarySlice === 'function' - ; -} -exports.isBuffer = isBuffer; + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; -function objectToString(o) { - return Object.prototype.toString.call(o); -} + 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; -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} + // 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; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - + // a flag to see when we're in the middle of a write. + this.writing = false; -// 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)); -}; + // 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; -/** - * 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 - } - }); -}; + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; - var keys = shims.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; + // the amount that is being written when _write is called. + this.writelen = 0; -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); + this.buffer = []; } -},{"_shims":5}],20:[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]; +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); - i += d; + this._writableState = new WritableState(options, this); - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + // legacy. + this.writable = true; - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + Stream.call(this); +} - 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); +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); }; -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; - - value = Math.abs(value); - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } +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); + }); +} - 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 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; } - - 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; -}; - -},{}],21:[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, ''); + return valid; } -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; +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; - // 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 + "="; - } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - var type; - - // 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; + 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; - case 'string': - this.length = Buffer.byteLength(subject, encoding); - break; + if (typeof cb !== 'function') + cb = function() {}; - case 'object': // Assume object is an array - this.length = coerce(subject.length); - break; + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); - default: - throw new Error('First argument needs to be a number, ' + - 'array or string.'); - } + return ret; +}; - // 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; - } - } +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); } + return chunk; } -Buffer.prototype.get = function get(i) { - if (i < 0 || i >= this.length) throw new Error('oob'); - return this[i]; -}; +// 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; -Buffer.prototype.set = function set(i, v) { - if (i < 0 || i >= this.length) throw new Error('oob'); - return this[i] = v; -}; + state.length += len; -Buffer.byteLength = function (str, encoding) { - switch (encoding || "utf8") { - case 'hex': - return str.length / 2; + var ret = state.length < state.highWaterMark; + state.needDrain = !ret; - case 'utf8': - case 'utf-8': - return utf8ToBytes(str).length; + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); - case 'ascii': - case 'binary': - return str.length; + return ret; +} - case 'base64': - return base64ToBytes(str).length; +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; +} - default: - throw new Error('Unknown encoding'); - } -}; +function onwriteError(stream, state, sync, er, cb) { + if (sync) + setImmediate(function() { + cb(er); + }); + else + cb(er); -Buffer.prototype.utf8Write = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length); -}; + stream.emit('error', er); +} -Buffer.prototype.asciiWrite = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length); -}; +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} -Buffer.prototype.binaryWrite = Buffer.prototype.asciiWrite; +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; -Buffer.prototype.base64Write = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length); -}; + onwriteStateUpdate(state); -Buffer.prototype.base64Slice = function (start, end) { - var bytes = Array.prototype.slice.apply(this, arguments) - return require("base64-js").fromByteArray(bytes); -}; + 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); -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 (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); - i++; + if (sync) { + setImmediate(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } } +} - return res + decodeUtf8Char(tmp); +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); } -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; +// 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'); + } } -Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice; -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] = '...'; +// 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; } } - return ''; -}; + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; +} -Buffer.prototype.hexSlice = function(start, end) { - var len = this.length; +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); +}; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; - var out = ''; - for (var i = start; i < end; i++) { - out += toHex(this[i]); + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - return out; + + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); }; -Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - start = +start || 0; - if (typeof end == 'undefined') end = this.length; +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); +} - // Fastpath empty strings - if (+end == start) { - return ''; +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); } + return need; +} - switch (encoding) { - case 'hex': - return this.hexSlice(start, end); - - case 'utf8': - case 'utf-8': - return this.utf8Slice(start, end); +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; +} - case 'ascii': - return this.asciiSlice(start, end); +},{"./index.js":24,"buffer":2,"inherits":17,"process/browser.js":25}],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. - case 'binary': - return this.binarySlice(start, end); +var Buffer = require('buffer').Buffer; - case 'base64': - return this.base64Slice(start, end); +function assertEncoding(encoding) { + if (encoding && !Buffer.isEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} +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 'ucs-2': - return this.ucs2Slice(start, end); - + 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: - throw new Error('Unknown encoding'); + this.write = passThroughWrite; + return; } -}; + this.charBuffer = new Buffer(6); + this.charReceived = 0; + this.charLength = 0; +}; -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; - } - } - // 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; -}; +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + var offset = 0; + // 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.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; - } + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, offset, i); + this.charReceived += (i - offset); + offset = i; - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; } - } - 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); + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - case 'ascii': - return this.asciiWrite(string, offset, length); + // 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; - case 'binary': - return this.binaryWrite(string, offset, length); + // if there are no more bytes in this buffer, just emit our char + if (i == buffer.length) return charStr; - case 'base64': - return this.base64Write(string, offset, length); + // otherwise cut off the characters end from the beginning of this buffer + buffer = buffer.slice(i, buffer.length); + break; + } - case 'ucs2': - case 'ucs-2': - return this.ucs2Write(string, offset, length); + var lenIncomplete = this.detectIncompleteChar(buffer); - default: - throw new Error('Unknown encoding'); + 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; } -}; -// 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; -} + charStr += buffer.toString(this.encoding, 0, end); -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'); - } - - if (start < 0 || start >= source.length) { - throw new Error('sourceStart out of bounds'); - } - - if (end < 0 || end > source.length) { - throw new Error('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 temp = []; - for (var i=start; i= 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); } - for (var i=target_start; i= this.length) { - throw new Error('start out of bounds'); - } - - if (end < 0 || end > this.length) { - throw new Error('end out of bounds'); - } +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; - for (var i = start; i < end; i++) { - this[i] = value; - } -} + // 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]; -// Static methods -Buffer.isBuffer = function isBuffer(b) { - return b instanceof Buffer || b instanceof Buffer; -}; + // See http://en.wikipedia.org/wiki/UTF-8#Description -Buffer.concat = function (list, totalLength) { - if (!isArray(list)) { - throw new Error("Usage: Buffer.concat(list, [totalLength])\n \ - list should be an Array."); - } + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } - if (list.length === 0) { - return new Buffer(0); - } else if (list.length === 1) { - return list[0]; - } + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } - if (typeof totalLength !== 'number') { - totalLength = 0; - for (var i = 0; i < list.length; i++) { - var buf = list[i]; - totalLength += buf.length; + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; } } - 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; + return i; }; -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; +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); - default: - return false; + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); } -}; -// helpers + return res; +}; -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 passThroughWrite(buffer) { + return buffer.toString(this.encoding); } -function isArray(subject) { - return (Array.isArray || - function(subject){ - return {}.toString.apply(subject) == '[object Array]' - }) - (subject) +function utf16DetectIncompleteChar(buffer) { + var incomplete = this.charReceived = buffer.length % 2; + this.charLength = incomplete ? 2 : 0; + return incomplete; } -function isArrayIsh(subject) { - return isArray(subject) || Buffer.isBuffer(subject) || - subject && typeof subject === 'object' && - typeof subject.length === 'number'; +function base64DetectIncompleteChar(buffer) { + var incomplete = this.charReceived = buffer.length % 3; + this.charLength = incomplete ? 3 : 0; + return incomplete; } -function toHex(n) { - if (n < 16) return '0' + n.toString(16); - return n.toString(16); -} +},{"buffer":2}],31:[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 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)); - } +var punycode = require('punycode'); - return byteArray; -} +exports.parse = urlParse; +exports.resolve = urlResolve; +exports.resolveObject = urlResolveObject; +exports.format = urlFormat; -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 ); +exports.Url = Url; - return byteArray; +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 base64ToBytes(str) { - return require("base64-js").toByteArray(str); -} +// Reference: RFC 3986, RFC 1808, RFC 2396 -function blitBuffer(src, dst, offset, length) { - var pos, i = 0; - while (i < length) { - if ((i+offset >= dst.length) || (i >= src.length)) - break; +// 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]*$/, - dst[i + offset] = src[i]; - i++; - } - return i; -} + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], -function decodeUtf8Char(str) { - try { - return decodeURIComponent(str); - } catch (err) { - return String.fromCharCode(0xFFFD); // UTF 8 invalid char - } -} + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), -// read/write bit-twiddling + // 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'); -Buffer.prototype.readUInt8 = function(offset, noAssert) { - var buffer = this; +function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject(url) && url instanceof Url) return url; - if (!noAssert) { - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; +} - assert.ok(offset < buffer.length, - 'Trying to read beyond buffer length'); +Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } - 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'); + var rest = url; - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); - assert.ok(offset + 1 < buffer.length, - 'Trying to read beyond buffer length'); + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.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; + // 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; } } - return val; -} + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { -Buffer.prototype.readUInt16LE = function(offset, noAssert) { - return readUInt16(this, offset, false, noAssert); -}; + // 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 -Buffer.prototype.readUInt16BE = function(offset, noAssert) { - return readUInt16(this, offset, true, noAssert); -}; + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. -function readUInt32(buffer, offset, isBigEndian, noAssert) { - var val = 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; + } - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + // 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); + } - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + // 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); + } - assert.ok(offset + 3 < buffer.length, - 'Trying to read beyond buffer length'); - } + // 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; - if (offset >= buffer.length) return 0; + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); - 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); - } + // pull out port. + this.parseHost(); - return val; -} + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; -Buffer.prototype.readUInt32LE = function(offset, noAssert) { - return readUInt32(this, offset, false, noAssert); -}; + // 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] === ']'; -Buffer.prototype.readUInt32BE = function(offset, noAssert) { - return readUInt32(this, offset, true, noAssert); -}; + // 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; + } + } + } + } + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } -/* - * 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 (!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('.'); + } - if (!noAssert) { - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; - assert.ok(offset < buffer.length, - 'Trying to read beyond buffer 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; + } + } } - if (offset >= buffer.length) return; + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { - neg = buffer[offset] & 0x80; - if (!neg) { - return (buffer[offset]); + // 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); + } } - return ((0xff - buffer[offset] + 1) * -1); -}; - -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'); + // 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); } - - val = readUInt16(buffer, offset, isBigEndian, noAssert); - neg = val & 0x8000; - if (!neg) { - return val; + 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 = '/'; } - return (0xffff - val + 1) * -1; -} - -Buffer.prototype.readInt16LE = function(offset, noAssert) { - return readInt16(this, offset, false, noAssert); -}; + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } -Buffer.prototype.readInt16BE = function(offset, noAssert) { - return readInt16(this, offset, true, noAssert); + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; }; -function readInt32(buffer, offset, isBigEndian, noAssert) { - var neg, val; +// 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(); +} - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); +Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; - assert.ok(offset + 3 < buffer.length, - 'Trying to read beyond buffer length'); + 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; + } } - val = readUInt32(buffer, offset, isBigEndian, noAssert); - neg = val & 0x80000000; - if (!neg) { - return (val); + if (this.query && + isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); } - return (0xffffffff - val + 1) * -1; -} - -Buffer.prototype.readInt32LE = function(offset, noAssert) { - return readInt32(this, offset, false, noAssert); -}; - -Buffer.prototype.readInt32BE = function(offset, noAssert) { - return readInt32(this, offset, true, noAssert); -}; + var search = this.search || (query && ('?' + query)) || ''; -function readFloat(buffer, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - assert.ok(offset + 3 < buffer.length, - 'Trying to read beyond buffer length'); + // 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 require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, - 23, 4); -} - -Buffer.prototype.readFloatLE = function(offset, noAssert) { - return readFloat(this, offset, false, noAssert); -}; - -Buffer.prototype.readFloatBE = function(offset, noAssert) { - return readFloat(this, offset, true, noAssert); -}; + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; -function readDouble(buffer, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); - assert.ok(offset + 7 < buffer.length, - 'Trying to read beyond buffer length'); - } + return protocol + host + pathname + search + hash; +}; - return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian, - 52, 8); +function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); } -Buffer.prototype.readDoubleLE = function(offset, noAssert) { - return readDouble(this, offset, false, noAssert); -}; - -Buffer.prototype.readDoubleBE = function(offset, noAssert) { - return readDouble(this, offset, true, noAssert); +Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); }; +function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); +} -/* - * 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'); +Url.prototype.resolveObject = function(relative) { + if (isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } - assert.ok(value >= 0, - 'specified a negative value for writing an unsigned value'); + var result = new Url(); + Object.keys(this).forEach(function(k) { + result[k] = this[k]; + }, this); - assert.ok(value <= max, 'value is larger than maximum value for type'); + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; - assert.ok(Math.floor(value) === value, 'value has a fractional component'); -} + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } -Buffer.prototype.writeUInt8 = function(value, offset, noAssert) { - var buffer = this; + // 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]; + }); - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + result.href = result.format(); + return result; + } - assert.ok(offset < buffer.length, - 'trying to write beyond buffer length'); + 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; + } - verifuint(value, 0xff); + 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; } - if (offset < buffer.length) { - buffer[offset] = value; - } -}; + 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]; -function writeUInt16(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); + // 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; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + 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 : ''); + } + result.href = result.format(); + return result; + } - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + 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; + } - assert.ok(offset + 1 < buffer.length, - 'trying to write beyond buffer length'); + // 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 === ''); - verifuint(value, 0xffff); + // 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; i < Math.min(buffer.length - offset, 2); i++) { - buffer[offset + i] = - (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>> - (isBigEndian ? 1 - i : i) * 8; + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } } -} - -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); -}; + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } -function writeUInt32(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); + // 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(); + } + } - assert.ok(offset + 3 < buffer.length, - 'trying to write beyond buffer length'); + mustEndAbs = mustEndAbs || (result.host && srcPath.length); - verifuint(value, 0xffffffff); + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); } - for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) { - buffer[offset + i] = - (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff; + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); } -} -Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) { - writeUInt32(this, value, offset, false, noAssert); + //to support request.http + if (!isNull(result.pathname) || !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; }; -Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) { - writeUInt32(this, value, offset, true, noAssert); +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); + } + if (host) this.hostname = host; }; - -/* - * 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'); - - assert.ok(value <= max, 'value larger than maximum allowed value'); - - assert.ok(value >= min, 'value smaller than minimum allowed value'); - - assert.ok(Math.floor(value) === value, 'value has a fractional component'); +function isString(arg) { + return typeof arg === "string"; } -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 isObject(arg) { + return typeof arg === 'object' && arg !== 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 isNull(arg) { + return arg === null; +} +function isNullOrUndefined(arg) { + return arg == null; +} - assert.ok(offset < buffer.length, - 'Trying to write beyond buffer length'); +},{"punycode":19,"querystring":22}],32:[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'; +} +},{}],33:[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. - verifsint(value, 0x7f, -0x80); +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 (value >= 0) { - buffer.writeUInt8(value, offset, noAssert); - } else { - buffer.writeUInt8(0xff + value + 1, offset, noAssert); + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } } + return str; }; -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); +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; } - if (value >= 0) { - writeUInt16(buffer, value, offset, isBigEndian, noAssert); - } else { - writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert); + if (process.noDeprecation === true) { + return fn; } -} -Buffer.prototype.writeInt16LE = function(value, offset, noAssert) { - writeInt16(this, value, offset, false, noAssert); -}; + 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); + } -Buffer.prototype.writeInt16BE = function(value, offset, noAssert) { - writeInt16(this, value, offset, true, noAssert); + return deprecated; }; -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'); - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset + 3 < buffer.length, - 'Trying to write beyond buffer length'); - - verifsint(value, 0x7fffffff, -0x80000000); +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } } + return debugs[set]; +}; - if (value >= 0) { - writeUInt32(buffer, value, offset, isBigEndian, noAssert); - } else { - writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert); + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); } +exports.inspect = inspect; -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); +// 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 writeFloat(buffer, value, offset, isBigEndian, noAssert) { - if (!noAssert) { - assert.ok(value !== undefined && value !== null, - 'missing value'); - - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); +// 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' +}; - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - assert.ok(offset + 3 < buffer.length, - 'Trying to write beyond buffer length'); +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; - verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38); + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; } - - require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, - 23, 4); } -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'); - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); +function stylizeNoColor(str, styleType) { + return str; +} - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - assert.ok(offset + 7 < buffer.length, - 'Trying to write beyond buffer length'); +function arrayToHash(array) { + var hash = {}; - verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308); - } + array.forEach(function(val, idx) { + hash[val] = true; + }); - require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, - 52, 8); + return hash; } -Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) { - writeDouble(this, value, offset, false, noAssert); -}; - -Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) { - writeDouble(this, value, offset, true, noAssert); -}; - -},{"./buffer_ieee754":20,"assert":11,"base64-js":22}],22:[function(require,module,exports){ -(function (exports) { - 'use strict'; - var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +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; + } - 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'; - } + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - // 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; + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - // base64 is 4/3 + up to two characters of the original data - arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders); + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? b64.length - 4 : b64.length; + // 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); + } - 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); - } - - return arr; - } - - function uint8ToBase64(uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length; - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; - }; + // 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); + } + } - // 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); - } + var base = '', array = false, braces = ['{', '}']; - // 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; - } + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } - return output; - } + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } - module.exports.toByteArray = b64ToByteArray; - module.exports.fromByteArray = uint8ToBase64; -}()); + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } -},{}],23:[function(require,module,exports){ -var Buffer = require('buffer').Buffer; -var intSize = 4; -var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); -var chrsz = 8; + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } -function toArray(buf, bigEndian) { - if ((buf.length % intSize) !== 0) { - var len = buf.length + (intSize - (buf.length % intSize)); - buf = Buffer.concat([buf, zeroBuffer], len); + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); } - var arr = []; - var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE; - for (var i = 0; i < buf.length; i += intSize) { - arr.push(fn.call(buf, i)); + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; } - return arr; -} -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); + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } } - 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); -} + ctx.seen.push(value); -module.exports = { hash: hash }; + 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); + }); + } -},{"buffer":21}],24:[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') + ctx.seen.pop(); -var algorithms = { - sha1: sha, - sha256: sha256, - md5: md5 + return reduceToSingleString(output, base, braces); } -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) - if(key.length > blocksize) { - key = fn(key) - } else if(key.length < blocksize) { - key = Buffer.concat([key, zeroBuffer], blocksize) +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'); +} - 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 hash = fn(Buffer.concat([ipad, data])) - return fn(Buffer.concat([opad, hash])) +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; } -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 + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); } } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; } -function 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) } +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 { - return new Buffer(rng(size)) + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } } -} -function each(a, f) { - for(var i in a) - f(a[i], i) + return name + ': ' + str; } -// 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":25,"./rng":26,"./sha":27,"./sha256":28,"buffer":21}],25:[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); -}; +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); -},{"./helpers":23}],26:[function(require,module,exports){ -// Original code adapted from Robert Kieffer. -// details at https://github.com/broofa/node-uuid -(function() { - var _global = this; + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } - var mathRNG, whatwgRNG; + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} - // NOTE: Math.random() does not guarantee "cryptographic quality" - mathRNG = function(size) { - var bytes = new Array(size); - var r; - for (var i = 0, r; i < size; i++) { - if ((i & 0x03) == 0) r = Math.random() * 0x100000000; - bytes[i] = r >>> ((i & 0x03) << 3) & 0xff; - } +// 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; - return bytes; - } +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - if (_global.crypto && crypto.getRandomValues) { - whatwgRNG = function(size) { - var bytes = new Uint8Array(size); - crypto.getRandomValues(bytes); - return bytes; - } - } +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; - module.exports = whatwgRNG || mathRNG; +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; -}()) +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; -},{}],27:[function(require,module,exports){ -/* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; -var helpers = require('./helpers'); +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; -/* - * 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); +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; } +exports.isRegExp = isRegExp; -/* - * 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; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; } +exports.isObject = isObject; -/* - * Determine the appropriate additive constant for the current iteration - */ -function sha1_kt(t) -{ - return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : - (t < 60) ? -1894007588 : -899497514; +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; } +exports.isDate = isDate; -/* - * 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); +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); } +exports.isError = isError; -/* - * Bitwise rotate a 32-bit number to the left. - */ -function rol(num, cnt) -{ - return (num << cnt) | (num >>> (32 - cnt)); +function isFunction(arg) { + return typeof arg === 'function'; } +exports.isFunction = isFunction; -module.exports = function sha1(buf) { - return helpers.hash(buf, core_sha1, 20, true); -}; +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; -},{"./helpers":23}],28:[function(require,module,exports){ +exports.isBuffer = require('./support/isBuffer'); -/** - * 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 - * - */ +function objectToString(o) { + return Object.prototype.toString.call(o); +} -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); -}; +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} -var S = function(X, n) { - return (X >>> n) | (X << (32 - n)); -}; -var R = function(X, n) { - return (X >>> n); -}; +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; -var Ch = function(x, y, z) { - return ((x & y) ^ ((~x) & z)); -}; +// 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 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)); +// 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 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)); -}; +/** + * 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'); -var Gamma1256 = function(x) { - return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); -}; +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; -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); - } - 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]); + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; } - return HASH; -}; - -module.exports = function sha256(buf) { - return helpers.hash(buf, core_sha256, 32, true); -}; - -},{"./helpers":23}],29:[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; + return origin; }; -http.Agent = function () {}; -http.Agent.defaultMaxSockets = 4; +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} -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'); - } -})(); - -},{"./lib/request":30,"events":12}],30:[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'); - -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)); - } - - 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); - }; -}; - -util.inherits(Request, Stream); - -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); - } -}; - -Request.prototype.write = function (s) { - this.body.write(s); -}; - -Request.prototype.destroy = function (s) { - this.xhr.abort(); - this.emit('close'); -}; - -Request.prototype.end = function (s) { - if (s !== undefined) this.body.write(s); - this.body.end() - this.xhr.send(this.body.getBody()); -}; - -// 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" -]; - -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; -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -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; -}; - -},{"./response":31,"Base64":32,"concat-stream":33,"stream":15,"util":19}],31:[function(require,module,exports){ -var Stream = require('stream'); -var util = require('util'); - -var Response = module.exports = function (res) { - this.offset = 0; - this.readable = true; -}; - -util.inherits(Response, Stream); - -var capable = { - streaming : true, - status2 : true -}; - -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; -} - -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()]; -}; - -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'); - } -}; - -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; - } -}; - -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -},{"stream":15,"util":19}],32:[function(require,module,exports){ -;(function () { - - 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; }}()); - - // 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; - }); - -}()); - -},{}],33:[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 - }) -} - -util.inherits(ConcatStream, stream.Stream) - -ConcatStream.prototype.write = function(chunk) { - this.body.push(chunk) -} - -ConcatStream.prototype.destroy = function() {} - -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) }) -} - -ConcatStream.prototype.isArray = function(arr) { - return Array.isArray(arr) -} - -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 -} - -ConcatStream.prototype.end = function() { - if (this.cb) this.cb(this.getBody()) -} - -module.exports = function(cb) { - return new ConcatStream(cb) -} - -module.exports.ConcatStream = ConcatStream - -},{"bops":34,"stream":15,"util":19}],34:[function(require,module,exports){ -var proto = {} -module.exports = proto - -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') - -mix(require('./read.js'), proto) -mix(require('./write.js'), proto) - -function mix(from, into) { - for(var key in from) { - into[key] = from[key] - } -} - -},{"./copy.js":37,"./create.js":38,"./from.js":39,"./is.js":40,"./join.js":41,"./read.js":43,"./subarray.js":44,"./to.js":45,"./write.js":46}],35:[function(require,module,exports){ -module.exports=require(22) -},{}],36:[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 find_pad_position(byt) { - for(var i = 0; i < 7; ++i) { - if(!(byt & mask[i])) { - break - } - } - return i -} - -function reduced(list) { - var out = 0 - for(var i = 0, len = list.length; i < len; ++i) { - out |= list[i] << ((len - i - 1) * 6) - } - return out -} - -},{}],37:[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 - - if(source_end === source_start) { - return - } - - if(target.length === 0 || source.length === 0) { - return - } - - if(source_end > source.length) { - source_end = source.length - } - - if(target.length - target_start < source_end - source_start) { - source_end = target.length - target_start + start - } - - if(source.buffer !== target.buffer) { - return fast_copy(source, target, target_start, source_start, source_end) - } - return slow_copy(source, target, target_start, source_start, source_end) -} - -function fast_copy(source, target, target_start, source_start, source_end) { - var len = (source_end - source_start) + target_start - - for(var i = target_start, j = source_start; - i < len; - ++i, - ++j) { - target[i] = source[j] - } -} - -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 - - for(; i < iend; ++i, ++x) { - to[j++] = tmp[x] - } -} - -},{}],38:[function(require,module,exports){ -module.exports = function(size) { - return new Uint8Array(size) -} - -},{}],39:[function(require,module,exports){ -module.exports = from - -var base64 = require('base64-js') - -var decoders = { - hex: from_hex - , utf8: from_utf - , base64: from_base64 -} - -function from(source, encoding) { - if(Array.isArray(source)) { - return new Uint8Array(source) - } - - return decoders[encoding || 'utf8'](source) -} - -function from_hex(str) { - var size = str.length / 2 - , buf = new Uint8Array(size) - , character = '' - - for(var i = 0, len = str.length; i < len; ++i) { - character += str.charAt(i) - - if(i > 0 && (i % 2) === 1) { - buf[i>>>1] = parseInt(character, 16) - character = '' - } - } - - return buf -} - -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) - } - } else { - bytes[bytes.length] = ch - } - } - - return new Uint8Array(bytes) -} - -function from_base64(str) { - return new Uint8Array(base64.toByteArray(str)) -} - -},{"base64-js":35}],40:[function(require,module,exports){ - -module.exports = function(buffer) { - return buffer instanceof Uint8Array; -} - -},{}],41:[function(require,module,exports){ -module.exports = join - -function join(targets, hint) { - if(!targets.length) { - return new Uint8Array(0) - } - - var len = hint !== undefined ? hint : get_length(targets) - , out = new Uint8Array(len) - , cur = targets[0] - , curlen = cur.length - , curidx = 0 - , curoff = 0 - , i = 0 - - while(i < len) { - if(curoff === curlen) { - curoff = 0 - ++curidx - cur = targets[curidx] - curlen = cur && cur.length - continue - } - out[i++] = cur[curoff++] - } - - return out -} - -function get_length(targets) { - var size = 0 - for(var i = 0, len = targets.length; i < len; ++i) { - size += targets[i].byteLength - } - return size -} - -},{}],42:[function(require,module,exports){ -var proto - , map - -module.exports = proto = {} - -map = typeof WeakMap === 'undefined' ? null : new WeakMap - -proto.get = !map ? no_weakmap_get : get - -function no_weakmap_get(target) { - return new DataView(target.buffer, 0) -} - -function get(target) { - var out = map.get(target.buffer) - if(!out) { - map.set(target.buffer, out = new DataView(target.buffer, 0)) - } - return out -} - -},{}],43:[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 -} - -var map = require('./mapped.js') - -function read_uint8(target, at) { - return target[at] -} - -function read_int8(target, at) { - var v = target[at]; - return v < 0x80 ? v : v - 0x100 -} - -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) -} - -function read_int16_le(target, at) { - var dv = map.get(target); - return dv.getInt16(at + target.byteOffset, true) -} - -function read_int32_le(target, at) { - var dv = map.get(target); - return dv.getInt32(at + target.byteOffset, true) -} - -function read_float_le(target, at) { - var dv = map.get(target); - return dv.getFloat32(at + target.byteOffset, true) -} - -function read_double_le(target, at) { - var dv = map.get(target); - return dv.getFloat64(at + target.byteOffset, true) -} - -function read_uint16_be(target, at) { - var dv = map.get(target); - return dv.getUint16(at + target.byteOffset, false) -} - -function read_uint32_be(target, at) { - var dv = map.get(target); - return dv.getUint32(at + target.byteOffset, false) -} - -function read_int16_be(target, at) { - var dv = map.get(target); - return dv.getInt16(at + target.byteOffset, false) -} - -function read_int32_be(target, at) { - var dv = map.get(target); - return dv.getInt32(at + target.byteOffset, false) -} - -function read_float_be(target, at) { - var dv = map.get(target); - return dv.getFloat32(at + target.byteOffset, false) -} - -function read_double_be(target, at) { - var dv = map.get(target); - return dv.getFloat64(at + target.byteOffset, false) -} - -},{"./mapped.js":42}],44:[function(require,module,exports){ -module.exports = subarray - -function subarray(buf, from, to) { - return buf.subarray(from || 0, to || buf.length) -} - -},{}],45:[function(require,module,exports){ -module.exports = to - -var base64 = require('base64-js') - , toutf8 = require('to-utf8') - -var encoders = { - hex: to_hex - , utf8: to_utf - , base64: to_base64 -} - -function to(buf, encoding) { - return encoders[encoding || 'utf8'](buf) -} - -function to_hex(buf) { - var str = '' - , byt - - for(var i = 0, len = buf.length; i < len; ++i) { - byt = buf[i] - str += ((byt & 0xF0) >>> 4).toString(16) - str += (byt & 0x0F).toString(16) - } - - return str -} - -function to_utf(buf) { - return toutf8(buf) -} - -function to_base64(buf) { - return base64.fromByteArray(buf) -} - - -},{"base64-js":35,"to-utf8":36}],46:[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 -} - -var map = require('./mapped.js') - -function write_uint8(target, value, at) { - return target[at] = value -} - -function write_int8(target, value, at) { - return target[at] = value < 0 ? value + 0x100 : value -} - -function write_uint16_le(target, value, at) { - var dv = map.get(target); - return dv.setUint16(at + target.byteOffset, value, true) -} - -function write_uint32_le(target, value, at) { - var dv = map.get(target); - return dv.setUint32(at + target.byteOffset, value, true) -} - -function write_int16_le(target, value, at) { - var dv = map.get(target); - return dv.setInt16(at + target.byteOffset, value, true) -} - -function write_int32_le(target, value, at) { - var dv = map.get(target); - return dv.setInt32(at + target.byteOffset, value, true) -} - -function write_float_le(target, value, at) { - var dv = map.get(target); - return dv.setFloat32(at + target.byteOffset, value, true) -} - -function write_double_le(target, value, at) { - var dv = map.get(target); - return dv.setFloat64(at + target.byteOffset, value, true) -} - -function write_uint16_be(target, value, at) { - var dv = map.get(target); - return dv.setUint16(at + target.byteOffset, value, false) -} - -function write_uint32_be(target, value, at) { - var dv = map.get(target); - return dv.setUint32(at + target.byteOffset, value, false) -} - -function write_int16_be(target, value, at) { - var dv = map.get(target); - return dv.setInt16(at + target.byteOffset, value, false) -} - -function write_int32_be(target, value, at) { - var dv = map.get(target); - return dv.setInt32(at + target.byteOffset, value, false) -} - -function write_float_be(target, value, at) { - var dv = map.get(target); - return dv.setFloat32(at + target.byteOffset, value, false) -} - -function write_double_be(target, value, at) { - var dv = map.get(target); - return dv.setFloat64(at + target.byteOffset, value, false) -} - -},{"./mapped.js":42}],47:[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; - } - 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; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -},{}],"q9TxCC":[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, ''); -} - -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; - - // 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 + "="; - } - } - - var type; - - // 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; - - case 'string': - this.length = Buffer.byteLength(subject, encoding); - break; - - case 'object': // Assume object is an array - this.length = coerce(subject.length); - break; - - default: - throw new Error('First argument needs to be a number, ' + - 'array or string.'); - } - - // 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; - } - } - } -} - -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; -}; - -Buffer.byteLength = function (str, encoding) { - switch (encoding || "utf8") { - case 'hex': - return str.length / 2; - - case 'utf8': - case 'utf-8': - return utf8ToBytes(str).length; - - case 'ascii': - case 'binary': - return str.length; - - case 'base64': - return base64ToBytes(str).length; - - default: - throw new Error('Unknown encoding'); - } -}; - -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; - -Buffer.prototype.base64Write = function (string, offset, length) { - var bytes, pos; - return Buffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length); -}; - -Buffer.prototype.base64Slice = function (start, end) { - var bytes = Array.prototype.slice.apply(this, arguments) - return require("base64-js").fromByteArray(bytes); -}; - -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); -} - -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; -} - -Buffer.prototype.binarySlice = Buffer.prototype.asciiSlice; - -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 ''; -}; - - -Buffer.prototype.hexSlice = function(start, end) { - var len = this.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - - var out = ''; - for (var i = start; i < end; i++) { - out += toHex(this[i]); - } - return out; -}; - - -Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); - start = +start || 0; - if (typeof end == 'undefined') end = this.length; - - // Fastpath empty strings - if (+end == start) { - return ''; - } - - switch (encoding) { - case 'hex': - return this.hexSlice(start, end); - - case 'utf8': - case 'utf-8': - return this.utf8Slice(start, end); - - case 'ascii': - return this.asciiSlice(start, end); - - case 'binary': - return this.binarySlice(start, end); - - case 'base64': - return this.base64Slice(start, end); - - case 'ucs2': - case 'ucs-2': - return this.ucs2Slice(start, end); - - default: - throw new Error('Unknown encoding'); - } -}; - - -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; - } - } - - // 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; -}; - - -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; - } - - 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(); - - 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'); - } - - if (start < 0 || start >= source.length) { - throw new Error('sourceStart out of bounds'); - } - - if (end < 0 || end > source.length) { - throw new Error('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 temp = []; - for (var i=start; i= this.length) { - throw new Error('start out of bounds'); - } - - if (end < 0 || end > this.length) { - throw new Error('end out of bounds'); - } - - for (var i = start; i < end; i++) { - this[i] = value; - } -} - -// 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."); - } - - 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; - } - } - - 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; - } -}; - -// 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 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 base64ToBytes(str) { - return require("base64-js").toByteArray(str); -} - -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 decodeUtf8Char(str) { - try { - return decodeURIComponent(str); - } catch (err) { - return String.fromCharCode(0xFFFD); // UTF 8 invalid char - } -} - -// 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'); - } - - 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; - } - } - - 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); -}; - -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); - } - - 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 (offset >= buffer.length) return; - - neg = buffer[offset] & 0x80; - if (!neg) { - return (buffer[offset]); - } - - return ((0xff - buffer[offset] + 1) * -1); -}; - -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; - } - - 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); -}; - -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); - } - - return (0xffffffff - val + 1) * -1; -} - -Buffer.prototype.readInt32LE = function(offset, noAssert) { - return readInt32(this, offset, false, noAssert); -}; - -Buffer.prototype.readInt32BE = function(offset, noAssert) { - return readInt32(this, offset, true, noAssert); -}; - -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); -}; - -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'); - - assert.ok(offset + 7 < buffer.length, - 'Trying to read beyond buffer length'); - } - - 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); -}; - - -/* - * 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'); - - assert.ok(value <= max, 'value is larger than maximum value for type'); - - assert.ok(Math.floor(value) === value, 'value has a fractional component'); -} - -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); - } - - if (offset < buffer.length) { - buffer[offset] = value; - } -}; - -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'); - - verifuint(value, 0xffff); - } - - 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; - } - -} - -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'); - - assert.ok(offset + 3 < buffer.length, - 'trying to write beyond buffer length'); - - verifuint(value, 0xffffffff); - } - - for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) { - buffer[offset + i] = - (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff; - } -} - -Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) { - writeUInt32(this, value, offset, false, noAssert); -}; - -Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) { - writeUInt32(this, value, offset, true, noAssert); -}; - - -/* - * 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'); - - assert.ok(value <= max, 'value larger than maximum allowed value'); - - assert.ok(value >= min, 'value smaller than minimum allowed value'); - - assert.ok(Math.floor(value) === value, 'value has a fractional component'); -} - -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'); -} - -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'); - - assert.ok(offset < buffer.length, - 'Trying to write beyond buffer length'); - - verifsint(value, 0x7f, -0x80); - } - - if (value >= 0) { - buffer.writeUInt8(value, offset, noAssert); - } else { - buffer.writeUInt8(0xff + value + 1, offset, noAssert); - } -}; - -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 (value >= 0) { - writeUInt16(buffer, value, offset, isBigEndian, noAssert); - } else { - writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert); - } -} - -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'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset + 3 < buffer.length, - 'Trying to write beyond buffer length'); - - verifsint(value, 0x7fffffff, -0x80000000); - } - - if (value >= 0) { - writeUInt32(buffer, value, offset, isBigEndian, noAssert); - } else { - writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert); - } -} - -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'); - - 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 write beyond buffer length'); - - verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38); - } - - require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, - 23, 4); -} - -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'); - - assert.ok(typeof (isBigEndian) === 'boolean', - 'missing or invalid endian'); - - assert.ok(offset !== undefined && offset !== null, - 'missing offset'); - - assert.ok(offset + 7 < buffer.length, - 'Trying to write beyond buffer length'); - - verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308); - } - - require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian, - 52, 8); -} - -Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) { - writeDouble(this, value, offset, false, noAssert); -}; - -Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) { - writeDouble(this, value, offset, true, noAssert); -}; - -},{"./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 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); - } - - return arr; - } - - function uint8ToBase64(uint8) { - var i, - extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes - output = "", - temp, length; - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; - }; - - // 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); - } - - // 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; - } - - return output; - } - - 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; +}).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":32,"FWaASH":18,"inherits":17}],34:[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. + */ - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } +/** + * 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; + } - return true; + if (arguments.length < 2) return arguments[0]; - // 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); - } -} + var target = arguments[0]; -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} + // convert arguments to array and cut off target object + var args = Array.prototype.slice.call(arguments, 1); -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; -} + var key, val, src, clone, tmpBuf; -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); + args.forEach(function (obj) { + if (typeof obj !== 'object') return; -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; + for (key in obj) { + if ( ! (key in obj)) continue; -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); + src = target[key]; + val = obj[key]; -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; + if (val === target) continue; -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + 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; + } -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; + if (typeof src !== 'object' || src === null) { + clone = (Array.isArray(val)) ? [] : {}; + target[key] = deepExtend(clone, val); + continue; + } -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } + if (Array.isArray(val)) { + clone = (Array.isArray(src)) ? src : []; + } else { + clone = (!Array.isArray(src)) ? src : {}; + } - 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; - } + target[key] = deepExtend(clone, val); + } + }); - return false; + return target; } -function _throws(shouldThrow, block, expected, message) { - var actual; +}).call(this,require("buffer").Buffer) +},{"buffer":2}],36:[function(require,module,exports){ +/*! + * EventEmitter2 + * https://github.com/hij1nx/EventEmitter2 + * + * Copyright (c) 2013 hij1nx + * Licensed under the MIT license. + */ +;!function(undefined) { - if (util.isString(expected)) { - message = expected; - expected = null; - } + var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + var defaultMaxListeners = 10; - try { - block(); - } catch (e) { - actual = e; + function init() { + this._events = {}; + if (this._conf) { + configure.call(this, this._conf); + } } - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); + function configure(conf) { + if (conf) { - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } + this._conf = conf; - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } + 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 ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; + if (this.wildcard) { + this.listenerTree = {}; + } + } } -} - -// 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":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. - -var shims = require('_shims'); -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(' '); + function EventEmitter(conf) { + this._events = {}; + this.newListener = false; + configure.call(this, conf); } - 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; + // + // 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 []; } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); + 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]; + } } - } - 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); - } - // 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; + 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; + } -// 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] -}; + listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); + } -// 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' -}; + 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 stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + // 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); + } + } - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; + return listeners; } -} + function growListenerTree(type, listener) { -function stylizeNoColor(str, styleType) { - return str; -} + 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; + } + } -function arrayToHash(array) { - var hash = {}; + var tree = this.listenerTree; + var name = type.shift(); - shims.forEach(array, function(val, idx) { - hash[val] = true; - }); + while (name) { - return hash; -} + if (!tree[name]) { + tree[name] = {}; + } + tree = tree[name]; -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); - } - return ret; - } + if (type.length === 0) { - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + if (!tree._listeners) { + tree._listeners = listener; + } + else if(typeof tree._listeners === 'function') { + tree._listeners = [tree._listeners, listener]; + } + else if (isArray(tree._listeners)) { - // Look up the keys of the object. - var keys = shims.keys(value); - var visibleKeys = arrayToHash(keys); + tree._listeners.push(listener); - if (ctx.showHidden) { - keys = shims.getOwnPropertyNames(value); - } + if (!tree._listeners.warned) { - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } + var m = defaultMaxListeners; - var base = '', array = false, braces = ['{', '}']; + if (typeof this._events.maxListeners !== 'undefined') { + m = this._events.maxListeners; + } - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } + if (m > 0 && tree._listeners.length > m) { - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; + 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; } - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(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. - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + EventEmitter.prototype.delimiter = '.'; - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + EventEmitter.prototype.setMaxListeners = function(n) { + this._events || init.call(this); + this._events.maxListeners = n; + if (!this._conf) this._conf = {}; + this._conf.maxListeners = n; + }; - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + EventEmitter.prototype.event = ''; - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } + EventEmitter.prototype.once = function(event, fn) { + this.many(event, 1, fn); + return this; + }; - ctx.seen.push(value); + EventEmitter.prototype.many = function(event, ttl, fn) { + var self = this; - 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); - }); - } + if (typeof fn !== 'function') { + throw new Error('many only accepts instances of Function'); + } - ctx.seen.pop(); + function listener() { + if (--ttl === 0) { + self.off(event, listener); + } + fn.apply(this, arguments); + } - return reduceToSingleString(output, base, braces); -} + listener._origin = fn; + this.on(event, listener); -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'); -} + return self; + }; + EventEmitter.prototype.emit = function() { -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} + this._events || init.call(this); + var type = arguments[0]; -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(''); + if (type === 'newListener' && !this.newListener) { + if (!this._events.newListener) { return false; } } - } - shims.forEach(keys, function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); + // 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); + } } - }); - return output; -} + // If there is no 'error' event listener then throw. + if (type === 'error') { -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 (!this._all && + !this._events.error && + !(this.wildcard && this.listenerTree.error)) { - 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); + 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; -},{}],48:[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; + } +}(); -},{}],49:[function(require,module,exports){ +},{}],37:[function(require,module,exports){ //! moment.js //! version : 2.5.1 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors @@ -12840,11 +10102,11 @@ process.chdir = function (dir) { } }).call(this); -},{}],50:[function(require,module,exports){ +},{}],38:[function(require,module,exports){ module.exports = require('./lib/'); -},{"./lib/":51}],51:[function(require,module,exports){ +},{"./lib/":39}],39:[function(require,module,exports){ /** * Module dependencies. @@ -12933,7 +10195,7 @@ exports.connect = lookup; exports.Manager = require('./manager'); exports.Socket = require('./socket'); -},{"./manager":52,"./socket":54,"./url":55,"debug":58,"socket.io-parser":89}],52:[function(require,module,exports){ +},{"./manager":40,"./socket":42,"./url":43,"debug":46,"socket.io-parser":77}],40:[function(require,module,exports){ /** * Module dependencies. @@ -13408,7 +10670,7 @@ Manager.prototype.onreconnect = function(){ this.emitAll('reconnect', attempt); }; -},{"./on":53,"./socket":54,"./url":55,"component-bind":56,"component-emitter":57,"debug":58,"engine.io-client":59,"indexof":85,"object-component":86,"socket.io-parser":89}],53:[function(require,module,exports){ +},{"./on":41,"./socket":42,"./url":43,"component-bind":44,"component-emitter":45,"debug":46,"engine.io-client":47,"indexof":73,"object-component":74,"socket.io-parser":77}],41:[function(require,module,exports){ /** * Module exports. @@ -13434,7 +10696,7 @@ function on(obj, ev, fn) { }; } -},{}],54:[function(require,module,exports){ +},{}],42:[function(require,module,exports){ /** * Module dependencies. @@ -13820,8 +11082,9 @@ Socket.prototype.disconnect = function(){ return this; }; -},{"./on":53,"component-bind":56,"component-emitter":57,"debug":58,"has-binary":83,"socket.io-parser":89,"to-array":93}],55:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; +},{"./on":41,"component-bind":44,"component-emitter":45,"debug":46,"has-binary":71,"socket.io-parser":77,"to-array":81}],43:[function(require,module,exports){ +(function (global){ + /** * Module dependencies. */ @@ -13895,7 +11158,8 @@ function url(uri, loc){ return obj; } -},{"debug":58,"parseuri":87}],56:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"debug":46,"parseuri":75}],44:[function(require,module,exports){ /** * Slice reference. */ @@ -13920,7 +11184,7 @@ module.exports = function(obj, fn){ } }; -},{}],57:[function(require,module,exports){ +},{}],45:[function(require,module,exports){ /** * Expose `Emitter`. @@ -14086,7 +11350,7 @@ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; -},{}],58:[function(require,module,exports){ +},{}],46:[function(require,module,exports){ /** * Expose `debug()` as the module. @@ -14225,11 +11489,11 @@ try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} -},{}],59:[function(require,module,exports){ +},{}],47:[function(require,module,exports){ module.exports = require('./lib/'); -},{"./lib/":60}],60:[function(require,module,exports){ +},{"./lib/":48}],48:[function(require,module,exports){ module.exports = require('./socket'); @@ -14241,8 +11505,9 @@ module.exports = require('./socket'); */ module.exports.parser = require('engine.io-parser'); -},{"./socket":61,"engine.io-parser":70}],61:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{"./socket":49,"engine.io-parser":58}],49:[function(require,module,exports){ +(function (global){ +/** * Module dependencies. */ @@ -14926,7 +12191,8 @@ Socket.prototype.filterUpgrades = function (upgrades) { return filteredUpgrades; }; -},{"./transport":62,"./transports":63,"component-emitter":57,"debug":58,"engine.io-parser":70,"indexof":85,"parsejson":79,"parseqs":80,"parseuri":81}],62:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./transport":50,"./transports":51,"component-emitter":45,"debug":46,"engine.io-parser":58,"indexof":73,"parsejson":67,"parseqs":68,"parseuri":69}],50:[function(require,module,exports){ /** * Module dependencies. */ @@ -15078,8 +12344,9 @@ Transport.prototype.onClose = function () { this.emit('close'); }; -},{"component-emitter":57,"engine.io-parser":70}],63:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{"component-emitter":45,"engine.io-parser":58}],51:[function(require,module,exports){ +(function (global){ +/** * Module dependencies */ @@ -15133,8 +12400,10 @@ function polling(opts){ } } -},{"./polling-jsonp":64,"./polling-xhr":65,"./websocket":67,"xmlhttprequest":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-jsonp":52,"./polling-xhr":53,"./websocket":55,"xmlhttprequest":56}],52:[function(require,module,exports){ +(function (global){ + /** * Module requirements. */ @@ -15368,8 +12637,10 @@ JSONPPolling.prototype.doWrite = function (data, fn) { } }; -},{"./polling":66,"component-inherit":69}],65:[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":54,"component-inherit":57}],53:[function(require,module,exports){ +(function (global){ +/** * Module requirements. */ @@ -15721,7 +12992,8 @@ function unloadHandler() { } } -},{"./polling":66,"component-emitter":57,"component-inherit":69,"debug":58,"xmlhttprequest":68}],66:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./polling":54,"component-emitter":45,"component-inherit":57,"debug":46,"xmlhttprequest":56}],54:[function(require,module,exports){ /** * Module dependencies. */ @@ -15968,7 +13240,7 @@ Polling.prototype.uri = function(){ return schema + '://' + this.hostname + port + this.path + query; }; -},{"../transport":62,"component-inherit":69,"debug":58,"engine.io-parser":70,"parseqs":80,"xmlhttprequest":68}],67:[function(require,module,exports){ +},{"../transport":50,"component-inherit":57,"debug":46,"engine.io-parser":58,"parseqs":68,"xmlhttprequest":56}],55:[function(require,module,exports){ /** * Module dependencies. */ @@ -16199,7 +13471,7 @@ WS.prototype.check = function(){ return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name); }; -},{"../transport":62,"component-inherit":69,"debug":58,"engine.io-parser":70,"parseqs":80,"ws":82}],68:[function(require,module,exports){ +},{"../transport":50,"component-inherit":57,"debug":46,"engine.io-parser":58,"parseqs":68,"ws":70}],56:[function(require,module,exports){ // browser shim for xmlhttprequest module var hasCORS = require('has-cors'); @@ -16237,7 +13509,7 @@ module.exports = function(opts) { } } -},{"has-cors":77}],69:[function(require,module,exports){ +},{"has-cors":65}],57:[function(require,module,exports){ module.exports = function(a, b){ var fn = function(){}; @@ -16245,8 +13517,9 @@ module.exports = function(a, b){ a.prototype = new fn; a.prototype.constructor = a; }; -},{}],70:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{}],58:[function(require,module,exports){ +(function (global){ +/** * Module dependencies. */ @@ -16813,7 +14086,8 @@ exports.decodePayloadAsBinary = function (data, binaryType, callback) { }); }; -},{"./keys":71,"after":72,"arraybuffer.slice":73,"base64-arraybuffer":74,"blob":75,"utf8":76}],71:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./keys":59,"after":60,"arraybuffer.slice":61,"base64-arraybuffer":62,"blob":63,"utf8":64}],59:[function(require,module,exports){ /** * Gets the keys for an object. @@ -16834,7 +14108,7 @@ module.exports = Object.keys || function keys (obj){ return arr; }; -},{}],72:[function(require,module,exports){ +},{}],60:[function(require,module,exports){ module.exports = after function after(count, callback, err_cb) { @@ -16864,7 +14138,7 @@ function after(count, callback, err_cb) { function noop() {} -},{}],73:[function(require,module,exports){ +},{}],61:[function(require,module,exports){ /** * An abstraction for slicing an arraybuffer even when * ArrayBuffer.prototype.slice is not supported @@ -16895,7 +14169,7 @@ module.exports = function(arraybuffer, start, end) { return result.buffer; }; -},{}],74:[function(require,module,exports){ +},{}],62:[function(require,module,exports){ /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer @@ -16956,8 +14230,9 @@ module.exports = function(arraybuffer, start, end) { }; })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); -},{}],75:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{}],63:[function(require,module,exports){ +(function (global){ +/** * Create a blob builder even when vendor prefixes exist */ @@ -17007,8 +14282,10 @@ module.exports = (function() { } })(); -},{}],76:[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 : {}) +},{}],64:[function(require,module,exports){ +(function (global){ +/*! http://mths.be/utf8js v2.0.0 by @mathias */ ;(function(root) { // Detect free variables `exports` @@ -17248,7 +14525,8 @@ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? }(this)); -},{}],77:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],65:[function(require,module,exports){ /** * Module dependencies. @@ -17273,7 +14551,7 @@ try { module.exports = false; } -},{"global":78}],78:[function(require,module,exports){ +},{"global":66}],66:[function(require,module,exports){ /** * Returns `this`. Execute this without a "context" (i.e. without it being @@ -17283,8 +14561,9 @@ try { module.exports = (function () { return this; })(); -},{}],79:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{}],67:[function(require,module,exports){ +(function (global){ +/** * JSON parse. * * @see Based on jQuery#parseJSON (MIT) and JSON2 @@ -17316,7 +14595,8 @@ module.exports = function parsejson(data) { return (new Function('return ' + data))(); } }; -},{}],80:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],68:[function(require,module,exports){ /** * Compiles a querystring * Returns string representation of the object @@ -17355,7 +14635,7 @@ exports.decode = function(qs){ return qry; }; -},{}],81:[function(require,module,exports){ +},{}],69:[function(require,module,exports){ /** * Parses an URI * @@ -17396,7 +14676,7 @@ module.exports = function parseuri(str) { return uri; }; -},{}],82:[function(require,module,exports){ +},{}],70:[function(require,module,exports){ /** * Module dependencies. @@ -17441,8 +14721,9 @@ function ws(uri, protocols, opts) { if (WebSocket) ws.prototype = WebSocket.prototype; -},{}],83:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; +},{}],71:[function(require,module,exports){ +(function (global){ + /* * Module requirements. */ @@ -17501,12 +14782,13 @@ function hasBinary(data) { return _hasBinary(data); } -},{"isarray":84}],84:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"isarray":72}],72:[function(require,module,exports){ module.exports = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; -},{}],85:[function(require,module,exports){ +},{}],73:[function(require,module,exports){ var indexOf = [].indexOf; @@ -17517,7 +14799,7 @@ module.exports = function(arr, obj){ } return -1; }; -},{}],86:[function(require,module,exports){ +},{}],74:[function(require,module,exports){ /** * HOP ref. @@ -17602,7 +14884,7 @@ exports.length = function(obj){ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; -},{}],87:[function(require,module,exports){ +},{}],75:[function(require,module,exports){ /** * Parses an URI * @@ -17629,8 +14911,9 @@ module.exports = function parseuri(str) { return uri; }; -},{}],88:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/*global Blob,File*/ +},{}],76:[function(require,module,exports){ +(function (global){ +/*global Blob,File*/ /** * Module requirements @@ -17772,7 +15055,8 @@ exports.removeBlobs = function(data, callback) { } }; -},{"./is-buffer":90,"isarray":91}],89:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./is-buffer":78,"isarray":79}],77:[function(require,module,exports){ /** * Module dependencies. @@ -18170,8 +15454,9 @@ function error(data){ }; } -},{"./binary":88,"./is-buffer":90,"component-emitter":57,"debug":58,"isarray":91,"json3":92}],90:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; +},{"./binary":76,"./is-buffer":78,"component-emitter":45,"debug":46,"isarray":79,"json3":80}],78:[function(require,module,exports){ +(function (global){ + module.exports = isBuf; /** @@ -18185,9 +15470,10 @@ function isBuf(obj) { (global.ArrayBuffer && obj instanceof ArrayBuffer); } -},{}],91:[function(require,module,exports){ -module.exports=require(84) -},{}],92:[function(require,module,exports){ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],79:[function(require,module,exports){ +module.exports=require(72) +},{}],80:[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. @@ -19050,7 +16336,7 @@ module.exports=require(84) } }(this)); -},{}],93:[function(require,module,exports){ +},{}],81:[function(require,module,exports){ module.exports = toArray function toArray(list, index) { @@ -19065,7 +16351,7 @@ function toArray(list, index) { return array } -},{}],94:[function(require,module,exports){ +},{}],82:[function(require,module,exports){ // Generated by CoffeeScript 1.7.1 (function() { var lang; @@ -19126,7 +16412,7 @@ function toArray(list, index) { }).call(this); -},{}],95:[function(require,module,exports){ +},{}],83:[function(require,module,exports){ // Generated by CoffeeScript 1.7.1 (function() { var deprecate, hasModule, makeTwix, @@ -19842,7 +17128,7 @@ function toArray(list, index) { }).call(this); -},{"./lang":94,"moment":49}],96:[function(require,module,exports){ +},{"./lang":82,"moment":37}],84:[function(require,module,exports){ // Underscore.js 1.5.2 // http://underscorejs.org // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors @@ -21120,8 +18406,8 @@ function toArray(list, index) { }).call(this); -},{}],97:[function(require,module,exports){ -module.exports=module.exports={ +},{}],85:[function(require,module,exports){ +module.exports={ "name": "joola.sdk", "preferGlobal": false, "version": "0.7.22", @@ -21182,7 +18468,7 @@ module.exports=module.exports={ "license": "GPL-3.0" } -},{}],98:[function(require,module,exports){ +},{}],86:[function(require,module,exports){ /** * @title joola/lib/sdk/common/api * @copyright (c) Joola Smart Solutions, Ltd. @@ -21488,7 +18774,7 @@ joola.events.on('rpc:done', function () { joola.usage = {currentCalls: 0}; joola.usage.currentCalls--; }); -},{"../index":105,"http":29,"https":13,"querystring":14,"url":18}],99:[function(require,module,exports){ +},{"../index":93,"http":12,"https":16,"querystring":22,"url":31}],87:[function(require,module,exports){ /** * joola * @@ -21518,7 +18804,6 @@ dispatch.buildstub = function (callback) { var self = this; dispatch.fetchMeta(function (err, result) { - joola.api.describe = {}; Object.keys(result).forEach(function (endpoints) { dispatch[endpoints] = {}; @@ -21544,6 +18829,12 @@ dispatch.buildstub = function (callback) { if (typeof args[Object.keys(args).length - 1] === 'function') { callback = args[Object.keys(args).length - 1]; } + if (fn !== 'verifyAPIToken') { + if (!joola.connected) + return callback(new Error('Joola not connected.')); + if (!joola.USER) + return callback(new Error('Joola not connected, invalid user.')); + } var argCounter = 0; var _args = {}; if (_fn.inputs.required) @@ -21601,7 +18892,7 @@ dispatch.buildstub = function (callback) { }; -},{"../../../build/temp/meta.json":1,"../index":105,"cloneextend":2}],100:[function(require,module,exports){ +},{"../../../build/temp/meta.json":1,"../index":93,"cloneextend":34}],88:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -21621,8 +18912,10 @@ var _events = new EventEmitter2({wildcard: true, newListener: true}); _events._id = 'events'; module.exports = exports = _events; -},{"../index":105,"eventemitter2":4}],101:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** + +},{"../index":93,"eventemitter2":36}],89:[function(require,module,exports){ +(function (global){ +/** * @title joola * @overview the open-source data analytics framework * @copyright Joola Smart Solutions, Ltd. @@ -21648,8 +18941,10 @@ joola.timezone = function (tz) { return offset; }; -},{"../index":105}],102:[function(require,module,exports){ -var Buffer=require("__browserify_Buffer").Buffer;/*jshint -W083 */ +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../index":93}],90:[function(require,module,exports){ +(function (Buffer){ +/*jshint -W083 */ /** * @title joola @@ -21839,7 +19134,8 @@ common.ensureLength = function (string, length) { } return string; }; -},{"../index":105,"./modifiers":104,"__browserify_Buffer":47,"cloneextend":2,"crypto":24,"deep-extend":3,"underscore":96,"util":19}],103:[function(require,module,exports){ +}).call(this,require("buffer").Buffer) +},{"../index":93,"./modifiers":92,"buffer":2,"cloneextend":34,"crypto":6,"deep-extend":35,"underscore":84,"util":33}],91:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -21910,7 +19206,7 @@ logger.error = function (message, callback) { return this._log('error', message, callback); }; -},{"../index":105}],104:[function(require,module,exports){ +},{"../index":93}],92:[function(require,module,exports){ /** * @title joola/lib/common/modifiers * @overview Includes different prototype modifiers used by joola @@ -22065,8 +19361,9 @@ Array.prototype.equals = function (array) { return true; }; -},{}],105:[function(require,module,exports){ -var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};/** +},{}],93:[function(require,module,exports){ +(function (global){ +/** * @title joola * @overview the open-source data analytics framework * @copyright Joola Smart Solutions, Ltd. @@ -22078,6 +19375,10 @@ var global=typeof self !== "undefined" ? self : typeof window !== "undefined" ? //THE OBJECT +var + util = require('util'), + EventEmitter = require('events').EventEmitter; + var joola = exports; //try injecting global @@ -22110,7 +19411,7 @@ joola.options = { timezoneOffset: null }; - +joola.connected = false; //libraries joola.globals = require('./common/globals'); joola.logger = require('./common/logger'); @@ -22118,8 +19419,12 @@ joola.dispatch = require('./common/dispatch'); joola.common = require('./common/index'); joola.events = require('./common/events'); joola.events.setMaxListeners(1000); -joola.on = joola.events.on; - +joola.on = function (event, cb) { + joola.events.on(event, cb); +}; +joola.emit = function (event, message) { + joola.events.emit(event, message); +}; joola.api = require('./common/api'); joola.state = {}; joola.viz = require('./viz/index'); @@ -22170,7 +19475,12 @@ if (isBrowser()) { if (scr.src) { if (scr.src.indexOf('joola.js') > -1 || scr.src.indexOf('joola.min.js') > -1) { var parts = require('url').parse(scr.src); - joola.options.host = parts.protocol + '//' + parts.host; + var protocol = parts.protocol; + var host = parts.host; + var port = 443; + if (protocol !== 'https:') + port = 80; + joola.options.host = parts.protocol + '//' + host + ':' + port; if (parts.query) { var qs = require('querystring').parse(parts.query); if (qs && qs.APIToken) { @@ -22180,7 +19490,13 @@ if (isBrowser()) { joola.options.token = qs.token; } if (qs && qs.host) { - joola.options.host = qs.host; + parts = require('url').parse(qs.host); + protocol = parts.protocol; + host = parts.host; + port = 443; + if (protocol !== 'https:') + port = 80; + joola.options.host = parts.protocol + '//' + host + ':' + port; } } } @@ -22188,6 +19504,8 @@ if (isBrowser()) { }); } +joola.dispatch.buildstub(); + //init procedure joola.init = function (options, callback) { callback = callback || emptyfunc; @@ -22281,7 +19599,7 @@ joola.init = function (options, callback) { //done('css'); }; css.rel = 'stylesheet'; - css.href = joola.options.host + '/joola.css'; + css.href = joola.options.host + '/joola.min.css'; document.head.appendChild(css); done('css'); } @@ -22292,101 +19610,99 @@ joola.init = function (options, callback) { return done('not browser'); } } - - browser3rd(function () { - if (options.token) { - joola._token = options.token; - } - else { - if (typeof location !== 'undefined') { - var qs = require('querystring'); - var parts = qs.parse(location.search.substring(1, location.search.length)); - if (parts.token) - joola._token = parts.token; - } - } - joola.events.emit('core.init.start'); - joola.logger.info('Starting joola client SDK, version ' + joola.VERSION); - - //else if (joola.options.isBrowser) { - if (!joola.options.host && joola.options.isBrowser) { - joola.options.host = location.protocol + '//' + location.host; + if (options.token) { + joola._token = options.token; + } + else { + if (typeof location !== 'undefined') { + var qs = require('querystring'); + var parts = qs.parse(location.search.substring(1, location.search.length)); + if (parts.token) + joola._token = parts.token; } + } + joola.events.emit('core.init.start'); + joola.logger.info('Starting joola client SDK, version ' + joola.VERSION); - if (!joola.options.host) - throw new Error('joola host not specified'); + //else if (joola.options.isBrowser) { + if (!joola.options.host && joola.options.isBrowser) { + joola.options.host = location.protocol + '//' + location.host; + } - //var io = require('socket.io-browserify'); - var io = require('socket.io-client'); - joola.io = io; - joola.io.socket = joola.io.connect(joola.options.host); + if (!joola.options.host) + throw new Error('joola host not specified'); - joola.io.socket.on('SIG_HUP', function () { - console.log('SIG_HUP'); - }); + //var io = require('socket.io-browserify'); + var io = require('socket.io-client'); + joola.io = io; + joola.io.socket = joola.io.connect(joola.options.host); - //} - //joola.config.init(function (err) { - // if (err) - // return callback(err); + joola.io.socket.on('SIG_HUP', function () { + console.log('SIG_HUP'); + }); - joola.dispatch.buildstub(function (err) { + //} + //joola.config.init(function (err) { + // if (err) + // return callback(err); + //joola.dispatch.buildstub(function (err) { + // if (err) + // return callback(err); + browser3rd(function () { + }); + if (joola.options.token) { + joola.dispatch.users.getByToken(joola._token, function (err, user) { if (err) return callback(err); - if (joola.options.token) { - joola.dispatch.users.getByToken(joola._token, function (err, user) { - if (err) - return callback(err); - - joola.USER = user; - joola.TOKEN = joola._token; - joola.events.emit('core.init.finish'); - if (callback) - return callback(null, joola); + joola.USER = user; + joola.TOKEN = joola._token; + joola.events.emit('core.init.finish'); + if (callback) + return callback(null, joola); - }); - } - else if (joola.options.APIToken) { - joola._apitoken = joola.options.APIToken; - joola.USER = null; - joola._token = null; + }); + } + else if (joola.options.APIToken) { + joola._apitoken = joola.options.APIToken; + joola.USER = null; + joola._token = null; - joola.dispatch.users.verifyAPIToken(joola._apitoken, function (err, user) { - if (err) - return callback(err); - joola.USER = user; - joola.events.emit('core.init.finish'); - joola.events.emit('ready'); - if (typeof callback === 'function') - return callback(null, joola); - }); - } - else { - joola.events.emit('core.init.finish'); - joola.events.emit('ready'); - if (typeof callback === 'function') - return callback(null, joola); - } + joola.dispatch.users.verifyAPIToken(joola._apitoken, function (err, user) { + if (err) + return callback(err); + joola.USER = user; + joola.events.emit('core.init.finish'); + joola.events.emit('ready'); + if (typeof callback === 'function') + return callback(null, joola); }); - //}); + } + else { + joola.events.emit('core.init.finish'); + joola.events.emit('ready'); + if (typeof callback === 'function') + return callback(null, joola); + } + //}); + //}); - //global function hook (for debug) - if (joola.options.debug && joola.options.debug.functions && joola.options.debug.functions.enabled) - [joola].forEach(function (obj) { - joola.common.hookEvents(obj, function (event) { - }); + //global function hook (for debug) + if (joola.options.debug && joola.options.debug.functions && joola.options.debug.functions.enabled) + [joola].forEach(function (obj) { + joola.common.hookEvents(obj, function (event) { }); + }); - //global event catcher (for debug) - if (joola.options.debug.enabled && joola.options.debug.events) - joola.events.onAny(function () { - if (joola.options.debug.events.enabled) - joola.logger.debug('Event raised: ' + this.event); - if (joola.options.debug.events.enabled && joola.options.debug.events.trace) - console.trace(); - }); - }); + //global event catcher (for debug) + if (joola.options.debug.enabled && joola.options.debug.events) + joola.events.onAny(function () { + if (joola.options.debug.events.enabled) + joola.logger.debug('Event raised: ' + this.event); + if (joola.options.debug.events.enabled && joola.options.debug.events.trace) + console.trace(); + }); + //}); }; if (joola.options.APIToken || joola.options.token) { @@ -22435,11 +19751,14 @@ joola.colors = ['#058DC7', '#50B432', '#ED7E17', '#AF49C5', '#EDEF00', '#8080FF' joola.offcolors = ['#AADFF3', '#C9E7BE', '#F2D5BD', '#E1C9E8', '#F6F3B1', '#DADBFB', '#E7E6B4', '#F4B3BC', '#AADFF3', '#F2D5BD', '#C9E7BE', '#EEEEEE']; var start = new Date().getTime(); -joola.events.on('ready', function () { +joola.on('ready', function () { + joola.connected = true; var end = new Date().getTime(); console.log('loaded in ', end - start, 'ms.'); }); -},{"./../../package.json":97,"./common/api":98,"./common/dispatch":99,"./common/events":100,"./common/globals":101,"./common/index":102,"./common/logger":103,"./viz/index":120,"querystring":14,"socket.io-client":50,"url":18}],106:[function(require,module,exports){ + +}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./../../package.json":85,"./common/api":86,"./common/dispatch":87,"./common/events":88,"./common/globals":89,"./common/index":90,"./common/logger":91,"./viz/index":108,"events":11,"querystring":22,"socket.io-client":38,"url":31,"util":33}],94:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -22811,7 +20130,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":105,"./_proto":119,"underscore":96}],107:[function(require,module,exports){ +},{"../index":93,"./_proto":107,"underscore":84}],95:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -23058,7 +20377,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":105,"./_proto":119,"cloneextend":2,"eventemitter2":4,"underscore":96}],108:[function(require,module,exports){ +},{"../index":93,"./_proto":107,"cloneextend":34,"eventemitter2":36,"underscore":84}],96:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -24056,7 +21375,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":105,"./_proto":119,"underscore":96}],109:[function(require,module,exports){ +},{"../index":93,"./_proto":107,"underscore":84}],97:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -24372,88 +21691,7 @@ DimensionPicker.template = function (options) { return html; }; -DimensionPicker.meta = { - key: 'dimensionpicker', - jQueryTag: 'Metric', - title: 'Metric Box', - tagline: '', - description: '' + - 'Metric Boxes...', - longDescription: '', - example: { - css: 'width:100%', - options: { - caption: 'Mouse moves (last month)', - template: '
', - query: { - timeframe: 'last_month', - interval: 'day', - dimensions: ['mousemoves'], - collection: 'demo-mousemoves', - "realtime": true - } - }, - draw: '$("#example").Metric(options);' - }, - template: DimensionPicker.template(), - metaOptions: { - container: { - datatype: 'string', - defaultValue: null, - description: '`optional` if using jQuery plugin. contains the Id of the HTML container.' - }, - template: { - datatype: 'string', - defaultValue: null, - description: '`optional` Specify the HTML template to use instead of the default one.' - }, - caption: { - datatype: 'string', - defaultValue: null, - description: '`optional` the caption for the dimension.' - }, - query: { - datatype: 'object', - defaultValue: null, - description: '`required` contains the query object.' - } - }, - metaMethods: { - init: { - signature: '.init(options)', - description: 'Initialize the visualization with a set of `options`.', - example: '$(\'#visualization\').init(options);' - }, - update: { - signature: '.update(options)', - description: 'Update an existing visualization with a set of `options`.', - example: '$(\'#visualization\').update(options);' - }, - destroy: { - signature: '.destroy()', - description: 'Destroy the visualization.', - example: '$(\'#visualization\').destroy();' - } - }, - metaEvents: { - load: { - description: 'Visualization loaded.' - }, - draw: { - description: 'The visualization HTML frame has been drawn on screen.' - }, - destroy: { - description: 'Visualization destroyed.' - }, - update: { - description: 'The underlying data has changed.' - }, - select: { - description: 'Selection changed, dimension box clicked.' - } - } -}; -},{"./_proto":119,"cloneextend":2,"eventemitter2":4}],110:[function(require,module,exports){ +},{"./_proto":107,"cloneextend":34,"eventemitter2":36}],98:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -24593,7 +21831,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":105,"./_proto":119}],111:[function(require,module,exports){ +},{"../index":93,"./_proto":107}],99:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -24851,88 +22089,7 @@ Metric.template = function (options) { return html; }; -Metric.meta = { - key: 'metricbox', - jQueryTag: 'Metric', - title: 'Metric Box', - tagline: '', - description: '' + - 'Metric Boxes...', - longDescription: '', - example: { - css: 'width:100%', - options: { - caption: 'Mouse moves (last month)', - template: '
', - query: { - timeframe: 'last_month', - interval: 'day', - metrics: ['mousemoves'], - collection: 'demo-mousemoves', - "realtime": true - } - }, - draw: '$("#example").Metric(options);' - }, - template: Metric.template(), - metaOptions: { - container: { - datatype: 'string', - defaultValue: null, - description: '`optional` if using jQuery plugin. contains the Id of the HTML container.' - }, - template: { - datatype: 'string', - defaultValue: null, - description: '`optional` Specify the HTML template to use instead of the default one.' - }, - caption: { - datatype: 'string', - defaultValue: null, - description: '`optional` the caption for the metric.' - }, - query: { - datatype: 'object', - defaultValue: null, - description: '`required` contains the query object.' - } - }, - metaMethods: { - init: { - signature: '.init(options)', - description: 'Initialize the visualization with a set of `options`.', - example: '$(\'#visualization\').init(options);' - }, - update: { - signature: '.update(options)', - description: 'Update an existing visualization with a set of `options`.', - example: '$(\'#visualization\').update(options);' - }, - destroy: { - signature: '.destroy()', - description: 'Destroy the visualization.', - example: '$(\'#visualization\').destroy();' - } - }, - metaEvents: { - load: { - description: 'Visualization loaded.' - }, - draw: { - description: 'The visualization HTML frame has been drawn on screen.' - }, - destroy: { - description: 'Visualization destroyed.' - }, - update: { - description: 'The underlying data has changed.' - }, - select: { - description: 'Selection changed, metric box clicked.' - } - } -}; -},{"../index":105,"./_proto":119,"cloneextend":2}],112:[function(require,module,exports){ +},{"../index":93,"./_proto":107,"cloneextend":34}],100:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -25247,88 +22404,7 @@ MetricPicker.template = function (options) { return html; }; -MetricPicker.meta = { - key: 'metricpicker', - jQueryTag: 'Metric', - title: 'Metric Box', - tagline: '', - description: '' + - 'Metric Boxes...', - longDescription: '', - example: { - css: 'width:100%', - options: { - caption: 'Mouse moves (last month)', - template: '
', - query: { - timeframe: 'last_month', - interval: 'day', - metrics: ['mousemoves'], - collection: 'demo-mousemoves', - "realtime": true - } - }, - draw: '$("#example").Metric(options);' - }, - template: MetricPicker.template(), - metaOptions: { - container: { - datatype: 'string', - defaultValue: null, - description: '`optional` if using jQuery plugin. contains the Id of the HTML container.' - }, - template: { - datatype: 'string', - defaultValue: null, - description: '`optional` Specify the HTML template to use instead of the default one.' - }, - caption: { - datatype: 'string', - defaultValue: null, - description: '`optional` the caption for the metric.' - }, - query: { - datatype: 'object', - defaultValue: null, - description: '`required` contains the query object.' - } - }, - metaMethods: { - init: { - signature: '.init(options)', - description: 'Initialize the visualization with a set of `options`.', - example: '$(\'#visualization\').init(options);' - }, - update: { - signature: '.update(options)', - description: 'Update an existing visualization with a set of `options`.', - example: '$(\'#visualization\').update(options);' - }, - destroy: { - signature: '.destroy()', - description: 'Destroy the visualization.', - example: '$(\'#visualization\').destroy();' - } - }, - metaEvents: { - load: { - description: 'Visualization loaded.' - }, - draw: { - description: 'The visualization HTML frame has been drawn on screen.' - }, - destroy: { - description: 'Visualization destroyed.' - }, - update: { - description: 'The underlying data has changed.' - }, - select: { - description: 'Selection changed, metric box clicked.' - } - } -}; -},{"./_proto":119,"cloneextend":2,"eventemitter2":4}],113:[function(require,module,exports){ +},{"./_proto":107,"cloneextend":34,"eventemitter2":36}],101:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -25631,7 +22707,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":105,"./_proto":119,"underscore":96}],114:[function(require,module,exports){ +},{"../index":93,"./_proto":107,"underscore":84}],102:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -25863,112 +22939,7 @@ Pie.template = function (options) { return html; }; -Pie.meta = { - key: 'pie-chart', - jQueryTag: 'Pie', - title: 'Pie Chart', - tagline: '', - description: '' + - 'Pie Charts are mainly used to provide a high-level overview of metrics based on categories. ' + - 'For example, how many visitors a site had based on their browser.', - longDescription: '', - example: { - css: 'height:250px;width:100%', - options: { - query: { - timeframe: 'last_month', - interval: 'day', - dimensions: ['browser'], - metrics: ['mousemoves'], - collection: 'demo-mousemoves', - "realtime": true - } - }, - draw: '$("#example").Pie(options);', - external: [ - { - title: 'Change Pie Limits', - src: 'http://jsfiddle.com' - }, - { - title: 'Another example', - src: 'http://jsfiddle.com' - }, - { - title: 'And yet another', - src: 'http://jsfiddle.com' - } - ] - }, - template: Pie.template(), - metaOptions: { - container: { - datatype: 'string', - defaultValue: null, - description: '`optional` if using jQuery plugin. contains the Id of the HTML container.' - }, - template: { - datatype: 'string', - defaultValue: null, - description: '`optional` Specify the HTML template to use instead of the default one.' - }, - query: { - datatype: 'object', - defaultValue: null, - description: '`required` contains the query object.' - }, - chart: { - datatype: 'object', - defaultValue: null, - description: '`optional` Options for the charting provider.' - }, - limit: { - datatype: 'number', - defaultValue: '5', - description: '`optional` The number of items to show.' - }, - legend: { - datatype: 'bool', - defaultValue: 'true', - description: '`optional` Show the Pie Chart legend.' - } - }, - metaMethods: { - init: { - signature: '.init(options)', - description: 'Initialize the visualization with a set of `options`.', - example: '$(\'#visualization\').init(options);' - }, - update: { - signature: '.update(options)', - description: 'Update an existing visualization with a set of `options`.', - example: '$(\'#visualization\').update(options);' - }, - destroy: { - signature: '.destroy()', - description: 'Destroy the visualization.', - example: '$(\'#visualization\').destroy();' - } - }, - metaEvents: { - load: { - description: 'Visualization loaded.' - }, - draw: { - description: 'The visualization HTML frame has been drawn on screen.' - }, - destroy: { - description: 'Visualization destroyed.' - }, - update: { - description: 'The underlying data has changed.' - }, - select: { - description: 'Selection changed, pie chart slice clicked.' - } - } -}; -},{"../index":105,"./_proto":119,"underscore":96}],115:[function(require,module,exports){ +},{"../index":93,"./_proto":107,"underscore":84}],103:[function(require,module,exports){ /*jshint -W083 */ /** @@ -26195,7 +23166,7 @@ joola.events.on('core.init.finish', function () { }); -},{"../index":105,"./_proto":119,"underscore":96}],116:[function(require,module,exports){ +},{"../index":93,"./_proto":107,"underscore":84}],104:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -26457,7 +23428,7 @@ joola.events.on('core.init.finish', function () { }; } }); -},{"../index":105,"./_proto":119}],117:[function(require,module,exports){ +},{"../index":93,"./_proto":107}],105:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -26866,106 +23837,7 @@ Table.template = function (options) { return html; }; -Table.meta = { - key: 'table', - jQueryTag: 'Table', - title: 'Table', - tagline: '', - description: '' + - 'Plot powerful and customizable data tables.', - longDescription: '', - example: { - //css: 'height:250px;width:100%', - options: { - limit: 5, - query: { - timeframe: 'last_month', - interval: 'day', - dimensions: ['browser'], - metrics: [ - {key: 'mousemoves', name: "Mouse Moves", collection: 'demo-mousemoves'}, - {key: 'clicks', suffix: " clk.", collection: 'demo-clicks'}, - {key: 'visits', collection: 'demo-visits'} - ], - collection: 'demo-mousemoves', - "realtime": true - } - }, - draw: '$("#example").Table(options);'/*, - external: [ - { - title: 'Change Pie Limits', - src: 'http://jsfiddle.com' - }, - { - title: 'Another example', - src: 'http://jsfiddle.com' - }, - { - title: 'And yet another', - src: 'http://jsfiddle.com' - } - ]*/ - }, - template: Table.template(), - metaOptions: { - container: { - datatype: 'string', - defaultValue: null, - description: '`optional` if using jQuery plugin. contains the Id of the HTML container.' - }, - template: { - datatype: 'string', - defaultValue: null, - description: '`optional` Specify the HTML template to use instead of the default one.' - }, - query: { - datatype: 'object', - defaultValue: null, - description: '`required` contains the query object.' - }, - limit: { - datatype: 'number', - defaultValue: '5', - description: 'The number of items to show.' - } - }, - metaMethods: { - init: { - signature: '.init(options)', - description: 'Initialize the visualization with a set of `options`.', - example: '$(\'#visualization\').init(options);' - }, - update: { - signature: '.update(options)', - description: 'Update an existing visualization with a set of `options`.', - example: '$(\'#visualization\').update(options);' - }, - destroy: { - signature: '.destroy()', - description: 'Destroy the visualization.', - example: '$(\'#visualization\').destroy();' - } - }, - metaEvents: { - load: { - description: 'Visualization loaded.' - }, - draw: { - description: 'The visualization HTML frame has been drawn on screen.' - }, - destroy: { - description: 'Visualization destroyed.' - }, - update: { - description: 'The underlying data has changed.' - }, - select: { - description: 'Selection changed, table row clicked.' - } - } -}; -},{"../index":105,"./_proto":119,"underscore":96}],118:[function(require,module,exports){ +},{"../index":93,"./_proto":107,"underscore":84}],106:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -27424,97 +24296,7 @@ Timeline.template = function (options) { return html; }; -Timeline.meta = { - key: 'timeline', - title: 'Timeline', - tagline: '', - jQueryTag: 'Timeline', - description: '' + - 'Timelines are a great way to show metrics over time.' + - '', - example: { - css: 'height:250px;', - options: { - caption: 'Mouse moves (last 30 seconds)', - chart: { - chart: { - spacing: 0, - backgroundColor: 'transparent', - type: 'column' - }, - plotOptions: { - column: { - color: 'rgba(240,95,104,1)' - } - } - }, - query: { - timeframe: 'last_30_seconds', - interval: 'second', - dimensions: ['timestamp'], - metrics: ['mousemoves'], - collection: 'demo-mousemoves', - realtime: true - } - }, - draw: '$("#example").Timeline(options)', - more: [ - 'http://jsfiddle.com/' - ] - }, - template: Timeline.template(), - metaOptions: { - container: { - datatype: 'string', - defaultValue: null, - description: '`optional` if using jQuery plugin. contains the Id of the HTML container.' - }, - template: { - datatype: 'string', - defaultValue: null, - description: '`optional` Specify the HTML template to use instead of the default one.' - }, - caption: { - datatype: 'string', - defaultValue: null, - description: '`optional` the caption for the metric.' - }, - query: { - datatype: 'object', - defaultValue: null, - description: '`required` contains the `query` object.' - }, - chart: { - datatype: 'object', - defaultValue: null, - description: 'Options for the charting provider.' - } - }, - metaEvents: { - load: { - description: 'Visualization loaded.' - }, - draw: { - description: 'The visualization HTML frame has been drawn on screen.' - }, - destroy: { - description: 'Visualization destroyed.' - }, - update: { - description: 'The underlying data has changed.' - }, - select: { - description: 'Selection changed, data point clicked.' - } - }, - html: '', - css: { - - }, - chartProvider: 'highcharts', - license: 'MIT' -}; -},{"../index":105,"./_proto":119,"moment":49,"underscore":96}],119:[function(require,module,exports){ +},{"../index":93,"./_proto":107,"moment":37,"underscore":84}],107:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -27656,13 +24438,35 @@ proto.makeChartTimelineSeries = function (message) { var yAxis = [null, null]; var series = []; var seriesIndex = -1; + var interval = self.options.query.interval; + var checkExists = function (timestampDimension, documents, date) { + return _.find(documents, function (document) { + switch (interval) { + case 'month': + case 'day': + date.setHours(date.getHours() - (date.getTimezoneOffset() / 60)); + return new Date(document.values[timestampDimension.key]).getTime() === date.getTime(); + default: + return new Date(document.values[timestampDimension.key]).getTime() === date.getTime(); + } + }); + }; + var fill = function (resultRow, row, timestampDimension) { + Object.keys(resultRow).forEach(function (key) { + if (key !== timestampDimension.key) { + row.values[key] = 0; + row.fvalues[key] = 0; + } + }); + }; + message.forEach(function (result, resultIndex) { var dimensions = result.dimensions; var metrics = result.metrics; var documents = ce.clone(result.documents); //should we fill the date range var query = ce.clone(result.query); - var interval = self.options.query.interval; + var timestampDimension = _.find(result.dimensions, function (item) { return item.datatype === 'date'; }); @@ -27674,18 +24478,6 @@ proto.makeChartTimelineSeries = function (message) { query.timeframe.start = result.documents[result.documents.length - 1].values.timestamp; query.timeframe.end = result.documents[0].values.timestamp; } - var checkExists = function (timestampDimension, documents, date) { - return _.find(documents, function (document) { - switch (interval) { - case 'month': - case 'day': - date.setHours(date.getHours() - (date.getTimezoneOffset() / 60)); - return new Date(document.values[timestampDimension.key]).getTime() === date.getTime(); - default: - return new Date(document.values[timestampDimension.key]).getTime() === date.getTime(); - } - }); - }; var counter = 0; var fixed = []; @@ -27702,17 +24494,19 @@ proto.makeChartTimelineSeries = function (message) { exists = {values: {}, fvalues: {}}; exists.values[timestampDimension.key] = _d.toISOString(); exists.fvalues[timestampDimension.key] = _d.toISOString(); - Object.keys(result.documents[0].values).forEach(function (key) { - if (key !== timestampDimension.key) { - exists.values[key] = 0; - exists.fvalues[key] = 0; - } - }); + fill(result.documents[0].values, exists, timestampDimension); + /*Object.keys(result.documents[0].values).forEach(function (key) { + if (key !== timestampDimension.key) { + exists.values[key] = 0; + exists.fvalues[key] = 0; + } + });*/ } fixed.push(exists); } + documents = fixed; } - documents = fixed; + if (!metrics) return series; metrics.forEach(function (metric, index) { @@ -27853,7 +24647,7 @@ proto.find = function (obj) { }; -},{"../index":105,"cloneextend":2,"moment":49,"twix":95,"underscore":96}],120:[function(require,module,exports){ +},{"../index":93,"cloneextend":34,"moment":37,"twix":83,"underscore":84}],108:[function(require,module,exports){ /** * @title joola * @overview the open-source data analytics framework @@ -27895,5 +24689,4 @@ viz.stam = function (callback) { return viz.pickers.init(callback); }; -},{"../index":105,"./BarTable":106,"./Canvas":107,"./DatePicker":108,"./DimensionPicker":109,"./Geo":110,"./Metric":111,"./MetricPicker":112,"./MiniTable":113,"./Pie":114,"./PunchCard":115,"./Sparkline":116,"./Table":117,"./Timeline":118}]},{},[105]) -; \ No newline at end of file +},{"../index":93,"./BarTable":94,"./Canvas":95,"./DatePicker":96,"./DimensionPicker":97,"./Geo":98,"./Metric":99,"./MetricPicker":100,"./MiniTable":101,"./Pie":102,"./PunchCard":103,"./Sparkline":104,"./Table":105,"./Timeline":106}]},{},[93]) \ No newline at end of file diff --git a/build/release/joola.min.css b/build/release/joola.min.css index 30657fe..8889553 100644 --- a/build/release/joola.min.css +++ b/build/release/joola.min.css @@ -1,2 +1,2 @@ /*! joola.sdk - v0.7.22 - 2014-11-18 */ -[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 +[jio-domain=joola]{margin:0;padding:0}[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} \ No newline at end of file diff --git a/build/release/joola.min.js b/build/release/joola.min.js index ab5ea07..766130b 100644 --- a/build/release/joola.min.js +++ b/build/release/joola.min.js @@ -7,8 +7,8 @@ return arguments.length>=3&&(d.depth=arguments[2]),arguments.length>=4&&(d.color 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.readyState="closed",this.engine&&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||this.skipReconnect)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(){a.skipReconnect||(j("attempting reconnect"),a.emitAll("reconnect_attempt",a.attempts),a.emitAll("reconnecting",a.attempts),a.skipReconnect||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":41,"./socket":42,"./url":43,"component-bind":44,"component-emitter":45,debug:46,"engine.io-client":47,indexof:73,"object-component":74,"socket.io-parser":77}],41:[function(a,b){function c(a,b,c){return a.on(b,c),{destroy:function(){a.removeListener(b,c)}}}b.exports=c},{}],42:[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}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");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(){if(!this.subs){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.subEvents(),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}},{}],46:[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){}},{}],47:[function(a,b){b.exports=a("./lib/")},{"./lib/":48}],48:[function(a,b){b.exports=a("./socket"),b.exports.parser=a("engine.io-parser")},{"./socket":49,"engine.io-parser":58}],49:[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){if(h('probe transport "%s" pong',a),m.upgrading=!0,m.emit("upgrading",k),!k)return;d.priorWebsocketSuccess="websocket"==k.name,h('pausing current transport "%s"',m.transport.name),m.transport.pause(function(){l||"closed"!=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":50,"./transports":51,"component-emitter":45,debug:46,"engine.io-parser":58,indexof:73,parsejson:67,parseqs:68,parseuri:69}],50:[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":45,"engine.io-parser":58}],51:[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":52,"./polling-xhr":53,"./websocket":55,xmlhttprequest:56}],52:[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,this.iframe=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='