From a986b601d5132baae0345b6462da2b908405580e Mon Sep 17 00:00:00 2001 From: Petka Antonov Date: Mon, 22 Dec 2014 00:43:39 +0200 Subject: [PATCH] Make browser testing more sensical --- .gitignore | 2 +- .travis.yml | 8 +- Gruntfile.js | 18 +- README.md | 5 +- browser/bundle.js | 32492 ---------------------------------------- browser/bundler.js | 43 - browser/do_run.js | 52 - browser/index.html | 8 +- browser/init_run.js | 21 - browser/main.js | 130 + browser/mocha.css | 158 +- browser/mocha.js | 2781 +++- browser/mocha_init.js | 7 - browser/setup | 4 - package.json | 5 +- src/race.js | 3 +- test/mocha/cancel.js | 12 +- test/mocha/timers.js | 57 +- 18 files changed, 2407 insertions(+), 33399 deletions(-) delete mode 100644 browser/bundle.js delete mode 100644 browser/bundler.js delete mode 100644 browser/do_run.js delete mode 100644 browser/init_run.js create mode 100644 browser/main.js delete mode 100644 browser/mocha_init.js delete mode 100644 browser/setup diff --git a/.gitignore b/.gitignore index e285ade6f..5c4abe416 100644 --- a/.gitignore +++ b/.gitignore @@ -6,9 +6,9 @@ benchmark/async-compare/node_modules/* benchmark/promises-benchmark/node_modules/* benchmark/promises-benchmark/fixtures/* benchmark/perf-promises/node_modules/* -browser/main.js async sync +browser/bundle.js mixed bench.json js/bluebird_sync.min.js diff --git a/.travis.yml b/.travis.yml index b6c37e5f9..713238953 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,11 +1,7 @@ language: node_js node_js: - '0.10' -install: 'npm install grunt grunt-contrib-jshint grunt-contrib-watch acorn q mocha sinon grunt-cli grunt-contrib-connect grunt-saucelabs mkdirp' +install: 'npm install browserify grunt grunt-contrib-jshint grunt-contrib-watch acorn q mocha sinon grunt-cli grunt-contrib-connect grunt-saucelabs mkdirp' before_script: - git submodule update --init --recursive -script: 'grunt test --ci && grunt test-browser --ci' -env: - global: - - secure: lFeRife2Lr6vaiVAKjRg2VyTP8Gu+1z6i0JeQ4w6BfAbIkpAgFLOsyVH5QGlnmOLclBtMIHMcNGOCH3RfozVd26TPZMPslPCgh4zal0hCYQHE1n0Cpqsq/m7aA8WlhYd2RGx4A/zZaJ5ZVhUPLnpAAnEocslMsW4aRzkb3aJHIs= - - secure: U4//Sr89P3kGimkmxRr7gqYRtvaoy4HQXtPIORAlIX1BPXxS4EJ63JCgbEtqNSnIZ0/ybjTlpT7AHcBkMUX7BWjQojTj4sEmUeYe4jorK8NVCpam3r99q5XhsdFzJ3t2R0pLiC4q9GyuTyUitJmZ4U7jHbrXkfh7UJ3FdqIECv4= +script: 'grunt test --ci && npm run browsers && grunt test-browser --ci' diff --git a/Gruntfile.js b/Gruntfile.js index bb9610828..571b2a2b0 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -26,12 +26,11 @@ module.exports = function( grunt ) { function getBrowsers() { //Terse format to generate the verbose format required by sauce var browsers = { - "internet explorer|WIN8": ["10"], - "internet explorer|WIN8.1": ["11"], - "firefox|Windows 7": ["3.5", "4", "25"], - "chrome|Windows 7": null, - "safari|Windows 7": ["5"], - "iphone|OS X 10.8": ["6.0"] + "internet explorer|Windows XP": ["7", "8"], + "internet explorer|Windows 7": ["9"], + "firefox|Windows 7": ["3.5", "4", "25", "33"], + "chrome|Windows 7": ["beta"], + "safari|Windows 7": ["5"] }; var ret = []; @@ -51,7 +50,7 @@ module.exports = function( grunt ) { } else { ret.push({ - browserName: browser, + browserNAme: browser, platform: platform }); } @@ -326,9 +325,10 @@ module.exports = function( grunt ) { all: { options: { urls: ["http://127.0.0.1:9999/index.html"], - tunnelTimeout: 5, + tunnelTimeout: 30, build: process.env.TRAVIS_JOB_ID, - concurrency: 3, + maxPollRetries: 3, + throttled: 3, browsers: getBrowsers(), testname: "mocha tests", tags: ["master"] diff --git a/README.md b/README.md index 0884c481d..140410ebf 100644 --- a/README.md +++ b/README.md @@ -475,10 +475,9 @@ The reason for the unusual way of testing is because the majority of tests are f To test in browsers: - cd browser - setup + npm run browsers -Then open the `index.html` in your browser. Requires bash (on windows the mingw32 that comes with git works fine too). +Then open the `browser/index.html` in your browser. You may also [visit the github hosted page](http://petkaantonov.github.io/bluebird/browser/). diff --git a/browser/bundle.js b/browser/bundle.js deleted file mode 100644 index 7b20c280b..000000000 --- a/browser/bundle.js +++ /dev/null @@ -1,32492 +0,0 @@ -;(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 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; -} - -},{}],2:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// UTILITY -var util = require('util'); -var shims = require('_shims'); -var pSlice = Array.prototype.slice; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - this.message = options.message || getMessage(this); -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; -} - -function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} - -function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try { - var ka = shims.keys(a), - kb = shims.keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; - -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (util.isString(expected)) { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function(err) { if (err) {throw err;}}; -},{"_shims":1,"util":6}],3:[function(require,module,exports){ - -// not implemented -// The reason for having an empty file and not throwing is to allow -// untraditional implementation of this module. - -},{}],4:[function(require,module,exports){ -module.exports=require(3) -},{}],5:[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. - -var util = require('util'); -var shims = require('_shims'); - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = - /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; -var splitPath = function(filename) { - return splitPathRe.exec(filename).slice(1); -}; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) ? arguments[i] : process.cwd(); - - // Skip empty and invalid entries - if (!util.isString(path)) { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeArray(shims.filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; - -// path.normalize(path) -// posix version -exports.normalize = function(path) { - var isAbsolute = exports.isAbsolute(path), - trailingSlash = shims.substr(path, -1) === '/'; - - // Normalize the path - path = normalizeArray(shims.filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; -}; - -// posix version -exports.isAbsolute = function(path) { - return path.charAt(0) === '/'; -}; - -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(shims.filter(paths, function(p, index) { - if (!util.isString(p)) { - throw new TypeError('Arguments to path.join must be strings'); - } - return p; - }).join('/')); -}; - - -// path.relative(from, to) -// posix version -exports.relative = function(from, to) { - from = exports.resolve(from).substr(1); - to = exports.resolve(to).substr(1); - - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - - return outputParts.join('/'); -}; - -exports.sep = '/'; -exports.delimiter = ':'; - -exports.dirname = function(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; -}; - - -exports.basename = function(path, ext) { - var f = splitPath(path)[2]; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -}; - - -exports.extname = function(path) { - return splitPath(path)[3]; -}; - -},{"__browserify_process":16,"_shims":1,"util":6}],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. - -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(' '); - } - - 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; -}; - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - shims.forEach(array, function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = shims.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = shims.getOwnPropertyNames(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - - shims.forEach(keys, function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = 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 (!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'); - } - } - - 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); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return shims.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && objectToString(e) === '[object Error]'; -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.binarySlice === 'function' - ; -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = function(ctor, superCtor) { - ctor.super_ = superCtor; - ctor.prototype = shims.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); -}; - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = shims.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -},{"_shims":1}],7:[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]; - - 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; -}; - -},{}],8:[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":7,"assert":2,"base64-js":9}],9:[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; -}()); - -},{}],10:[function(require,module,exports){ -var Buffer = require('buffer').Buffer; -var intSize = 4; -var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0); -var chrsz = 8; - -function toArray(buf, bigEndian) { - if ((buf.length % intSize) !== 0) { - var len = buf.length + (intSize - (buf.length % intSize)); - buf = Buffer.concat([buf, zeroBuffer], len); - } - - 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; -} - -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 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); -} - -module.exports = { hash: hash }; - -},{"buffer":8}],11:[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') - -var algorithms = { - sha1: sha, - sha256: sha256, - md5: md5 -} - -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) - } - - 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 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) { - 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 error () { - var m = [].slice.call(arguments).join(' ') - throw new Error([ - m, - 'we accept pull requests', - 'http://github.com/dominictarr/crypto-browserify' - ].join('\n')) -} - -exports.createHash = function (alg) { return hash(alg) } -exports.createHmac = function (alg, key) { return hash(alg, key) } -exports.randomBytes = function(size, callback) { - if (callback && callback.call) { - try { - callback.call(this, undefined, new Buffer(rng(size))) - } catch (err) { callback(err) } - } else { - return new Buffer(rng(size)) - } -} - -function each(a, f) { - for(var i in a) - f(a[i], i) -} - -// the least I can do is make error messages for the rest of the node.js/crypto api. -each(['createCredentials' -, 'createCipher' -, 'createCipheriv' -, 'createDecipher' -, 'createDecipheriv' -, 'createSign' -, 'createVerify' -, 'createDiffieHellman' -, 'pbkdf2'], function (name) { - exports[name] = function () { - error('sorry,', name, 'is not implemented yet') - } -}) - -},{"./md5":12,"./rng":13,"./sha":14,"./sha256":15,"buffer":8}],12:[function(require,module,exports){ -/* - * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message - * Digest Algorithm, as defined in RFC 1321. - * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for more info. - */ - -var helpers = require('./helpers'); - -/* - * Perform a simple self-test to see if the VM is working - */ -function md5_vm_test() -{ - return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72"; -} - -/* - * Calculate the MD5 of an array of little-endian words, and a bit length - */ -function core_md5(x, len) -{ - /* append padding */ - x[len >> 5] |= 0x80 << ((len) % 32); - x[(((len + 64) >>> 9) << 4) + 14] = len; - - var a = 1732584193; - var b = -271733879; - var c = -1732584194; - var d = 271733878; - - for(var i = 0; i < x.length; i += 16) - { - var olda = a; - var oldb = b; - var oldc = c; - var oldd = d; - - a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936); - d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586); - c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819); - b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330); - a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897); - d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426); - c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341); - b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983); - a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416); - d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417); - c = md5_ff(c, d, a, b, x[i+10], 17, -42063); - b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162); - a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682); - d = md5_ff(d, a, b, c, x[i+13], 12, -40341101); - c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290); - b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329); - - a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510); - d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632); - c = md5_gg(c, d, a, b, x[i+11], 14, 643717713); - b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302); - a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691); - d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083); - c = md5_gg(c, d, a, b, x[i+15], 14, -660478335); - b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848); - a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438); - d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690); - c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961); - b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501); - a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467); - d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784); - c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473); - b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734); - - a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558); - d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463); - c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562); - b = md5_hh(b, c, d, a, x[i+14], 23, -35309556); - a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060); - d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353); - c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632); - b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640); - a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174); - d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222); - c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979); - b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189); - a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487); - d = md5_hh(d, a, b, c, x[i+12], 11, -421815835); - c = md5_hh(c, d, a, b, x[i+15], 16, 530742520); - b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651); - - a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844); - d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415); - c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905); - b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055); - a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571); - d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606); - c = md5_ii(c, d, a, b, x[i+10], 15, -1051523); - b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799); - a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359); - d = md5_ii(d, a, b, c, x[i+15], 10, -30611744); - c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380); - b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649); - a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070); - d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379); - c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259); - b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551); - - a = safe_add(a, olda); - b = safe_add(b, oldb); - c = safe_add(c, oldc); - d = safe_add(d, oldd); - } - return Array(a, b, c, d); - -} - -/* - * These functions implement the four basic operations the algorithm uses. - */ -function md5_cmn(q, a, b, x, s, t) -{ - return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b); -} -function md5_ff(a, b, c, d, x, s, t) -{ - return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); -} -function md5_gg(a, b, c, d, x, s, t) -{ - return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); -} -function md5_hh(a, b, c, d, x, s, t) -{ - return md5_cmn(b ^ c ^ d, a, b, x, s, t); -} -function md5_ii(a, b, c, d, x, s, t) -{ - return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); -} - -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ -function safe_add(x, y) -{ - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); -} - -/* - * Bitwise rotate a 32-bit number to the left. - */ -function bit_rol(num, cnt) -{ - return (num << cnt) | (num >>> (32 - cnt)); -} - -module.exports = function md5(buf) { - return helpers.hash(buf, core_md5, 16); -}; - -},{"./helpers":10}],13:[function(require,module,exports){ -// Original code adapted from Robert Kieffer. -// details at https://github.com/broofa/node-uuid -(function() { - var _global = this; - - var mathRNG, whatwgRNG; - - // 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; - } - - return bytes; - } - - if (_global.crypto && crypto.getRandomValues) { - var _rnds = new Uint32Array(4); - whatwgRNG = function(size) { - var bytes = new Array(size); - crypto.getRandomValues(_rnds); - - for (var c = 0 ; c < size; c++) { - bytes[c] = _rnds[c >> 2] >>> ((c & 0x03) * 8) & 0xff; - } - return bytes; - } - } - - module.exports = whatwgRNG || mathRNG; - -}()) - -},{}],14:[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. - */ - -var helpers = require('./helpers'); - -/* - * Perform a simple self-test to see if the VM is working - */ -function sha1_vm_test() -{ - return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d"; -} - -/* - * 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); - -} - -/* - * 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; -} - -/* - * Determine the appropriate additive constant for the current iteration - */ -function sha1_kt(t) -{ - return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : - (t < 60) ? -1894007588 : -899497514; -} - -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ -function safe_add(x, y) -{ - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); -} - -/* - * Bitwise rotate a 32-bit number to the left. - */ -function rol(num, cnt) -{ - return (num << cnt) | (num >>> (32 - cnt)); -} - -module.exports = function sha1(buf) { - return helpers.hash(buf, core_sha1, 20, true); -}; - -},{"./helpers":10}],15:[function(require,module,exports){ - -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - -var helpers = require('./helpers'); - -var safe_add = function(x, y) { - var lsw = (x & 0xFFFF) + (y & 0xFFFF); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return (msw << 16) | (lsw & 0xFFFF); -}; - -var S = function(X, n) { - return (X >>> n) | (X << (32 - n)); -}; - -var R = function(X, n) { - return (X >>> n); -}; - -var Ch = function(x, y, z) { - return ((x & y) ^ ((~x) & z)); -}; - -var Maj = function(x, y, z) { - return ((x & y) ^ (x & z) ^ (y & z)); -}; - -var Sigma0256 = function(x) { - return (S(x, 2) ^ S(x, 13) ^ S(x, 22)); -}; - -var Sigma1256 = function(x) { - return (S(x, 6) ^ S(x, 11) ^ S(x, 25)); -}; - -var Gamma0256 = function(x) { - return (S(x, 7) ^ S(x, 18) ^ R(x, 3)); -}; - -var Gamma1256 = function(x) { - return (S(x, 17) ^ S(x, 19) ^ R(x, 10)); -}; - -var core_sha256 = function(m, l) { - var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2); - var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19); - var W = new Array(64); - var a, b, c, d, e, f, g, h, i, j; - var T1, T2; - /* append padding */ - m[l >> 5] |= 0x80 << (24 - l % 32); - m[((l + 64 >> 9) << 4) + 15] = l; - for (var i = 0; i < m.length; i += 16) { - a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7]; - for (var j = 0; j < 64; j++) { - if (j < 16) { - W[j] = m[j + i]; - } else { - W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]); - } - T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]); - T2 = safe_add(Sigma0256(a), Maj(a, b, c)); - h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2); - } - HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]); - HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]); - } - return HASH; -}; - -module.exports = function sha256(buf) { - return helpers.hash(buf, core_sha256, 32, true); -}; - -},{"./helpers":10}],16:[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) { - if (ev.source === window && 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'); -}; - -},{}],17:[function(require,module,exports){ -var Promise = require("../js/debug/bluebird.js"); -Promise.onPossiblyUnhandledRejection();(function (){ - var global = window; - global.adapter = Promise; - global.sinon = require("sinon"); - global.assert = require("assert"); - global.setImmediate = function(fn){ - setTimeout(fn, 0); - }; -})(); - -;window.tests = [{fn: function(){ return require('../test/mocha/2.1.2.js');}, name: '../test/mocha/2.1.2.js'}, -{fn: function(){ return require('../test/mocha/2.1.3.js');}, name: '../test/mocha/2.1.3.js'}, -{fn: function(){ return require('../test/mocha/2.2.1.js');}, name: '../test/mocha/2.2.1.js'}, -{fn: function(){ return require('../test/mocha/2.2.2.js');}, name: '../test/mocha/2.2.2.js'}, -{fn: function(){ return require('../test/mocha/2.2.3.js');}, name: '../test/mocha/2.2.3.js'}, -{fn: function(){ return require('../test/mocha/2.2.4.js');}, name: '../test/mocha/2.2.4.js'}, -{fn: function(){ return require('../test/mocha/2.2.5.js');}, name: '../test/mocha/2.2.5.js'}, -{fn: function(){ return require('../test/mocha/2.2.6.js');}, name: '../test/mocha/2.2.6.js'}, -{fn: function(){ return require('../test/mocha/2.2.7.js');}, name: '../test/mocha/2.2.7.js'}, -{fn: function(){ return require('../test/mocha/2.3.1.js');}, name: '../test/mocha/2.3.1.js'}, -{fn: function(){ return require('../test/mocha/2.3.2.js');}, name: '../test/mocha/2.3.2.js'}, -{fn: function(){ return require('../test/mocha/2.3.3.js');}, name: '../test/mocha/2.3.3.js'}, -{fn: function(){ return require('../test/mocha/2.3.4.js');}, name: '../test/mocha/2.3.4.js'}, -{fn: function(){ return require('../test/mocha/3.2.1.js');}, name: '../test/mocha/3.2.1.js'}, -{fn: function(){ return require('../test/mocha/3.2.2.js');}, name: '../test/mocha/3.2.2.js'}, -{fn: function(){ return require('../test/mocha/3.2.3.js');}, name: '../test/mocha/3.2.3.js'}, -{fn: function(){ return require('../test/mocha/3.2.4.js');}, name: '../test/mocha/3.2.4.js'}, -{fn: function(){ return require('../test/mocha/3.2.5.js');}, name: '../test/mocha/3.2.5.js'}, -{fn: function(){ return require('../test/mocha/3.2.6.js');}, name: '../test/mocha/3.2.6.js'}, -{fn: function(){ return require('../test/mocha/api_exceptions.js');}, name: '../test/mocha/api_exceptions.js'}, -{fn: function(){ return require('../test/mocha/async.js');}, name: '../test/mocha/async.js'}, -{fn: function(){ return require('../test/mocha/bind.js');}, name: '../test/mocha/bind.js'}, -{fn: function(){ return require('../test/mocha/bluebird-multiple-instances.js');}, name: '../test/mocha/bluebird-multiple-instances.js'}, -{fn: function(){ return require('../test/mocha/call.js');}, name: '../test/mocha/call.js'}, -{fn: function(){ return require('../test/mocha/cancel.js');}, name: '../test/mocha/cancel.js'}, -{fn: function(){ return require('../test/mocha/catch_filter.js');}, name: '../test/mocha/catch_filter.js'}, -{fn: function(){ return require('../test/mocha/collections_thenables.js');}, name: '../test/mocha/collections_thenables.js'}, -{fn: function(){ return require('../test/mocha/constructor.js');}, name: '../test/mocha/constructor.js'}, -{fn: function(){ return require('../test/mocha/cycles.js');}, name: '../test/mocha/cycles.js'}, -{fn: function(){ return require('../test/mocha/direct_resolving.js');}, name: '../test/mocha/direct_resolving.js'}, -{fn: function(){ return require('../test/mocha/domain.js');}, name: '../test/mocha/domain.js'}, -{fn: function(){ return require('../test/mocha/each.js');}, name: '../test/mocha/each.js'}, -{fn: function(){ return require('../test/mocha/error.js');}, name: '../test/mocha/error.js'}, -{fn: function(){ return require('../test/mocha/filter.js');}, name: '../test/mocha/filter.js'}, -{fn: function(){ return require('../test/mocha/following.js');}, name: '../test/mocha/following.js'}, -{fn: function(){ return require('../test/mocha/get.js');}, name: '../test/mocha/get.js'}, -{fn: function(){ return require('../test/mocha/github-2xx-76.js');}, name: '../test/mocha/github-2xx-76.js'}, -{fn: function(){ return require('../test/mocha/github-3.6.4.js');}, name: '../test/mocha/github-3.6.4.js'}, -{fn: function(){ return require('../test/mocha/github-3.7.3.js');}, name: '../test/mocha/github-3.7.3.js'}, -{fn: function(){ return require('../test/mocha/github36.js');}, name: '../test/mocha/github36.js'}, -{fn: function(){ return require('../test/mocha/late_buffer_safety.js');}, name: '../test/mocha/late_buffer_safety.js'}, -{fn: function(){ return require('../test/mocha/method.js');}, name: '../test/mocha/method.js'}, -{fn: function(){ return require('../test/mocha/promisify.js');}, name: '../test/mocha/promisify.js'}, -{fn: function(){ return require('../test/mocha/props.js');}, name: '../test/mocha/props.js'}, -{fn: function(){ return require('../test/mocha/q_all.js');}, name: '../test/mocha/q_all.js'}, -{fn: function(){ return require('../test/mocha/q_done.js');}, name: '../test/mocha/q_done.js'}, -{fn: function(){ return require('../test/mocha/q_fin.js');}, name: '../test/mocha/q_fin.js'}, -{fn: function(){ return require('../test/mocha/q_inspect.js');}, name: '../test/mocha/q_inspect.js'}, -{fn: function(){ return require('../test/mocha/q_make_node_resolver.js');}, name: '../test/mocha/q_make_node_resolver.js'}, -{fn: function(){ return require('../test/mocha/q_nodeify.js');}, name: '../test/mocha/q_nodeify.js'}, -{fn: function(){ return require('../test/mocha/q_progress.js');}, name: '../test/mocha/q_progress.js'}, -{fn: function(){ return require('../test/mocha/q_propagation.js');}, name: '../test/mocha/q_propagation.js'}, -{fn: function(){ return require('../test/mocha/q_settle.js');}, name: '../test/mocha/q_settle.js'}, -{fn: function(){ return require('../test/mocha/q_spread.js');}, name: '../test/mocha/q_spread.js'}, -{fn: function(){ return require('../test/mocha/race.js');}, name: '../test/mocha/race.js'}, -{fn: function(){ return require('../test/mocha/reduce.js');}, name: '../test/mocha/reduce.js'}, -{fn: function(){ return require('../test/mocha/reflect.js');}, name: '../test/mocha/reflect.js'}, -{fn: function(){ return require('../test/mocha/resolution.js');}, name: '../test/mocha/resolution.js'}, -{fn: function(){ return require('../test/mocha/reused_promise.js');}, name: '../test/mocha/reused_promise.js'}, -{fn: function(){ return require('../test/mocha/schedule.js');}, name: '../test/mocha/schedule.js'}, -{fn: function(){ return require('../test/mocha/some.js');}, name: '../test/mocha/some.js'}, -{fn: function(){ return require('../test/mocha/tap.js');}, name: '../test/mocha/tap.js'}, -{fn: function(){ return require('../test/mocha/timers.js');}, name: '../test/mocha/timers.js'}, -{fn: function(){ return require('../test/mocha/try.js');}, name: '../test/mocha/try.js'}, -{fn: function(){ return require('../test/mocha/unhandled_rejections.js');}, name: '../test/mocha/unhandled_rejections.js'}, -{fn: function(){ return require('../test/mocha/using.js');}, name: '../test/mocha/using.js'}, -{fn: function(){ return require('../test/mocha/when_all.js');}, name: '../test/mocha/when_all.js'}, -{fn: function(){ return require('../test/mocha/when_any.js');}, name: '../test/mocha/when_any.js'}, -{fn: function(){ return require('../test/mocha/when_defer.js');}, name: '../test/mocha/when_defer.js'}, -{fn: function(){ return require('../test/mocha/when_join.js');}, name: '../test/mocha/when_join.js'}, -{fn: function(){ return require('../test/mocha/when_map.js');}, name: '../test/mocha/when_map.js'}, -{fn: function(){ return require('../test/mocha/when_reduce.js');}, name: '../test/mocha/when_reduce.js'}, -{fn: function(){ return require('../test/mocha/when_settle.js');}, name: '../test/mocha/when_settle.js'}, -{fn: function(){ return require('../test/mocha/when_some.js');}, name: '../test/mocha/when_some.js'}, -{fn: function(){ return require('../test/mocha/when_spread.js');}, name: '../test/mocha/when_spread.js'}]; -},{"../js/debug/bluebird.js":21,"../test/mocha/2.1.2.js":70,"../test/mocha/2.1.3.js":71,"../test/mocha/2.2.1.js":72,"../test/mocha/2.2.2.js":73,"../test/mocha/2.2.3.js":74,"../test/mocha/2.2.4.js":75,"../test/mocha/2.2.5.js":76,"../test/mocha/2.2.6.js":77,"../test/mocha/2.2.7.js":78,"../test/mocha/2.3.1.js":79,"../test/mocha/2.3.2.js":80,"../test/mocha/2.3.3.js":81,"../test/mocha/2.3.4.js":82,"../test/mocha/3.2.1.js":83,"../test/mocha/3.2.2.js":84,"../test/mocha/3.2.3.js":85,"../test/mocha/3.2.4.js":86,"../test/mocha/3.2.5.js":87,"../test/mocha/3.2.6.js":88,"../test/mocha/api_exceptions.js":89,"../test/mocha/async.js":90,"../test/mocha/bind.js":91,"../test/mocha/bluebird-multiple-instances.js":92,"../test/mocha/call.js":93,"../test/mocha/cancel.js":94,"../test/mocha/catch_filter.js":95,"../test/mocha/collections_thenables.js":96,"../test/mocha/constructor.js":97,"../test/mocha/cycles.js":98,"../test/mocha/direct_resolving.js":99,"../test/mocha/domain.js":100,"../test/mocha/each.js":101,"../test/mocha/error.js":102,"../test/mocha/filter.js":103,"../test/mocha/following.js":104,"../test/mocha/get.js":105,"../test/mocha/github-2xx-76.js":106,"../test/mocha/github-3.6.4.js":107,"../test/mocha/github-3.7.3.js":108,"../test/mocha/github36.js":109,"../test/mocha/late_buffer_safety.js":114,"../test/mocha/method.js":115,"../test/mocha/promisify.js":116,"../test/mocha/props.js":117,"../test/mocha/q_all.js":118,"../test/mocha/q_done.js":119,"../test/mocha/q_fin.js":120,"../test/mocha/q_inspect.js":121,"../test/mocha/q_make_node_resolver.js":122,"../test/mocha/q_nodeify.js":123,"../test/mocha/q_progress.js":124,"../test/mocha/q_propagation.js":125,"../test/mocha/q_settle.js":126,"../test/mocha/q_spread.js":127,"../test/mocha/race.js":128,"../test/mocha/reduce.js":129,"../test/mocha/reflect.js":130,"../test/mocha/resolution.js":131,"../test/mocha/reused_promise.js":132,"../test/mocha/schedule.js":133,"../test/mocha/some.js":134,"../test/mocha/tap.js":135,"../test/mocha/timers.js":136,"../test/mocha/try.js":137,"../test/mocha/unhandled_rejections.js":138,"../test/mocha/using.js":139,"../test/mocha/when_all.js":140,"../test/mocha/when_any.js":141,"../test/mocha/when_defer.js":142,"../test/mocha/when_join.js":143,"../test/mocha/when_map.js":144,"../test/mocha/when_reduce.js":145,"../test/mocha/when_settle.js":146,"../test/mocha/when_some.js":147,"../test/mocha/when_spread.js":148,"assert":2,"sinon":55}],18:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise) { -var SomePromiseArray = Promise._SomePromiseArray; -var ASSERT = require("./assert.js"); - -function any(promises) { - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - if (promise.isRejected()) { - return promise; - } - ASSERT((ret instanceof SomePromiseArray), - "ret instanceof SomePromiseArray"); - ret.setHowMany(1); - ret.setUnwrap(); - ret.init(); - return promise; -} - -Promise.any = function (promises) { - return any(promises); -}; - -Promise.prototype.any = function () { - return any(this); -}; - -}; - -},{"./assert.js":19}],19:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = (function(){ -var AssertionError = (function() { - function AssertionError(a) { - this.constructor$(a); - this.message = a; - this.name = "AssertionError"; - } - AssertionError.prototype = new Error(); - AssertionError.prototype.constructor = AssertionError; - AssertionError.prototype.constructor$ = Error; - return AssertionError; -})(); - -function getParams(args) { - var params = []; - for (var i = 0; i < args.length; ++i) params.push("arg" + i); - return params; -} - -function nativeAssert(callName, args, expect) { - try { - var params = getParams(args); - var constructorArgs = params; - constructorArgs.push("return " + - callName + "("+ params.join(",") + ");"); - var fn = Function.apply(null, constructorArgs); - return fn.apply(null, args); - } catch (e) { - if (!(e instanceof SyntaxError)) { - throw e; - } else { - return expect; - } - } -} - -return function assert(boolExpr, message) { - if (boolExpr === true) return; - - if (typeof boolExpr === "string" && - boolExpr.charAt(0) === "%") { - var nativeCallName = boolExpr; - var $_len = arguments.length;var args = new Array($_len - 2); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];} - if (nativeAssert(nativeCallName, args, message) === message) return; - message = (nativeCallName + " !== " + message); - } - - var ret = new AssertionError(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(ret, assert); - } - if (console && console.error) { - console.error(ret.stack + ""); - } - throw ret; - -}; -})(); - -},{}],20:[function(require,module,exports){ -var process=require("__browserify_process");/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var firstLineError = new Error(); -var ASSERT = require("./assert.js"); -var schedule = require("./schedule.js"); -var Queue = require("./queue.js"); -var errorObj = require("./util.js").errorObj; -var tryCatch1 = require("./util.js").tryCatch1; -var _process = typeof process !== "undefined" ? process : undefined; - -function Async() { - this._isTickUsed = false; - this._schedule = schedule; - this._lateBuffer = new Queue(16); - this._functionBuffer = new Queue(65536); - var self = this; - this.consumeFunctionBuffer = function () { - self._consumeFunctionBuffer(); - }; -} - -Async.prototype.haveItemsQueued = function () { - return this._functionBuffer.length() > 0; -}; - -Async.prototype.invokeLater = function (fn, receiver, arg) { - ASSERT(((typeof fn) === "function"), - "typeof fn === \u0022function\u0022"); - ASSERT((arguments.length === 3), - "arguments.length === 3"); - if (_process !== undefined && - _process.domain != null && - !fn.domain) { - fn = _process.domain.bind(fn); - } - this._lateBuffer.push(fn, receiver, arg); - this._queueTick(); -}; - -Async.prototype._withDomain = function(fn) { - ASSERT(((typeof fn) === "function"), - "typeof fn === \u0022function\u0022"); - if (_process !== undefined && - _process.domain != null && - !fn.domain) { - fn = _process.domain.bind(fn); - } - return fn; -}; - -Async.prototype.invokeFirst = function (fn, receiver, arg) { - ASSERT((arguments.length === 3), - "arguments.length === 3"); - fn = this._withDomain(fn); - this._functionBuffer.unshift(fn, receiver, arg); - this._queueTick(); -}; - -Async.prototype.invoke = function (fn, receiver, arg) { - ASSERT((arguments.length === 3), - "arguments.length === 3"); - fn = this._withDomain(fn); - this._functionBuffer.push(fn, receiver, arg); - this._queueTick(); -}; - -Async.prototype._consumeFunctionBuffer = function () { - var functionBuffer = this._functionBuffer; - ASSERT(this._isTickUsed, - "this._isTickUsed"); - while (functionBuffer.length() > 0) { - var fn = functionBuffer.shift(); - var receiver = functionBuffer.shift(); - var arg = functionBuffer.shift(); - fn.call(receiver, arg); - } - this._reset(); - this._consumeLateBuffer(); -}; - -Async.prototype._consumeLateBuffer = function () { - var buffer = this._lateBuffer; - while(buffer.length() > 0) { - var fn = buffer.shift(); - var receiver = buffer.shift(); - var arg = buffer.shift(); - var res = tryCatch1(fn, receiver, arg); - if (res === errorObj) { - this._queueTick(); - if (fn.domain != null) { - fn.domain.emit("error", res.e); - } else { - throw res.e; - } - } - } -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.consumeFunctionBuffer); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = new Async(); -module.exports.firstLineError = firstLineError; - -},{"./assert.js":19,"./queue.js":43,"./schedule.js":46,"./util.js":53,"__browserify_process":16}],21:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict(bluebird) { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -module.exports = require("./promise.js")(); -module.exports.noConflict = noConflict; - -},{"./promise.js":38}],22:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = require("./util.js"); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -function makeMethodCaller (methodName) { - return new Function("obj", " \n\ - 'use strict' \n\ - var len = this.length; \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: return obj.methodName.apply(obj, this); \n\ - } \n\ - ".replace(/methodName/g, methodName)); -} - -function makeGetter (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); -} - -function getCompiled(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; -} - -function getMethodCaller(name) { - return getCompiled(name, makeMethodCaller, callerCache); -} - -function getGetter(name) { - return getCompiled(name, makeGetter, getterCache); -} - -function caller(obj) { - return obj[this.pop()].apply(obj, this); -} -Promise.prototype.call = function (methodName) { - var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then( - maybeCaller, undefined, undefined, args, undefined); - } - } - args.push(methodName); - return this._then(caller, undefined, undefined, args, undefined); -}; - -function namedGetter(obj) { - return obj[this]; -} -function indexedGetter(obj) { - return obj[this]; -} -Promise.prototype.get = function (propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, undefined, undefined, propertyName, undefined); -}; -}; - -},{"./util.js":53}],23:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var errors = require("./errors.js"); -var canAttachTrace = errors.canAttachTrace; -var async = require("./async.js"); -var ASSERT = require("./assert.js"); -var CancellationError = errors.CancellationError; - -Promise.prototype._cancel = function (reason) { - if (!this.isCancellable()) return this; - var parent; - var promiseToReject = this; - while ((parent = promiseToReject._cancellationParent) !== undefined && - parent.isCancellable()) { - promiseToReject = parent; - } - ASSERT(promiseToReject.isCancellable(), - "promiseToReject.isCancellable()"); - this._unsetCancellable(); - promiseToReject._attachExtraTrace(reason); - promiseToReject._rejectUnchecked(reason); -}; - -Promise.prototype.cancel = function (reason) { - if (!this.isCancellable()) return this; - reason = reason !== undefined - ? (canAttachTrace(reason) ? reason : new Error(reason + "")) - : new CancellationError(); - async.invokeLater(this._cancel, this, reason); - return this; -}; - -Promise.prototype.cancellable = function () { - if (this._cancellable()) return this; - this._setCancellable(); - this._cancellationParent = undefined; - return this; -}; - -Promise.prototype.uncancellable = function () { - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 2 | 4); - ret._follow(this); - ret._unsetCancellable(); - return ret; -}; - -Promise.prototype.fork = function (didFulfill, didReject, didProgress) { - var ret = this._then(didFulfill, didReject, didProgress, - undefined, undefined); - - ret._setCancellable(); - ret._cancellationParent = undefined; - return ret; -}; -}; - -},{"./assert.js":19,"./async.js":20,"./errors.js":28}],24:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function() { -var ASSERT = require("./assert.js"); -var inherits = require("./util.js").inherits; -var defineProperty = require("./es5.js").defineProperty; -var rtraceline = null; -var formatStack = null; - -function CapturedTrace(parent) { - ASSERT(((parent === undefined) || (parent instanceof CapturedTrace)), - "parent === undefined || parent instanceof CapturedTrace"); - this._parent = parent; - captureStackTrace(this, CapturedTrace); - -} -inherits(CapturedTrace, Error); - -CapturedTrace.prototype.parent = function() { - return this._parent; -}; - -CapturedTrace.prototype.setParent = function(parent) { - if (parent === this) return; - ASSERT((parent instanceof CapturedTrace), - "parent instanceof CapturedTrace"); - this._parent = parent; -}; - -CapturedTrace.prototype.hasParent = function() { - return this._parent !== undefined; -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - var trace = this; - var stack = error.stack; - stack = typeof stack === "string" ? stack.split("\n") : []; - this.protectErrorMessageNewlines(stack); - var headerLineCount = 1; - var combinedTraces = 1; - - do { - stack = trace.combine(stack); - combinedTraces++; - } while ((trace = trace.parent()) != null); - - var stackTraceLimit = Error.stackTraceLimit || 10; - var max = (stackTraceLimit + headerLineCount) * combinedTraces; - var len = stack.length; - if (len > max) { - stack.length = max; - } - - if (len > 0) - stack[0] = stack[0].split("\u0002\u0000\u0001").join("\n"); - - if (stack.length <= headerLineCount) { - error.stack = "(No stack trace)"; - } else { - error.stack = stack.join("\n"); - } -}; - -CapturedTrace.prototype.combine = function(current) { - var prev = this.stack.split("\n"); - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - for (var i = prev.length - 1; i >= 0; --i) { - if (prev[i] === currentLastLine) { - commonRootMeetPoint = i; - break; - } - } - - for (var i = commonRootMeetPoint; i >= 0; --i) { - var line = prev[i]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - - current.push("From previous event:"); - var lines = current.concat(prev); - - var ret = []; - - for (var i = 0, len = lines.length; i < len; ++i) { - if (((rtraceline.test(lines[i]) && shouldIgnore(lines[i])) || - (i > 0 && !rtraceline.test(lines[i])) && - lines[i] !== "From previous event:") - ) { - continue; - } - ret.push(lines[i]); - } - return ret; -}; - -CapturedTrace.prototype.protectErrorMessageNewlines = function(stack) { - for (var i = 0; i < stack.length; ++i) { - if (rtraceline.test(stack[i])) { - break; - } - } - - if (i <= 1) return; - - var errorMessageLines = []; - for (var j = 0; j < i; ++j) { - errorMessageLines.push(stack.shift()); - } - stack.unshift(errorMessageLines.join("\u0002\u0000\u0001")); -}; - -CapturedTrace.formatAndLogError = function(error, title) { - if (typeof console === "object") { - var message; - if (typeof error === "object" || typeof error === "function") { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof console.warn === "function" || - typeof console.warn === "object") { - console.warn(message); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -}; - -CapturedTrace.unhandledRejection = function (reason) { - CapturedTrace.formatAndLogError( - reason, "^--- With additional stack trace: "); -}; - -CapturedTrace.possiblyUnhandledRejection = function (reason) { - CapturedTrace.formatAndLogError( - reason, "Possibly unhandled "); -}; - -CapturedTrace.isSupported = function () { - return typeof captureStackTrace === "function"; -}; - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj.toString(); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } -} -CapturedTrace.setBounds = function(firstLineError, lastLineError) { - if (!CapturedTrace.isSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -}; - -var captureStackTrace = (function stackDetection() { - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - rtraceline = /^\s*at\s*/; - formatStack = function(stack, error) { - ASSERT((error !== null), - "error !== null"); - - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.name + ". " + error.message; - } - return formatNonError(error); - - - }; - var captureStackTrace = Error.captureStackTrace; - var bluebirdRegexp = /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo)/; - shouldIgnore = function(line) { - return bluebirdRegexp.test(line); - }; - return function(receiver, ignoreUntil) { - captureStackTrace(receiver, ignoreUntil); - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - typeof "".startsWith === "function" && - (err.stack.startsWith("stackDetection@")) && - stackDetection.name === "stackDetection") { - - defineProperty(Error, "stackTraceLimit", { - writable: true, - enumerable: false, - configurable: false, - value: 25 - }); - rtraceline = /@/; - var rline = /[@\n]/; - - formatStack = function(stack, error) { - if (typeof stack === "string") { - return (error.name + ". " + error.message + "\n" + stack); - } - - if (error.name !== undefined && - error.message !== undefined) { - return error.name + ". " + error.message; - } - return formatNonError(error); - }; - - return function captureStackTrace(o) { - var stack = new Error().stack; - var split = stack.split(rline); - var len = split.length; - var ret = ""; - for (var i = 0; i < len; i += 2) { - ret += split[i]; - ret += "@"; - ret += split[i + 1]; - ret += "\n"; - } - o.stack = ret; - }; - } else { - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.name + ". " + error.message; - } - return formatNonError(error); - }; - - return null; - } -})(); - -return CapturedTrace; -}; - -},{"./assert.js":19,"./es5.js":30,"./util.js":53}],25:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = require("./util.js"); -var errors = require("./errors.js"); -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; -var keys = require("./es5.js").keys; -var TypeError = errors.TypeError; - -function CatchFilter(instances, callback, promise) { - this._instances = instances; - this._callback = callback; - this._promise = promise; -} - -function safePredicate(predicate, e) { - var safeObject = {}; - var retfilter = tryCatch1(predicate, safeObject, e); - - if (retfilter === errorObj) return retfilter; - - var safeKeys = keys(safeObject); - if (safeKeys.length) { - errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); - return errorObj; - } - return retfilter; -} - -CatchFilter.prototype.doFilter = function (e) { - var cb = this._callback; - var promise = this._promise; - var boundTo = promise._boundTo; - for (var i = 0, len = this._instances.length; i < len; ++i) { - var item = this._instances[i]; - var itemIsErrorType = item === Error || - (item != null && item.prototype instanceof Error); - - if (itemIsErrorType && e instanceof item) { - var ret = tryCatch1(cb, boundTo, e); - if (ret === errorObj) { - NEXT_FILTER.e = ret.e; - return NEXT_FILTER; - } - return ret; - } else if (typeof item === "function" && !itemIsErrorType) { - var shouldHandle = safePredicate(item, e); - if (shouldHandle === errorObj) { - var trace = errors.canAttachTrace(errorObj.e) - ? errorObj.e - : new Error(errorObj.e + ""); - this._promise._attachExtraTrace(trace); - e = errorObj.e; - break; - } else if (shouldHandle) { - var ret = tryCatch1(cb, boundTo, e); - if (ret === errorObj) { - NEXT_FILTER.e = ret.e; - return NEXT_FILTER; - } - return ret; - } - } - } - NEXT_FILTER.e = e; - return NEXT_FILTER; -}; - -return CatchFilter; -}; - -},{"./errors.js":28,"./es5.js":30,"./util.js":53}],26:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var util = require("./util.js"); -var ASSERT = require("./assert.js"); -var isPrimitive = util.isPrimitive; -var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; - -module.exports = function(Promise) { -var returner = function () { - return this; -}; -var thrower = function () { - throw this; -}; - -var wrapper = function (value, action) { - if (action === 1) { - return function () { - throw value; - }; - } else if (action === 2) { - return function () { - return value; - }; - } - ASSERT(false, - "false"); -}; - - -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (wrapsPrimitiveReceiver && isPrimitive(value)) { - return this._then( - wrapper(value, 2), - undefined, - undefined, - undefined, - undefined - ); - } - return this._then(returner, undefined, undefined, value, undefined); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - if (wrapsPrimitiveReceiver && isPrimitive(reason)) { - return this._then( - wrapper(reason, 1), - undefined, - undefined, - undefined, - undefined - ); - } - return this._then(thrower, undefined, undefined, reason, undefined); -}; -}; - -},{"./assert.js":19,"./util.js":53}],27:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; - -Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, null, INTERNAL); -}; - -Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, null, INTERNAL); -}; -}; - -},{}],28:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var Objectfreeze = require("./es5.js").freeze; -var propertyIsWritable = require("./es5.js").propertyIsWritable; -var util = require("./util.js"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} -} - -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof OperationalError) || - e["isOperational"] === true); -} - -function isError(obj) { - return obj instanceof Error; -} - -function canAttachTrace(obj) { - return isError(obj) && propertyIsWritable(obj, "stack"); -} - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -AggregateError.prototype.length = 0; -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var key = "__BluebirdErrorTypes__"; -var errorTypes = Error[key]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - notEnumerableProp(Error, key, errorTypes); -} - -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - canAttachTrace: canAttachTrace -}; - -},{"./es5.js":30,"./util.js":53}],29:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise) { -var TypeError = require('./errors.js').TypeError; - -function apiRejection(msg) { - var error = new TypeError(msg); - var ret = Promise.rejected(error); - var parent = ret._peekContext(); - if (parent != null) { - parent.attachExtraTrace(error); - } - return ret; -} - -return apiRejection; -}; - -},{"./errors.js":28}],30:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * 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 isES5 = (function(){ - "use strict"; - return this === undefined; -})(); - -if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - keys: Object.keys, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5, - propertyIsWritable: function(obj, prop) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!(!descriptor || descriptor.writable || descriptor.set); - } - }; -} else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; - - var ObjectKeys = function (o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - } - - var ObjectDefineProperty = function (o, key, desc) { - o[key] = desc.value; - return o; - } - - var ObjectFreeze = function (obj) { - return obj; - } - - var ObjectGetPrototypeOf = function (obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - } - - var ArrayIsArray = function (obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - } - - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - defineProperty: ObjectDefineProperty, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5, - propertyIsWritable: function() { - return true; - } - }; -} - -},{}],31:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseMap = Promise.map; - -Promise.prototype.filter = function (fn, options) { - return PromiseMap(this, fn, options, INTERNAL); -}; - -Promise.filter = function (promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); -}; -}; - -},{}],32:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { -var util = require("./util.js"); -var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; -var isPrimitive = util.isPrimitive; -var thrower = util.thrower; - -function returnThis() { - return this; -} -function throwThis() { - throw this; -} -function return$(r) { - return function() { - return r; - }; -} -function throw$(r) { - return function() { - throw r; - }; -} -function promisedFinally(ret, reasonOrValue, isFulfilled) { - var then; - if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { - then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); - } else { - then = isFulfilled ? returnThis : throwThis; - } - return ret._then(then, thrower, undefined, reasonOrValue, undefined); -} - -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - var ret = promise._isBound() - ? handler.call(promise._boundTo) - : handler(); - - if (ret !== undefined) { - var maybePromise = tryConvertToPromise(ret, undefined); - if (maybePromise instanceof Promise) { - return promisedFinally(maybePromise, reasonOrValue, - promise.isFulfilled()); - } - } - - if (promise.isRejected()) { - NEXT_FILTER.e = reasonOrValue; - return NEXT_FILTER; - } else { - return reasonOrValue; - } -} - -function tapHandler(value) { - var promise = this.promise; - var handler = this.handler; - - var ret = promise._isBound() - ? handler.call(promise._boundTo, value) - : handler(value); - - if (ret !== undefined) { - var maybePromise = tryConvertToPromise(ret, undefined); - if (maybePromise instanceof Promise) { - return promisedFinally(maybePromise, value, true); - } - } - return value; -} - -Promise.prototype._passThroughHandler = function (handler, isFinally) { - if (typeof handler !== "function") return this.then(); - - var promiseAndHandler = { - promise: this, - handler: handler - }; - - return this._then( - isFinally ? finallyHandler : tapHandler, - isFinally ? finallyHandler : undefined, undefined, - promiseAndHandler, undefined); -}; - -Promise.prototype.lastly = -Promise.prototype["finally"] = function (handler) { - return this._passThroughHandler(handler, true); -}; - -Promise.prototype.tap = function (handler) { - return this._passThroughHandler(handler, false); -}; -}; - -},{"./util.js":53}],33:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise) { -var errors = require("./errors.js"); -var TypeError = errors.TypeError; -var ASSERT = require("./assert.js"); -var deprecated = require("./util.js").deprecated; -var util = require("./util.js"); -var errorObj = util.errorObj; -var tryCatch1 = util.tryCatch1; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - var _errorObj = errorObj; - var _Promise = Promise; - var len = yieldHandlers.length; - for (var i = 0; i < len; ++i) { - var result = tryCatch1(yieldHandlers[i], undefined, value); - if (result === _errorObj) { - return _Promise.reject(_errorObj.e); - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof _Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler) { - var promise = this._promise = new Promise(INTERNAL); - promise._setTrace(undefined); - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = undefined; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; -} - -PromiseSpawn.prototype.promise = function () { - return this._promise; -}; - -PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._next(undefined); -}; - -PromiseSpawn.prototype._continue = function (result) { - if (result === errorObj) { - this._generator = undefined; - var trace = errors.canAttachTrace(result.e) - ? result.e : new Error(result.e + ""); - this._promise._attachExtraTrace(trace); - this._promise._reject(result.e, trace); - return; - } - - var value = result.value; - if (result.done === true) { - this._generator = undefined; - if (!this._promise._tryFollow(value)) { - this._promise._fulfill(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - ASSERT(((maybePromise === null) || (maybePromise instanceof Promise)), - "maybePromise === null || maybePromise instanceof Promise"); - if (maybePromise === null) { - this._throw(new TypeError("A value was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a")); - return; - } - } - maybePromise._then( - this._next, - this._throw, - undefined, - this, - null - ); - } -}; - -PromiseSpawn.prototype._throw = function (reason) { - if (errors.canAttachTrace(reason)) - this._promise._attachExtraTrace(reason); - this._continue( - tryCatch1(this._generator["throw"], this._generator, reason) - ); -}; - -PromiseSpawn.prototype._next = function (value) { - this._continue( - tryCatch1(this._generator.next, this._generator, value) - ); -}; - -Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler); - spawn._generator = generator; - spawn._next(undefined); - return spawn.promise(); - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - yieldHandlers.push(fn); -}; - -Promise.spawn = function (generatorFunction) { - deprecated("Promise.spawn is deprecated. Use Promise.coroutine instead."); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; - -},{"./assert.js":19,"./errors.js":28,"./util.js":53}],34:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { -var util = require("./util.js"); -var canEvaluate = util.canEvaluate; -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; - - -if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; - - var caller = function(count) { - var values = []; - for (var i = 1; i <= count; ++i) values.push("holder.p" + i); - return new Function("holder", " \n\ - 'use strict'; \n\ - var callback = holder.fn; \n\ - return callback(values); \n\ - ".replace(/values/g, values.join(", "))); - }; - var thenCallbacks = []; - var callers = [undefined]; - for (var i = 1; i <= 5; ++i) { - thenCallbacks.push(thenCallback(i)); - callers.push(caller(i)); - } - - var Holder = function(total, fn) { - this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; - this.fn = fn; - this.total = total; - this.now = 0; - }; - - Holder.prototype.callers = callers; - Holder.prototype.checkFulfillment = function(promise) { - var now = this.now; - now++; - var total = this.total; - if (now >= total) { - var handler = this.callers[total]; - var ret = tryCatch1(handler, undefined, this); - if (ret === errorObj) { - promise._rejectUnchecked(ret.e); - } else if (!promise._tryFollow(ret)) { - promise._fulfillUnchecked(ret); - } - } else { - this.now = now; - } - }; -} - -function reject(reason) { - this._reject(reason); -} - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (last < 6 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._setTrace(undefined); - var holder = new Holder(last, fn); - var callbacks = thenCallbacks; - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], undefined); - if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - } else if (maybePromise.isFulfilled()) { - callbacks[i].call(ret, - maybePromise._settledValue, holder); - } else { - ret._reject(maybePromise._settledValue); - maybePromise._unsetRejectionIsUnhandled(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - return ret; - } - } - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; - -},{"./util.js":53}],35:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL) { -var ASSERT = require("./assert.js"); -var util = require("./util.js"); -var tryCatch3 = util.tryCatch3; -var errorObj = util.errorObj; -var PENDING = {}; -var EMPTY_ARRAY = []; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._callback = fn; - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = limit >= 1 ? [] : EMPTY_ARRAY; - this._init$(undefined, -2); -} -util.inherits(MappingPromiseArray, PromiseArray); - -MappingPromiseArray.prototype._init = function () {}; - -MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; - if (values[index] === PENDING) { - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return; - } - if (preservedValues !== null) preservedValues[index] = value; - - var callback = this._callback; - var receiver = this._promise._boundTo; - var ret = tryCatch3(callback, receiver, value, index, length); - if (ret === errorObj) return this._reject(ret.e); - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { - if (limit >= 1) this._inFlight++; - values[index] = PENDING; - return maybePromise._proxyPromiseArray(this, index); - } else if (maybePromise.isFulfilled()) { - ret = maybePromise._settledValue; - } else { - maybePromise._unsetRejectionIsUnhandled(); - return this._reject(maybePromise._settledValue); - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - - } -}; - -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; - -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - var limit = typeof options === "object" && options !== null - ? options.concurrency - : 0; - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter); -} - -Promise.prototype.map = function (fn, options) { - if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - - return map(this, fn, options, null).promise(); -}; - -Promise.map = function (promises, fn, options, _filter) { - if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - return map(promises, fn, options, _filter).promise(); -}; - - -}; - -},{"./assert.js":19,"./util.js":53}],36:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise) { -var util = require("./util.js"); -var async = require("./async.js"); -var ASSERT = require("./assert.js"); -var tryCatch2 = util.tryCatch2; -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; - -function thrower(r) { - throw r; -} - -function spreadAdapter(val, receiver) { - if (!util.isArray(val)) return successAdapter(val, receiver); - var ret = util.tryCatchApply(this, [null].concat(val), receiver); - if (ret === errorObj) { - async.invokeLater(thrower, undefined, ret.e); - } -} - -function successAdapter(val, receiver) { - var nodeback = this; - ASSERT(((typeof nodeback) == "function"), - "typeof nodeback == \u0022function\u0022"); - var ret = val === undefined - ? tryCatch1(nodeback, receiver, null) - : tryCatch2(nodeback, receiver, null, val); - if (ret === errorObj) { - async.invokeLater(thrower, undefined, ret.e); - } -} -function errorAdapter(reason, receiver) { - var nodeback = this; - ASSERT(((typeof nodeback) == "function"), - "typeof nodeback == \u0022function\u0022"); - var ret = tryCatch1(nodeback, receiver, reason); - if (ret === errorObj) { - async.invokeLater(thrower, undefined, ret.e); - } -} - -Promise.prototype.nodeify = function (nodeback, options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - nodeback, - this._boundTo - ); - } - return this; -}; -}; - -},{"./assert.js":19,"./async.js":20,"./util.js":53}],37:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray) { -var ASSERT = require("./assert.js"); -var util = require("./util.js"); -var async = require("./async.js"); -var errors = require("./errors.js"); -var tryCatch1 = util.tryCatch1; -var errorObj = util.errorObj; - -Promise.prototype.progressed = function (handler) { - return this._then(undefined, undefined, handler, undefined, undefined); -}; - -Promise.prototype._progress = function (progressValue) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._progressUnchecked(progressValue); - -}; - -Promise.prototype._progressHandlerAt = function (index) { - return index === 0 - ? this._progressHandler0 - : this[(index << 2) + index - 5 + 2]; -}; - -Promise.prototype._doProgressWith = function (progression) { - var progressValue = progression.value; - var handler = progression.handler; - var promise = progression.promise; - var receiver = progression.receiver; - - ASSERT(((typeof handler) === "function"), - "typeof handler === \u0022function\u0022"); - ASSERT((promise instanceof Promise), - "promise instanceof Promise"); - var ret = tryCatch1(handler, receiver, progressValue); - if (ret === errorObj) { - if (ret.e != null && - ret.e.name !== "StopProgressPropagation") { - var trace = errors.canAttachTrace(ret.e) - ? ret.e : new Error(ret.e + ""); - promise._attachExtraTrace(trace); - promise._progress(ret.e); - } - } else if (ret instanceof Promise) { - ret._then(promise._progress, null, null, promise, undefined); - } else { - promise._progress(ret); - } -}; - - -Promise.prototype._progressUnchecked = function (progressValue) { - if (!this.isPending()) return; - var len = this._length(); - var progress = this._progress; - for (var i = 0; i < len; i++) { - var handler = this._progressHandlerAt(i); - var promise = this._promiseAt(i); - if (!(promise instanceof Promise)) { - var receiver = this._receiverAt(i); - if (typeof handler === "function") { - handler.call(receiver, progressValue, promise); - } else if (receiver instanceof Promise && receiver._isProxied()) { - receiver._progressUnchecked(progressValue); - } else if (receiver instanceof PromiseArray && - !receiver._isResolved()) { - receiver._promiseProgressed(progressValue, promise); - } - continue; - } - - if (typeof handler === "function") { - async.invoke(this._doProgressWith, this, { - handler: handler, - promise: promise, - receiver: this._receiverAt(i), - value: progressValue - }); - } else { - async.invoke(progress, promise, progressValue); - } - } -}; -}; - -},{"./assert.js":19,"./async.js":20,"./errors.js":28,"./util.js":53}],38:[function(require,module,exports){ -var process=require("__browserify_process");/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); -}; -var reflect = function() { - return new Promise.PromiseInspection(this); -}; -var returnFirstElement = function(elements) { return elements[0]; }; -var ASSERT = require("./assert.js"); -var util = require("./util.js"); -var async = require("./async.js"); -var errors = require("./errors.js"); -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {e: null}; -var tryConvertToPromise = require("./thenables.js")(Promise, INTERNAL); -var PromiseArray = - require("./promise_array.js")(Promise, INTERNAL, tryConvertToPromise); -var CapturedTrace = require("./captured_trace.js")(); -var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); -var PromiseResolver = require("./promise_resolver.js"); -var isArray = util.isArray; -var errorObj = util.errorObj; -var tryCatch1 = util.tryCatch1; -var tryCatch2 = util.tryCatch2; -var tryCatchApply = util.tryCatchApply; -var RangeError = errors.RangeError; -var TypeError = errors.TypeError; -var CancellationError = errors.CancellationError; -var TimeoutError = errors.TimeoutError; -var OperationalError = errors.OperationalError; -var originatesFromRejection = errors.originatesFromRejection; -var markAsOriginatingFromRejection = errors.markAsOriginatingFromRejection; -var canAttachTrace = errors.canAttachTrace; -var apiRejection = require("./errors_api_rejection")(Promise); -var unhandledRejectionHandled; -var debugging = true || !!( - typeof process !== "undefined" && - typeof process.execPath === "string" && - typeof process.env === "object" && - (process.env["BLUEBIRD_DEBUG"] || - process.env["NODE_ENV"] === "development") -); - -function Promise(resolver) { - if (typeof resolver !== "function") { - throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); - } - if (this.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._progressHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - this._settledValue = undefined; - this._boundTo = undefined; - if (resolver !== INTERNAL) this._resolveFromResolver(resolver); -} - -Promise.prototype.bind = function (thisArg) { - var maybePromise = tryConvertToPromise(thisArg, this); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 2 | 1); - if (maybePromise instanceof Promise) { - var binder = maybePromise.then(function(thisArg) { - ret._setBoundTo(thisArg); - }); - var p = Promise.all([this, binder]).then(returnFirstElement); - ret._follow(p); - } else { - ret._follow(this); - ret._setBoundTo(thisArg); - } - - return ret; -}; - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (typeof item === "function") { - catchInstances[j++] = item; - } else { - var error = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); - this._attachExtraTrace(error); - return Promise.reject(error); - } - } - catchInstances.length = j; - fn = arguments[i]; - - this._resetTrace(); - var catchFilter = new CatchFilter(catchInstances, fn, this); - return this._then(undefined, catchFilter.doFilter, undefined, - catchFilter, undefined); - } - return this._then(undefined, fn, undefined, undefined, undefined); -}; - -Promise.prototype.reflect = function () { - return this._then(reflect, reflect, undefined, this, undefined); -}; - -Promise.prototype.then = function (didFulfill, didReject, didProgress) { - return this._then(didFulfill, didReject, didProgress, - undefined, undefined); -}; - - -Promise.prototype.done = function (didFulfill, didReject, didProgress) { - var promise = this._then(didFulfill, didReject, didProgress, - undefined, undefined); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function (didFulfill, didReject) { - return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); -}; - -Promise.prototype.isCancellable = function () { - return !this.isResolved() && - this._cancellable(); -}; - -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this._settledValue; - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this._settledValue; - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - return new PromiseArray(this).promise(); -}; - -Promise.prototype.error = function (fn) { - return this.caught(originatesFromRejection, fn); -}; - -Promise.is = function (val) { - return val instanceof Promise; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - } - return function () { - var value; - switch(arguments.length) { - case 0: value = tryCatch1(fn, this, undefined); break; - case 1: value = tryCatch1(fn, this, arguments[0]); break; - case 2: value = tryCatch2(fn, this, arguments[0], arguments[1]); break; - default: - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} - value = tryCatchApply(fn, args, this); break; - } - var ret = new Promise(INTERNAL); - ret._setTrace(undefined); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function (fn, args, ctx) { - if (typeof fn !== "function") { - return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - } - var value = isArray(args) - ? tryCatchApply(fn, args, ctx) - : tryCatch1(fn, ctx, args); - - var ret = new Promise(INTERNAL); - ret._setTrace(undefined); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.defer = Promise.pending = function () { - var promise = new Promise(INTERNAL); - promise._setTrace(undefined); - return new PromiseResolver(promise); -}; - -Promise.bind = function (thisArg) { - var maybePromise = tryConvertToPromise(thisArg, undefined); - var ret = new Promise(INTERNAL); - ret._setTrace(undefined); - - if (maybePromise instanceof Promise) { - var p = maybePromise.then(function(thisArg) { - ret._setBoundTo(thisArg); - }); - ret._follow(p); - } else { - ret._setBoundTo(thisArg); - ret._setFulfilled(); - } - return ret; -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj, undefined); - if (!(ret instanceof Promise)) { - var val = ret; - ret = new Promise(INTERNAL); - ret._setTrace(undefined); - ret._setFulfilled(); - ret._settledValue = val; - ret._cleanValues(); - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._setTrace(undefined); - markAsOriginatingFromRejection(reason); - ret._setRejected(); - ret._settledValue = reason; - ret._cleanValues(); - if (!canAttachTrace(reason)) { - var trace = new Error(reason + ""); - ret._setCarriedStackTrace(trace); - } - ret._ensurePossibleRejectionHandled(); - return ret; -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - CapturedTrace.possiblyUnhandledRejection = typeof fn === "function" - ? fn : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; -}; - -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && - debugging === false - ) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); - } - debugging = CapturedTrace.isSupported(); -}; - -Promise.hasLongStackTraces = function () { - return debugging && CapturedTrace.isSupported(); -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - async._schedule = fn; -}; - -Promise.prototype._then = function ( - didFulfill, - didReject, - didProgress, - receiver, - internalData -) { - ASSERT((arguments.length === 5), - "arguments.length === 5"); - var haveInternalData = internalData !== undefined; - var ret = haveInternalData ? internalData : new Promise(INTERNAL); - - if (!haveInternalData) { - ret._propagateFrom(this, 7); - } - - var callbackIndex = - this._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); - - if (this.isResolved() && !this._isSettlePromisesQueued()) { - async.invoke(this._settlePromiseAtPostResolution, this, callbackIndex); - } - - return ret; -}; - -Promise.prototype._settlePromiseAtPostResolution = function (index) { - ASSERT(((typeof index) === "number"), - "typeof index === \u0022number\u0022"); - ASSERT((index >= 0), - "index >= 0"); - ASSERT((this.isFulfilled() || this.isRejected()), - "this.isFulfilled() || this.isRejected()"); - ASSERT((this._promiseAt(index) !== undefined), - "this._promiseAt(index) !== undefined"); - if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); - this._setLength(0); - this._settlePromiseAt(index); -}; - -Promise.prototype._length = function () { - ASSERT((arguments.length === 0), - "arguments.length === 0"); - return this._bitField & 262143; -}; - -Promise.prototype._isFollowingOrFulfilledOrRejected = function () { - return (this._bitField & 939524096) > 0; -}; - -Promise.prototype._isFollowing = function () { - return (this._bitField & 536870912) === 536870912; -}; - -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -262144) | - (len & 262143); -}; - -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 134217728; -}; - -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 536870912; -}; - -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 33554432; -}; - -Promise.prototype._isFinal = function () { - return (this._bitField & 33554432) > 0; -}; - -Promise.prototype._cancellable = function () { - return (this._bitField & 67108864) > 0; -}; - -Promise.prototype._setCancellable = function () { - this._bitField = this._bitField | 67108864; -}; - -Promise.prototype._unsetCancellable = function () { - this._bitField = this._bitField & (~67108864); -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - ASSERT(this.isRejected(), - "this.isRejected()"); - this._bitField = this._bitField | 2097152; -}; - -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~2097152); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 2097152) > 0; -}; - -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 524288; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~524288); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 524288) > 0; -}; - -Promise.prototype._setCarriedStackTrace = function (capturedTrace) { - ASSERT(this.isRejected(), - "this.isRejected()"); - this._bitField = this._bitField | 1048576; - this._fulfillmentHandler0 = capturedTrace; -}; - -Promise.prototype._unsetCarriedStackTrace = function () { - ASSERT(this.isRejected(), - "this.isRejected()"); - this._bitField = this._bitField & (~1048576); - this._fulfillmentHandler0 = undefined; -}; - -Promise.prototype._isCarryingStackTrace = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._getCarriedStackTrace = function () { - ASSERT(this.isRejected(), - "this.isRejected()"); - return this._isCarryingStackTrace() - ? this._fulfillmentHandler0 - : undefined; -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 - ? this._receiver0 - : this[(index << 2) + index - 5 + 4]; - if (this._isBound() && ret === undefined) { - return this._boundTo; - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return index === 0 - ? this._promise0 - : this[(index << 2) + index - 5 + 3]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - ASSERT((! this._isCarryingStackTrace()), - "!this._isCarryingStackTrace()"); - return index === 0 - ? this._fulfillmentHandler0 - : this[(index << 2) + index - 5 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return index === 0 - ? this._rejectionHandler0 - : this[(index << 2) + index - 5 + 1]; -}; - -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - progress, - promise, - receiver -) { - var index = this._length(); - - if (index >= 262143 - 5) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - ASSERT((this._promise0 === undefined), - "this._promise0 === undefined"); - ASSERT((this._receiver0 === undefined), - "this._receiver0 === undefined"); - ASSERT(((this._fulfillmentHandler0 === undefined) || this._isCarryingStackTrace()), - "this._fulfillmentHandler0 === undefined ||\u000a this._isCarryingStackTrace()"); - ASSERT((this._rejectionHandler0 === undefined), - "this._rejectionHandler0 === undefined"); - ASSERT((this._progressHandler0 === undefined), - "this._progressHandler0 === undefined"); - - this._promise0 = promise; - if (receiver !== undefined) this._receiver0 = receiver; - if (typeof fulfill === "function" && !this._isCarryingStackTrace()) - this._fulfillmentHandler0 = fulfill; - if (typeof reject === "function") this._rejectionHandler0 = reject; - if (typeof progress === "function") this._progressHandler0 = progress; - } else { - ASSERT((this[(base + 3)] === undefined), - "this[base + CALLBACK_PROMISE_OFFSET] === undefined"); - ASSERT((this[(base + 4)] === undefined), - "this[base + CALLBACK_RECEIVER_OFFSET] === undefined"); - ASSERT((this[(base + 0)] === undefined), - "this[base + CALLBACK_FULFILL_OFFSET] === undefined"); - ASSERT((this[(base + 1)] === undefined), - "this[base + CALLBACK_REJECT_OFFSET] === undefined"); - ASSERT((this[(base + 2)] === undefined), - "this[base + CALLBACK_PROGRESS_OFFSET] === undefined"); - var base = index * 5 - 5; - this[base + 3] = promise; - this[base + 4] = receiver; - if (typeof fulfill === "function") - this[base + 0] = fulfill; - if (typeof reject === "function") - this[base + 1] = reject; - if (typeof progress === "function") - this[base + 2] = progress; - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { - var index = this._length(); - - if (index >= 262143 - 5) { - index = 0; - this._setLength(0); - } - if (index === 0) { - this._promise0 = promiseSlotValue; - this._receiver0 = receiver; - } else { - var base = index * 5 - 5; - this[base + 3] = promiseSlotValue; - this[base + 4] = receiver; - } - this._setLength(index + 1); -}; - -Promise.prototype._proxyPromiseArray = function (promiseArray, index) { - ASSERT((! this.isResolved()), - "!this.isResolved()"); - ASSERT((arguments.length === 2), - "arguments.length === 2"); - ASSERT(((typeof index) === "number"), - "typeof index === \u0022number\u0022"); - ASSERT(((index | 0) === index), - "(index | 0) === index"); - this._setProxyHandlers(promiseArray, index); -}; - -Promise.prototype._proxyPromise = function (promise) { - ASSERT((! promise._isProxied()), - "!promise._isProxied()"); - ASSERT((! this.isResolved()), - "!this.isResolved()"); - ASSERT((arguments.length === 1), - "arguments.length === 1"); - promise._setProxied(); - this._setProxyHandlers(promise, -15); -}; - -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 8388608; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~8388608); - } -}; - -Promise.prototype._isBound = function () { - return (this._bitField & 8388608) === 8388608; -}; - -Promise.prototype._resolveFromResolver = function (resolver) { - ASSERT(((typeof resolver) === "function"), - "typeof resolver === \u0022function\u0022"); - var promise = this; - this._setTrace(undefined); - - this._pushContext(); - var r = tryCatch2(resolver, undefined, function(val) { - if (promise._tryFollow(val)) { - return; - } - promise._fulfill(val); - }, function (val) { - var trace = canAttachTrace(val) ? val : new Error(val + ""); - promise._attachExtraTrace(trace); - markAsOriginatingFromRejection(val); - promise._reject(val, trace === val ? undefined : trace); - }); - this._popContext(); - - if (r !== undefined && r === errorObj) { - var e = r.e; - var trace = canAttachTrace(e) ? e : new Error(e + ""); - promise._reject(e, trace); - } -}; - -Promise.prototype._callHandler = function ( - handler, receiver, promise, value) { - var x; - promise._pushContext(); - if (receiver === APPLY && !this.isRejected()) { - ASSERT(isArray(value), - "isArray(value)"); - x = tryCatchApply(handler, value, this._boundTo); - } else { - x = tryCatch1(handler, receiver, value); - } - promise._popContext(); - return x; -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - if (promise.isRejected()) return; - ASSERT((! promise._isFollowingOrFulfilledOrRejected()), - "!promise._isFollowingOrFulfilledOrRejected()"); - var x = this._callHandler(handler, receiver, promise, value); - if (promise._isFollowing()) return; - - if (x === errorObj || x === promise || x === NEXT_FILTER) { - var err = x === promise - ? makeSelfResolutionError() - : x.e; - var trace = canAttachTrace(err) ? err : new Error(err + ""); - if (x !== NEXT_FILTER) promise._attachExtraTrace(trace); - promise._rejectUnchecked(err, trace); - } else { - var castValue = tryConvertToPromise(x, promise); - if (castValue instanceof Promise) { - if (castValue.isRejected() && - !castValue._isCarryingStackTrace() && - !canAttachTrace(castValue._settledValue)) { - var trace = new Error(castValue._settledValue + ""); - promise._attachExtraTrace(trace); - castValue._setCarriedStackTrace(trace); - } - promise._follow(castValue); - promise._propagateFrom(castValue, 1); - } else { - promise._fulfillUnchecked(x); - } - } -}; - -Promise.prototype._follow = function (promise) { - ASSERT((arguments.length === 1), - "arguments.length === 1"); - ASSERT((this._isFollowingOrFulfilledOrRejected() === false), - "this._isFollowingOrFulfilledOrRejected() === false"); - ASSERT((promise !== this), - "promise !== this"); - this._setFollowing(); - - if (promise.isPending()) { - this._propagateFrom(promise, 1); - promise._proxyPromise(this); - } else if (promise.isFulfilled()) { - this._fulfillUnchecked(promise._settledValue); - } else { - this._rejectUnchecked(promise._settledValue, - promise._getCarriedStackTrace()); - } - - if (promise._isRejectionUnhandled()) promise._unsetRejectionIsUnhandled(); - - if (debugging && - !promise._trace.hasParent()) { - ASSERT((this._trace instanceof CapturedTrace), - "this._trace instanceof CapturedTrace"); - promise._trace.setParent(this._trace); - } -}; - -Promise.prototype._tryFollow = function (value) { - ASSERT((arguments.length === 1), - "arguments.length === 1"); - if (this._isFollowingOrFulfilledOrRejected() || - value === this) { - return false; - } - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) { - return false; - } - this._follow(maybePromise); - return true; -}; - -Promise.prototype._resetTrace = function () { - if (debugging) { - this._trace = new CapturedTrace(this._peekContext()); - } -}; - -Promise.prototype._setTrace = function (parent) { - ASSERT((this._trace == null), - "this._trace == null"); - if (debugging) { - var context = this._peekContext(); - if (parent !== undefined && - parent._trace.parent() === context) { - this._trace = parent._trace; - } else { - this._trace = new CapturedTrace(context); - } - } - return this; -}; - -Promise.prototype._attachExtraTrace = function (error) { - if (debugging && canAttachTrace(error)) { - this._trace.attachExtraTrace(error); - } -}; - -Promise.prototype._cleanValues = function () { - if (this._cancellable()) { - this._cancellationParent = undefined; - } -}; - -Promise.prototype._propagateFrom = function (parent, flags) { - if ((flags & 1) > 0 && parent._cancellable()) { - this._setCancellable(); - this._cancellationParent = parent; - } - if ((flags & 4) > 0) { - this._setBoundTo(parent._boundTo); - } - if ((flags & 2) > 0) { - this._setTrace(parent); - } -}; - -Promise.prototype._fulfill = function (value) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._fulfillUnchecked(value); -}; - -Promise.prototype._reject = function (reason, carriedStackTrace) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._rejectUnchecked(reason, carriedStackTrace); -}; - -Promise.prototype._settlePromiseAt = function (index) { - var handler = this.isFulfilled() - ? this._fulfillmentHandlerAt(index) - : this._rejectionHandlerAt(index); - - ASSERT((this.isFulfilled() || this.isRejected()), - "this.isFulfilled() || this.isRejected()"); - - var carriedStackTrace = - this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; - var value = this._settledValue; - var receiver = this._receiverAt(index); - var promise = this._promiseAt(index); - this._clearCallbackDataAtIndex(index); - - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else { - var done = false; - var isFulfilled = this.isFulfilled(); - if (receiver !== undefined) { - if (receiver instanceof Promise && - receiver._isProxied()) { - if (receiver.isRejected()) return; - ASSERT(((! receiver.isFulfilled()) && (! receiver.isRejected())), - "!receiver.isFulfilled() && !receiver.isRejected()"); - receiver._unsetProxied(); - - if (isFulfilled) receiver._fulfillUnchecked(value); - else receiver._rejectUnchecked(value, - this._getCarriedStackTrace()); - done = true; - } else if (receiver instanceof PromiseArray) { - if (!receiver._isResolved()) { - if (isFulfilled) { - receiver._promiseFulfilled(value, promise); - } - else { - receiver._promiseRejected(value, promise); - } - } - done = true; - } - } - - if (!done) { - if (isFulfilled) promise._fulfill(value); - else promise._reject(value, carriedStackTrace); - } - } -}; - -Promise.prototype._clearCallbackDataAtIndex = function(index) { - if (index === 0) { - if (!this._isCarryingStackTrace()) { - this._fulfillmentHandler0 = undefined; - } - this._rejectionHandler0 = - this._progressHandler0 = - this._receiver0 = - this._promise0 = undefined; - } else { - var base = index * 5 - 5; - this[base + 3] = - this[base + 4] = - this[base + 0] = - this[base + 1] = - this[base + 2] = undefined; - } -}; - -Promise.prototype._isProxied = function () { - return (this._bitField & 4194304) === 4194304; -}; - -Promise.prototype._setProxied = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._unsetProxied = function () { - this._bitField = this._bitField & (~4194304); -}; - -Promise.prototype._isSettlePromisesQueued = function () { - return (this._bitField & - -1073741824) === -1073741824; -}; - -Promise.prototype._setSettlePromisesQueued = function () { - this._bitField = this._bitField | -1073741824; -}; - -Promise.prototype._unsetSettlePromisesQueued = function () { - this._bitField = this._bitField & (~-1073741824); -}; - -Promise.prototype._queueSettlePromises = function() { - if (!this._isSettlePromisesQueued()) { - async.invoke(this._settlePromises, this, undefined); - this._setSettlePromisesQueued(); - } -}; - -Promise.prototype._fulfillUnchecked = function (value) { - ASSERT(((! this.isFulfilled()) && (! this.isRejected())), - "!this.isFulfilled() && !this.isRejected()"); - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._rejectUnchecked(err, undefined); - } - this._setFulfilled(); - this._settledValue = value; - this._cleanValues(); - - if (this._length() > 0) { - this._queueSettlePromises(); - } -}; - -Promise.prototype._rejectUncheckedCheckError = function (reason) { - var trace = canAttachTrace(reason) ? reason : new Error(reason + ""); - this._rejectUnchecked(reason, trace === reason ? undefined : trace); -}; - -Promise.prototype._rejectUnchecked = function (reason, trace) { - ASSERT(((! this.isFulfilled()) && (! this.isRejected())), - "!this.isFulfilled() && !this.isRejected()"); - if (reason === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._rejectUnchecked(err); - } - this._setRejected(); - this._settledValue = reason; - this._cleanValues(); - - if (this._isFinal()) { - ASSERT((this._length() === 0), - "this._length() === 0"); - async.invokeLater(function(e) { - if ("stack" in e) { - async.invokeFirst( - CapturedTrace.unhandledRejection, undefined, e); - } - throw e; - }, undefined, trace === undefined ? reason : trace); - return; - } - - if (trace !== undefined) this._setCarriedStackTrace(trace); - - if (this._length() > 0) { - this._queueSettlePromises(); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._settlePromises = function () { - this._unsetSettlePromisesQueued(); - var len = this._length(); - this._setLength(0); - for (var i = 0; i < len; i++) { - this._settlePromiseAt(i); - } -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - this._setRejectionIsUnhandled(); - if (CapturedTrace.possiblyUnhandledRejection !== undefined) { - async.invokeLater(this._notifyUnhandledRejection, this, undefined); - } -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - if (typeof unhandledRejectionHandled === "function") { - async.invokeLater(unhandledRejectionHandled, undefined, this); - } -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue; - var trace = this._getCarriedStackTrace(); - - this._setUnhandledRejectionIsNotified(); - - if (trace !== undefined) { - this._unsetCarriedStackTrace(); - reason = trace; - } - if (typeof CapturedTrace.possiblyUnhandledRejection === "function") { - CapturedTrace.possiblyUnhandledRejection(reason, this); - } - } -}; - -var contextStack = []; -Promise.prototype._peekContext = function () { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; - -}; - -Promise.prototype._pushContext = function () { - if (!debugging) return; - contextStack.push(this._trace); -}; - -Promise.prototype._popContext = function () { - if (!debugging) return; - contextStack.pop(); -}; - -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === errorObj) { - this._setRejected(); - var reason = value.e; - this._settledValue = reason; - this._cleanValues(); - this._attachExtraTrace(reason); - this._ensurePossibleRejectionHandled(); - } else { - var maybePromise = tryConvertToPromise(value, this); - if (maybePromise instanceof Promise) { - this._follow(maybePromise); - } else { - this._setFulfilled(); - this._settledValue = value; - this._cleanValues(); - } - } -}; - -if (!CapturedTrace.isSupported()) { - Promise.longStackTraces = function(){}; - debugging = false; -} - -Promise._makeSelfResolutionError = makeSelfResolutionError; -require("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); -require("./direct_resolve.js")(Promise); -require("./synchronous_inspection.js")(Promise); -require("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); -Promise.RangeError = RangeError; -Promise.CancellationError = CancellationError; -Promise.TimeoutError = TimeoutError; -Promise.TypeError = TypeError; -Promise.OperationalError = OperationalError; -Promise.RejectionError = OperationalError; -Promise.AggregateError = errors.AggregateError; - -util.toFastProperties(Promise); -util.toFastProperties(Promise.prototype); -Promise.Promise = Promise; -CapturedTrace.setBounds(async.firstLineError, util.lastLineError); -require('./timers.js')(Promise,INTERNAL,tryConvertToPromise); -require('./race.js')(Promise,INTERNAL,tryConvertToPromise); -require('./call_get.js')(Promise); -require('./generators.js')(Promise,apiRejection,INTERNAL,tryConvertToPromise); -require('./map.js')(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL); -require('./nodeify.js')(Promise); -require('./promisify.js')(Promise,INTERNAL); -require('./props.js')(Promise,PromiseArray,tryConvertToPromise); -require('./reduce.js')(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL); -require('./settle.js')(Promise,PromiseArray); -require('./some.js')(Promise,PromiseArray,apiRejection); -require('./progress.js')(Promise,PromiseArray); -require('./cancel.js')(Promise,INTERNAL); -require('./filter.js')(Promise,INTERNAL); -require('./any.js')(Promise,PromiseArray); -require('./each.js')(Promise,INTERNAL); -require('./using.js')(Promise,apiRejection,tryConvertToPromise); - -Promise.prototype = Promise.prototype; -return Promise; - -}; - -},{"./any.js":18,"./assert.js":19,"./async.js":20,"./call_get.js":22,"./cancel.js":23,"./captured_trace.js":24,"./catch_filter.js":25,"./direct_resolve.js":26,"./each.js":27,"./errors.js":28,"./errors_api_rejection":29,"./filter.js":31,"./finally.js":32,"./generators.js":33,"./join.js":34,"./map.js":35,"./nodeify.js":36,"./progress.js":37,"./promise_array.js":39,"./promise_resolver.js":40,"./promisify.js":41,"./props.js":42,"./race.js":44,"./reduce.js":45,"./settle.js":47,"./some.js":48,"./synchronous_inspection.js":49,"./thenables.js":50,"./timers.js":51,"./using.js":52,"./util.js":53,"__browserify_process":16}],39:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise) { -var ASSERT = require("./assert.js"); -var canAttachTrace = require("./errors.js").canAttachTrace; -var util = require("./util.js"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -1: return undefined; - case -2: return []; - case -3: return {}; - } - ASSERT(false, - "false"); -} - -function PromiseArray(values) { - ASSERT((arguments.length === 1), - "arguments.length === 1"); - var promise = this._promise = new Promise(INTERNAL); - var parent; - if (values instanceof Promise) { - parent = values; - promise._propagateFrom(parent, 1 | 4); - } - promise._setTrace(parent); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -PromiseArray.prototype.length = function () { - return this._length; -}; - -PromiseArray.prototype.promise = function () { - return this._promise; -}; - -PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { - - var values = tryConvertToPromise(this._values, undefined); - if (values instanceof Promise) { - this._values = values; - values._setBoundTo(this._promise._boundTo); - if (values.isFulfilled()) { - values = values._settledValue; - if (!isArray(values)) { - var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); - this.__hardReject__(err); - return; - } - } else if (values.isPending()) { - ASSERT(((typeof resolveValueIfEmpty) === "number"), - "typeof resolveValueIfEmpty === \u0022number\u0022"); - ASSERT((resolveValueIfEmpty < 0), - "resolveValueIfEmpty < 0"); - values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - return; - } else { - values._unsetRejectionIsUnhandled(); - this._reject(values._settledValue); - return; - } - } else if (!isArray(values)) { - var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); - this.__hardReject__(err); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - var len = this.getActualLength(values.length); - this._length = len; - this._values = this.shouldCopyValues() ? new Array(len) : this._values; - var promise = this._promise; - for (var i = 0; i < len; ++i) { - if (this._isResolved()) return; - var maybePromise = tryConvertToPromise(values[i], promise); - if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { - maybePromise._proxyPromiseArray(this, i); - } else if (maybePromise.isFulfilled()) { - this._promiseFulfilled(maybePromise._settledValue, i); - } else { - maybePromise._unsetRejectionIsUnhandled(); - this._promiseRejected(maybePromise._settledValue, i); - } - } else { - this._promiseFulfilled(maybePromise, i); - } - } -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - ASSERT((! (value instanceof Promise)), - "!(value instanceof Promise)"); - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype.__hardReject__ = -PromiseArray.prototype._reject = function (reason) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - this._values = null; - var trace = canAttachTrace(reason) ? reason : new Error(reason + ""); - this._promise._attachExtraTrace(trace); - this._promise._reject(reason, trace); -}; - -PromiseArray.prototype._promiseProgressed = function (progressValue, index) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - ASSERT(isArray(this._values), - "isArray(this._values)"); - this._promise._progress({ - index: index, - value: progressValue - }); -}; - - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - ASSERT(isArray(this._values), - "isArray(this._values)"); - ASSERT(((typeof index) === "number"), - "typeof index === \u0022number\u0022"); - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - } -}; - -PromiseArray.prototype._promiseRejected = function (reason, index) { - ASSERT((index >= 0), - "index >= 0"); - ASSERT((! this._isResolved()), - "!this._isResolved()"); - ASSERT(isArray(this._values), - "isArray(this._values)"); - this._totalResolved++; - this._reject(reason); -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; - -},{"./assert.js":19,"./errors.js":28,"./util.js":53}],40:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var util = require("./util.js"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = require("./errors.js"); -var TimeoutError = errors.TimeoutError; -var OperationalError = errors.OperationalError; -var async = require("./async.js"); -var haveGetters = util.haveGetters; -var es5 = require("./es5.js"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - } else { - ret = obj; - } - errors.markAsOriginatingFromRejection(ret); - return ret; -} - -function nodebackForPromise(promise) { - return function(err, value) { - if (promise === null) return; - - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (arguments.length > 2) { - var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} - promise._fulfill(args); - } else { - promise._fulfill(value); - } - - promise = null; - }; -} - - -var PromiseResolver; -if (!haveGetters) { - PromiseResolver = function (promise) { - this.promise = promise; - this.asCallback = nodebackForPromise(promise); - this.callback = this.asCallback; - }; -} -else { - PromiseResolver = function (promise) { - this.promise = promise; - }; -} -if (haveGetters) { - var prop = { - get: function() { - return nodebackForPromise(this.promise); - } - }; - es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); - es5.defineProperty(PromiseResolver.prototype, "callback", prop); -} - -PromiseResolver._nodebackForPromise = nodebackForPromise; - -PromiseResolver.prototype.toString = function () { - return "[object PromiseResolver]"; -}; - -PromiseResolver.prototype.resolve = -PromiseResolver.prototype.fulfill = function (value) { - if (!(this instanceof PromiseResolver)) { - throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); - } - - var promise = this.promise; - if (promise._tryFollow(value)) { - return; - } - async.invoke(promise._fulfill, promise, value); -}; - -PromiseResolver.prototype.reject = function (reason) { - if (!(this instanceof PromiseResolver)) { - throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); - } - - var promise = this.promise; - errors.markAsOriginatingFromRejection(reason); - var trace = errors.canAttachTrace(reason) ? reason : new Error(reason + ""); - promise._attachExtraTrace(trace); - async.invoke(promise._reject, promise, reason); - if (trace !== reason) { - async.invoke(this._setCarriedStackTrace, this, trace); - } -}; - -PromiseResolver.prototype.progress = function (value) { - if (!(this instanceof PromiseResolver)) { - throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); - } - async.invoke(this.promise._progress, this.promise, value); -}; - -PromiseResolver.prototype.cancel = function () { - async.invoke(this.promise.cancel, this.promise, undefined); -}; - -PromiseResolver.prototype.timeout = function () { - this.reject(new TimeoutError("timeout")); -}; - -PromiseResolver.prototype.isResolved = function () { - return this.promise.isResolved(); -}; - -PromiseResolver.prototype.toJSON = function () { - return this.promise.toJSON(); -}; - -PromiseResolver.prototype._setCarriedStackTrace = function (trace) { - if (this.promise.isRejected()) { - this.promise._setCarriedStackTrace(trace); - } -}; - -module.exports = PromiseResolver; - -},{"./async.js":20,"./errors.js":28,"./es5.js":30,"./util.js":53}],41:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = require("./util.js"); -var nodebackForPromise = require("./promise_resolver.js") - ._nodebackForPromise; -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var ASSERT = require("./assert.js"); -var TypeError = require("./errors").TypeError; -var defaultSuffix = "Async"; -var defaultFilter = function(name, func) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - !util.isClass(func); -}; -var defaultPromisified = {__isPromisified__: true}; - - -function escapeIdentRegex(str) { - return str.replace(/([$])/, "\\$"); -} - -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" - .replace("%s", suffix)); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -function switchCaseArgumentOrder(likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 5); - for(var i = likelyArgumentCount - 1; i >= min; --i) { - if (i === likelyArgumentCount) continue; - ret.push(i); - } - for(var i = likelyArgumentCount + 1; i <= 5; ++i) { - ret.push(i); - } - return ret; -} - -function argumentSequence(argumentCount) { - return util.filledRange(argumentCount, "arguments[", "]"); -} - -function parameterDeclaration(parameterCount) { - return util.filledRange(parameterCount, "_arg", ""); -} - -function parameterCount(fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; -} - -function generatePropertyAccess(key) { - if (util.isIdentifier(key)) { - return "." + key; - } - else return "['" + key.replace(/(['\\])/g, "\\$1") + "']"; -} - -function makeNodePromisifiedEval(callback, receiver, originalName, fn, suffix) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var callbackName = - (typeof originalName === "string" && util.isIdentifier(originalName) - ? originalName + suffix - : "promisified"); - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (typeof callback === "string") { - ret = " \n\ - this.method({{args}}, fn); \n\ - break; \n\ - ".replace(".method", generatePropertyAccess(callback)); - } else if (receiver === THIS) { - ret = " \n\ - callback.call(this, {{args}}, fn); \n\ - break; \n\ - "; - } else if (receiver !== undefined) { - ret = " \n\ - callback.call(receiver, {{args}}, fn); \n\ - break; \n\ - "; - } else { - ret = " \n\ - callback({{args}}, fn); \n\ - break; \n\ - "; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for(var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - var codeForCall; - if (typeof callback === "string") { - codeForCall = " \n\ - this.property.apply(this, args); \n\ - " - .replace(".property", generatePropertyAccess(callback)); - } else if (receiver === THIS) { - codeForCall = " \n\ - callback.apply(this, args); \n\ - "; - } else { - codeForCall = " \n\ - callback.apply(receiver, args); \n\ - "; - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = fn; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", codeForCall); - return ret; - } - - return new Function("Promise", - "callback", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "INTERNAL"," \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._setTrace(undefined); \n\ - var fn = nodebackForPromise(promise); \n\ - try { \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - } catch (e) { \n\ - var wrapped = maybeWrapAsError(e); \n\ - promise._attachExtraTrace(wrapped); \n\ - promise._reject(wrapped); \n\ - } \n\ - return promise; \n\ - }; \n\ - ret.__isPromisified__ = true; \n\ - return ret; \n\ - " - .replace("FunctionName", callbackName) - .replace("Parameters", parameterDeclaration(newParameterCount)) - .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()))( - Promise, - callback, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - INTERNAL - ); -} - -function makeNodePromisifiedClosure(callback, receiver) { - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - if (typeof callback === "string") { - callback = _receiver[callback]; - } - ASSERT(((typeof callback) === "function"), - "typeof callback === \u0022function\u0022"); - var promise = new Promise(INTERNAL); - promise._setTrace(undefined); - var fn = nodebackForPromise(promise); - try { - callback.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - var wrapped = maybeWrapAsError(e); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } - return promise; - } - promisified.__isPromisified__ = true; - return promisified; -} - -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - -function promisifyAll(obj, suffix, filter, promisifier) { - ASSERT(((typeof suffix) === "string"), - "typeof suffix === \u0022string\u0022"); - ASSERT(((typeof filter) === "function"), - "typeof filter === \u0022function\u0022"); - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - obj[promisifiedKey] = promisifier === makeNodePromisified - ? makeNodePromisified(key, THIS, key, fn, suffix) - : promisifier(fn); - } - util.toFastProperties(obj); - return obj; -} - -function promisify(callback, receiver) { - return makeNodePromisified(callback, receiver, undefined, callback); -} - -Promise.promisify = function (fn, receiver) { - if (typeof fn !== "function") { - throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - } - if (isPromisified(fn)) { - return fn; - } - return promisify(fn, arguments.length < 2 ? THIS : receiver); -}; - -Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); - } - options = Object(options); - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); - } - - var keys = util.inheritedDataKeys(target, {includeHidden: true}); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier); - promisifyAll(value, suffix, filter, promisifier); - } - } - - return promisifyAll(target, suffix, filter, promisifier); -}; -}; - - -},{"./assert.js":19,"./errors":28,"./promise_resolver.js":40,"./util.js":53}],42:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray, tryConvertToPromise) { -var ASSERT = require("./assert.js"); -var util = require("./util.js"); -var apiRejection = require("./errors_api_rejection")(Promise); -var isObject = util.isObject; -var es5 = require("./es5.js"); - -function PropertiesPromiseArray(obj) { - var keys = es5.keys(obj); - var len = keys.length; - var values = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - values[i] = obj[key]; - values[i + len] = key; - } - this.constructor$(values); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () { - this._init$(undefined, -3) ; -}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - ASSERT((! (value instanceof Promise)), - "!(value instanceof Promise)"); - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - this._resolve(val); - } -}; - -PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - - this._promise._progress({ - key: this._values[index + this.length()], - value: value - }); -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; - -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises, undefined); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 4); - } - return ret; -} - -Promise.prototype.props = function () { - return props(this); -}; - -Promise.props = function (promises) { - return props(promises); -}; -}; - -},{"./assert.js":19,"./errors_api_rejection":29,"./es5.js":30,"./util.js":53}],43:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var ASSERT = require("./assert.js"); -function arrayCopy(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - } -} - -function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; - this._makeCapacity(); -} - -Queue.prototype._willBeOverCapacity = function (size) { - return this._capacity < size; -}; - -Queue.prototype._pushOne = function (arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; -}; - -Queue.prototype._unshiftOne = function(value) { - var capacity = this._capacity; - this._checkCapacity(this.length() + 1); - var front = this._front; - var i = (((( front - 1 ) & - ( capacity - 1) ) ^ capacity ) - capacity ); - this[i] = value; - this._front = i; - this._length = this.length() + 1; -}; - -Queue.prototype.unshift = function(fn, receiver, arg) { - this._unshiftOne(arg); - this._unshiftOne(receiver); - this._unshiftOne(fn); -}; - -Queue.prototype.push = function (fn, receiver, arg) { - ASSERT((arguments.length === 3), - "arguments.length === 3"); - ASSERT(((typeof fn) === "function"), - "typeof fn === \u0022function\u0022"); - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; -}; - -Queue.prototype.shift = function () { - ASSERT((this.length() > 0), - "this.length() > 0"); - var front = this._front, - ret = this[front]; - - this[front] = undefined; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; -}; - -Queue.prototype.length = function () { - return this._length; -}; - -Queue.prototype._makeCapacity = function () { - var len = this._capacity; - for (var i = 0; i < len; ++i) { - this[i] = undefined; - } -}; - -Queue.prototype._checkCapacity = function (size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 3); - } -}; - -Queue.prototype._resizeTo = function (capacity) { - var oldFront = this._front; - var oldCapacity = this._capacity; - var oldQueue = new Array(oldCapacity); - var length = this.length(); - - arrayCopy(this, 0, oldQueue, 0, oldCapacity); - this._capacity = capacity; - this._makeCapacity(); - this._front = 0; - if (oldFront + length <= oldCapacity) { - arrayCopy(oldQueue, oldFront, this, 0, length); - } else { var lengthBeforeWrapping = - length - ((oldFront + length) & (oldCapacity - 1)); - - arrayCopy(oldQueue, oldFront, this, 0, lengthBeforeWrapping); - arrayCopy(oldQueue, 0, this, lengthBeforeWrapping, - length - lengthBeforeWrapping); - } -}; - -module.exports = Queue; - -},{"./assert.js":19}],44:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise) { -var apiRejection = require("./errors_api_rejection.js")(Promise); -var isArray = require("./util.js").isArray; - -var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); -}; - -var hasOwn = {}.hasOwnProperty; -function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises, undefined); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else if (!isArray(promises)) { - return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); - } - - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 7); - } else { - ret._setTrace(undefined); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === undefined && !(hasOwn.call(promises, i))) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; -} - -Promise.race = function (promises) { - return race(promises, undefined); -}; - -Promise.prototype.race = function () { - return race(this, undefined); -}; - -}; - -},{"./errors_api_rejection.js":29,"./util.js":53}],45:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL) { -var ASSERT = require("./assert.js"); -var util = require("./util.js"); -var tryCatch4 = util.tryCatch4; -var tryCatch3 = util.tryCatch3; -var errorObj = util.errorObj; -function ReductionPromiseArray(promises, fn, accum, _each) { - this.constructor$(promises); - this._preservedValues = _each === INTERNAL ? [] : null; - this._zerothIsAccum = (accum === undefined); - this._gotAccum = false; - this._reducingIndex = (this._zerothIsAccum ? 1 : 0); - this._valuesPhase = undefined; - - var maybePromise = tryConvertToPromise(accum, undefined); - var rejected = false; - var isPromise = maybePromise instanceof Promise; - if (isPromise) { - if (maybePromise.isPending()) { - maybePromise._proxyPromiseArray(this, -1); - } else if (maybePromise.isFulfilled()) { - accum = maybePromise._settledValue; - this._gotAccum = true; - } else { - maybePromise._unsetRejectionIsUnhandled(); - this._reject(maybePromise.reason()); - rejected = true; - } - } - if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; - this._callback = fn; - this._accum = accum; - if (!rejected) this._init$(undefined, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._init = function () {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = function () { - if (this._gotAccum || this._zerothIsAccum) { - this._resolve(this._preservedValues !== null - ? [] : this._accum); - } -}; - -ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - var values = this._values; - values[index] = value; - var length = this.length(); - var preservedValues = this._preservedValues; - var isEach = preservedValues !== null; - var gotAccum = this._gotAccum; - var valuesPhase = this._valuesPhase; - var valuesPhaseIndex; - if (!valuesPhase) { - valuesPhase = this._valuesPhase = Array(length); - for (valuesPhaseIndex=0; valuesPhaseIndex - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var ASSERT = require("./assert.js"); -var schedule; -var _MutationObserver; -if (typeof process === "object" && typeof process.version === "string") { - schedule = function (fn) { - process.nextTick(fn); - }; -} -else if ((typeof MutationObserver !== "undefined" && - (_MutationObserver = MutationObserver)) || - (typeof WebKitMutationObserver !== "undefined" && - (_MutationObserver = WebKitMutationObserver))) { - schedule = (function() { - var div = document.createElement("div"); - var queuedFn; - var observer = new _MutationObserver(function() { - ASSERT((queuedFn !== undefined), - "queuedFn !== undefined"); - var fn = queuedFn; - queuedFn = undefined; - fn(); - }); - observer.observe(div, { - attributes: true - }); - return function(fn) { - ASSERT((queuedFn === undefined), - "queuedFn === undefined"); - queuedFn = fn; - div.classList.toggle("foo"); - }; - - })(); -} -else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} -else throw new Error("no async scheduler available"); -module.exports = schedule; - -},{"./assert.js":19,"__browserify_process":16}],47:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = - function(Promise, PromiseArray) { -var ASSERT = require("./assert.js"); -var PromiseInspection = Promise.PromiseInspection; -var util = require("./util.js"); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - ASSERT(((typeof index) === "number"), - "typeof index === \u0022number\u0022"); - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - } -}; - -SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - ASSERT(((typeof index) === "number"), - "typeof index === \u0022number\u0022"); - var ret = new PromiseInspection(); - ret._bitField = 268435456; - ret._settledValue = value; - this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - ASSERT(((typeof index) === "number"), - "typeof index === \u0022number\u0022"); - var ret = new PromiseInspection(); - ret._bitField = 134217728; - ret._settledValue = reason; - this._promiseResolved(index, ret); -}; - -Promise.settle = function (promises) { - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function () { - return new SettledPromiseArray(this).promise(); -}; -}; - -},{"./assert.js":19,"./util.js":53}],48:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var ASSERT = require("./assert.js"); -var util = require("./util.js"); -var RangeError = require("./errors.js").RangeError; -var AggregateError = require("./errors.js").AggregateError; -var isArray = util.isArray; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = function (count) { - if (this._isResolved()) return; - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = function (value) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - } - -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - ASSERT((! this._isResolved()), - "!this._isResolved()"); - this._addRejected(reason); - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - e.push(this._values[i]); - } - this._reject(e); - } -}; - -SomePromiseArray.prototype._fulfilled = function () { - return this._totalResolved; -}; - -SomePromiseArray.prototype._rejected = function () { - return this._values.length - this.length(); -}; - -SomePromiseArray.prototype._addRejected = function (reason) { - this._values.push(reason); -}; - -SomePromiseArray.prototype._addFulfilled = function (value) { - this._values[this._totalResolved++] = value; -}; - -SomePromiseArray.prototype._canPossiblyFulfill = function () { - return this.length() - this._rejected(); -}; - -SomePromiseArray.prototype._getRangeError = function (count) { - var message = "Input array must contain at least " + - this._howMany + " items but contains only " + count + " items"; - return new RangeError(message); -}; - -SomePromiseArray.prototype._resolveEmptyArray = function () { - this._reject(this._getRangeError(0)); -}; - -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - if (promise.isRejected()) { - return promise; - } - ASSERT((ret instanceof SomePromiseArray), - "ret instanceof SomePromiseArray"); - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -Promise.some = function (promises, howMany) { - return some(promises, howMany); -}; - -Promise.prototype.some = function (howMany) { - return some(this, howMany); -}; - -Promise._SomePromiseArray = SomePromiseArray; -}; - -},{"./assert.js":19,"./errors.js":28,"./util.js":53}],49:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - this._bitField = promise._bitField; - this._settledValue = promise.isResolved() - ? promise._settledValue - : undefined; - } - else { - this._bitField = 0; - this._settledValue = undefined; - } -} - -PromiseInspection.prototype.isFulfilled = -Promise.prototype.isFulfilled = function () { - return (this._bitField & 268435456) > 0; -}; - -PromiseInspection.prototype.isRejected = -Promise.prototype.isRejected = function () { - return (this._bitField & 134217728) > 0; -}; - -PromiseInspection.prototype.isPending = -Promise.prototype.isPending = function () { - return (this._bitField & 402653184) === 0; -}; - -PromiseInspection.prototype.value = -Promise.prototype.value = function () { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); - } - return this._settledValue; -}; - -PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = -Promise.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); - } - return this._settledValue; -}; - -PromiseInspection.prototype.isResolved = -Promise.prototype.isResolved = function () { - return (this._bitField & 402653184) > 0; -}; - -Promise.PromiseInspection = PromiseInspection; -}; - -},{}],50:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var ASSERT = require("./assert.js"); -var util = require("./util.js"); -var canAttachTrace = require("./errors.js").canAttachTrace; -var errorObj = util.errorObj; -var isObject = util.isObject; - -function getThen(obj) { - try { - return obj.then; - } - catch(e) { - errorObj.e = e; - return errorObj; - } -} - -function tryConvertToPromise(obj, traceParent) { - ASSERT((arguments.length === 2), - "arguments.length === 2"); - if (isObject(obj)) { - if (obj instanceof Promise) { - return obj; - } - else if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - ret._setTrace(undefined); - obj._then( - ret._fulfillUnchecked, - ret._rejectUncheckedCheckError, - ret._progressUnchecked, - ret, - null - ); - ret._setFollowing(); - return ret; - } - var then = getThen(obj); - if (then === errorObj) { - if (traceParent !== undefined && canAttachTrace(then.e)) { - traceParent._attachExtraTrace(then.e); - } - return Promise.reject(then.e); - } else if (typeof then === "function") { - return doThenable(obj, then, traceParent); - } - } - return obj; -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - return hasProp.call(obj, "_promise0"); -} - -function doThenable(x, then, traceParent) { - ASSERT(((typeof then) === "function"), - "typeof then === \u0022function\u0022"); - ASSERT((arguments.length === 3), - "arguments.length === 3"); - var resolver = Promise.defer(); - var called = false; - try { - then.call( - x, - resolveFromThenable, - rejectFromThenable, - progressFromThenable - ); - } catch(e) { - if (!called) { - called = true; - var trace = canAttachTrace(e) ? e : new Error(e + ""); - if (traceParent !== undefined) { - traceParent._attachExtraTrace(trace); - } - resolver.promise._reject(e, trace); - } - } - return resolver.promise; - - function resolveFromThenable(y) { - if (called) return; - called = true; - - if (x === y) { - var e = Promise._makeSelfResolutionError(); - if (traceParent !== undefined) { - traceParent._attachExtraTrace(e); - } - resolver.promise._reject(e, undefined); - return; - } - resolver.resolve(y); - } - - function rejectFromThenable(r) { - if (called) return; - called = true; - var trace = canAttachTrace(r) ? r : new Error(r + ""); - if (traceParent !== undefined) { - traceParent._attachExtraTrace(trace); - } - resolver.promise._reject(r, trace); - } - - function progressFromThenable(v) { - if (called) return; - var promise = resolver.promise; - if (typeof promise._progress === "function") { - promise._progress(v); - } - } -} - -return tryConvertToPromise; -}; - -},{"./assert.js":19,"./errors.js":28,"./util.js":53}],51:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var ASSERT = require("./assert.js"); -module.exports = function(Promise, INTERNAL, tryConvertToPromise) { -var util = require("./util.js"); -var errors = require("./errors.js"); -var apiRejection = require("./errors_api_rejection")(Promise); -var TimeoutError = Promise.TimeoutError; - -var afterTimeout = function (promise, parent, message) { - if (!promise.isPending()) return; - if (typeof message !== "string") { - message = "operation timed out"; - } - var err = new TimeoutError(message); - errors.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._cancel(err); -}; - -var afterDelay = function (value, promise) { - promise._fulfill(value); -}; - -var delay = Promise.delay = function (value, ms) { - if (ms === undefined) { - ms = value; - value = undefined; - } - ms = +ms; - var maybePromise = tryConvertToPromise(value, undefined); - var promise = new Promise(INTERNAL); - - if (maybePromise instanceof Promise) { - promise._propagateFrom(maybePromise, 7); - promise._follow(maybePromise); - return promise.then(function(value) { - return Promise.delay(value, ms); - }); - } else { - promise._setTrace(undefined); - setTimeout(function delayTimeout() { - afterDelay(value, promise); - }, ms); - } - return promise; -}; - -Promise.prototype.delay = function (ms) { - return delay(this, ms); -}; - -function successClear(value) { - var handle = this; - if (handle instanceof Number) handle = +handle; - clearTimeout(handle); - return value; -} - -function failureClear(reason) { - var handle = this; - if (handle instanceof Number) handle = +handle; - clearTimeout(handle); - throw reason; -} - -Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret = new Promise(INTERNAL).cancellable(); - ret._propagateFrom(this, 7); - ret._follow(this); - var handle = setTimeout(function timeoutTimeout() { - afterTimeout(ret, this, message); - }, ms); - return ret._then(successClear, failureClear, undefined, handle, undefined); -}; - -}; - -},{"./assert.js":19,"./errors.js":28,"./errors_api_rejection":29,"./util.js":53}],52:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function (Promise, apiRejection, tryConvertToPromise) { - var TypeError = require("./errors.js").TypeError; - var inherits = require("./util.js").inherits; - var PromiseInspection = Promise.PromiseInspection; - - function inspectionMapper(inspections) { - var len = inspections.length; - for (var i = 0; i < len; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - return Promise.reject(inspection.error()); - } - inspections[i] = inspection._settledValue; - } - return inspections; - } - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable, undefined); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = Promise.defer(); - function iterator() { - if (i >= len) return ret.resolve(); - var maybePromise = castPreservingDisposable(resources[i++]); - if (maybePromise instanceof Promise && - maybePromise._isDisposable()) { - try { - maybePromise = tryConvertToPromise( - maybePromise._getDisposer().tryDispose(inspection), - undefined); - } catch (e) { - return thrower(e); - } - if (maybePromise instanceof Promise) { - return maybePromise._then(iterator, thrower, - null, null, null); - } - } - iterator(); - } - iterator(); - return ret.promise; - } - - function disposerSuccess(value) { - var inspection = new PromiseInspection(); - inspection._settledValue = value; - inspection._bitField = 268435456; - return dispose(this, inspection).thenReturn(value); - } - - function disposerFail(reason) { - var inspection = new PromiseInspection(); - inspection._settledValue = reason; - inspection._bitField = 134217728; - return dispose(this, inspection).thenThrow(reason); - } - - function Disposer(data, promise) { - this._data = data; - this._promise = promise; - } - - Disposer.prototype.data = function () { - return this._data; - }; - - Disposer.prototype.promise = function () { - return this._promise; - }; - - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise()._settledValue; - } - return null; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var ret = resource !== null - ? this.doDispose(resource, inspection) : null; - this._promise._unsetDisposable(); - this._data = this._promise = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise) { - this.constructor$(fn, promise); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - len--; - var resources = new Array(len); - for (var i = 0; i < len; ++i) { - var resource = arguments[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } - resources[i] = resource; - } - - return Promise.settle(resources) - .then(inspectionMapper) - .spread(fn) - ._then( - disposerSuccess, disposerFail, undefined, resources, undefined); - }; - - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 262144; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function () { - return (this._bitField & 262144) > 0; - }; - - Promise.prototype._getDisposer = function () { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~262144); - this._disposer = undefined; - }; - - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this); - } - throw new TypeError(); - }; - -}; - -},{"./errors.js":28,"./util.js":53}],53:[function(require,module,exports){ -/** - * The MIT License (MIT) - * - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var ASSERT = require("./assert.js"); -var es5 = require("./es5.js"); -var haveGetters = (function(){ - try { - var o = {}; - es5.defineProperty(o, "f", { - get: function () { - return 3; - } - }); - return o.f === 3; - } - catch (e) { - return false; - } - -})(); -var canEvaluate = typeof navigator == "undefined"; -var errorObj = {e: {}}; -function tryCatch1(fn, receiver, arg) { - try { return fn.call(receiver, arg); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch2(fn, receiver, arg, arg2) { - try { return fn.call(receiver, arg, arg2); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch3(fn, receiver, arg, arg2, arg3) { - try { return fn.call(receiver, arg, arg2, arg3); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch4(fn, receiver, arg, arg2, arg3, arg4) { - try { return fn.call(receiver, arg, arg2, arg3, arg4); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatchApply(fn, args, receiver) { - try { return fn.apply(receiver, args); } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - -function asString(val) { - return typeof val === "string" ? val : ("" + val); -} - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return !isPrimitive(value); -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(asString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - - -var wrapsPrimitiveReceiver = (function() { - return this !== "string"; -}).call("string"); - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - if (es5.isES5) { - return function(obj, opts) { - var ret = []; - var visitedKeys = Object.create(null); - var getKeys = Object(opts).includeHidden - ? Object.getOwnPropertyNames - : Object.keys; - while (obj != null) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - return function(obj) { - var ret = []; - /*jshint forin:false */ - for (var key in obj) { - ret.push(key); - } - return ret; - }; - } - -})(); - -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.keys(fn.prototype); - return keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027*/ - function f() {} - f.prototype = obj; - ASSERT("%HasFastProperties", true, obj); - return f; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - haveGetters: haveGetters, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch1: tryCatch1, - tryCatch2: tryCatch2, - tryCatch3: tryCatch3, - tryCatch4: tryCatch4, - tryCatchApply: tryCatchApply, - inherits: inherits, - withAppended: withAppended, - asString: asString, - maybeWrapAsError: maybeWrapAsError, - wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, - toFastProperties: toFastProperties, - filledRange: filledRange, - lastLineError: new Error() -}; - -module.exports = ret; - -},{"./assert.js":19,"./es5.js":30}],54:[function(require,module,exports){ -var process=require("__browserify_process");// vim:ts=4:sts=4:sw=4: -/*! - * - * Copyright 2009-2012 Kris Kowal under the terms of the MIT - * license found at http://github.com/kriskowal/q/raw/master/LICENSE - * - * With parts by Tyler Close - * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found - * at http://www.opensource.org/licenses/mit-license.html - * Forked at ref_send.js version: 2009-05-11 - * - * With parts by Mark Miller - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -(function (definition) { - // Turn off strict mode for this function so we can assign to global.Q - /* jshint strict: false */ - - // This file will function properly as a - - + + - - diff --git a/browser/init_run.js b/browser/init_run.js deleted file mode 100644 index 8f163d636..000000000 --- a/browser/init_run.js +++ /dev/null @@ -1,21 +0,0 @@ -(function(tests){ - - - function requiresGetters(test) { - //AP2 requires real getters - //it's mostly about staying robust in the face - //of evil getters anyway. - return /2\.\d+\.\d+/.test(test.name) || - //requires real getters too - test.name.indexOf("promises_unwrapping") > -1; - } - - for( var i = 0, len = tests.length; i < len; ++i ) { - var test = tests[i]; - if( !haveGetters && requiresGetters( test ) ) { - continue; - } - test.fn(); - } - -})(tests); diff --git a/browser/main.js b/browser/main.js new file mode 100644 index 000000000..4d2c3b186 --- /dev/null +++ b/browser/main.js @@ -0,0 +1,130 @@ +var Promise = require("../js/debug/bluebird.js"); +window.Promise = Promise; +window.adapter = Promise; +window.sinon = require("sinon"); +window.assert = require("assert"); + +var prev = window.assert.deepEqual; +window.assert.deepEqual = function(a, b) { + if (Array.isArray(a) && + Array.isArray(b)) { + if (a.length === b.length) { + for (var i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + } + return false; + } else { + return prev.call(window.assert, a, b); + } +}; + +window.setImmediate = function(fn){ + setTimeout(fn, 0); +}; + +require('../test/mocha/2.1.2.js'); +require('../test/mocha/2.1.3.js'); +require('../test/mocha/2.2.1.js'); +require('../test/mocha/2.2.2.js'); +require('../test/mocha/2.2.3.js'); +require('../test/mocha/2.2.4.js'); +require('../test/mocha/2.2.5.js'); +require('../test/mocha/2.2.6.js'); +require('../test/mocha/2.2.7.js'); +require('../test/mocha/2.3.1.js'); +require('../test/mocha/2.3.2.js'); +if (haveGetters) require('../test/mocha/2.3.3.js'); +require('../test/mocha/2.3.4.js'); +require('../test/mocha/3.2.1.js'); +require('../test/mocha/3.2.2.js'); +require('../test/mocha/3.2.3.js'); +require('../test/mocha/3.2.4.js'); +require('../test/mocha/3.2.5.js'); +require('../test/mocha/3.2.6.js'); +require('../test/mocha/api_exceptions.js'); +require('../test/mocha/async.js'); +require('../test/mocha/bind.js'); +require('../test/mocha/bluebird-multiple-instances.js'); +require('../test/mocha/call.js'); +require('../test/mocha/cancel.js'); +require('../test/mocha/catch_filter.js'); +require('../test/mocha/collections_thenables.js'); +require('../test/mocha/constructor.js'); +require('../test/mocha/cycles.js'); +require('../test/mocha/direct_resolving.js'); +require('../test/mocha/domain.js'); +require('../test/mocha/each.js'); +require('../test/mocha/error.js'); +require('../test/mocha/filter.js'); +require('../test/mocha/following.js'); +require('../test/mocha/get.js'); +require('../test/mocha/github-2xx-76.js'); +require('../test/mocha/github-3.6.4.js'); +require('../test/mocha/github-3.7.3.js'); +require('../test/mocha/github36.js'); +require('../test/mocha/late_buffer_safety.js'); +require('../test/mocha/method.js'); +require('../test/mocha/promisify.js'); +require('../test/mocha/props.js'); +require('../test/mocha/q_all.js'); +require('../test/mocha/q_done.js'); +require('../test/mocha/q_fin.js'); +require('../test/mocha/q_inspect.js'); +require('../test/mocha/q_make_node_resolver.js'); +require('../test/mocha/q_nodeify.js'); +require('../test/mocha/q_progress.js'); +require('../test/mocha/q_propagation.js'); +require('../test/mocha/q_settle.js'); +require('../test/mocha/q_spread.js'); +require('../test/mocha/race.js'); +require('../test/mocha/reduce.js'); +require('../test/mocha/reflect.js'); +require('../test/mocha/resolution.js'); +require('../test/mocha/reused_promise.js'); +require('../test/mocha/schedule.js'); +require('../test/mocha/some.js'); +require('../test/mocha/tap.js'); +require('../test/mocha/timers.js'); +require('../test/mocha/try.js'); +require('../test/mocha/unhandled_rejections.js'); +require('../test/mocha/using.js'); +require('../test/mocha/when_all.js'); +require('../test/mocha/when_any.js'); +require('../test/mocha/when_defer.js'); +require('../test/mocha/when_join.js'); +require('../test/mocha/when_map.js'); +require('../test/mocha/when_reduce.js'); +require('../test/mocha/when_settle.js'); +require('../test/mocha/when_some.js'); +require('../test/mocha/when_spread.js'); + + +window.onload = function(){ + var runner = mocha.run(); + + var failedTests = []; + runner.on('end', function(){ + window.mochaResults = runner.stats; + window.mochaResults.reports = failedTests; + }); + + runner.on('fail', logFailure); + + function logFailure(test, err) { + + var flattenTitles = function(test){ + var titles = []; + while (test.parent.title){ + titles.push(test.parent.title); + test = test.parent; + } + return titles.reverse(); + }; + + failedTests.push({name: test.title, result: false, message: err.message, stack: err.stack, titles: flattenTitles(test) }); + } +}; diff --git a/browser/mocha.css b/browser/mocha.css index 7cfae5595..42b9798fa 100644 --- a/browser/mocha.css +++ b/browser/mocha.css @@ -1,35 +1,16 @@ -/* -(The MIT License) - -Copyright (c) 2011-2013 TJ Holowaychuk - -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. -*/ - -@charset "UTF-8"; +@charset "utf-8"; + body { + margin:0; +} + +#mocha { font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; - padding: 60px 50px; + margin: 60px 50px; } -#mocha ul, #mocha li { +#mocha ul, +#mocha li { margin: 0; padding: 0; } @@ -38,7 +19,8 @@ body { list-style: none; } -#mocha h1, #mocha h2 { +#mocha h1, +#mocha h2 { margin: 0; } @@ -62,6 +44,10 @@ body { font-size: .8em; } +#mocha .hidden { + display: none; +} + #mocha h2 { font-size: 12px; font-weight: normal; @@ -74,33 +60,24 @@ body { #mocha .test { margin-left: 15px; -} - -#mocha .test:hover h2::after { - position: relative; - top: 0; - right: -10px; - content: '(view source)'; - font-size: 12px; - font-family: arial; - color: #888; + overflow: hidden; } #mocha .test.pending:hover h2::after { content: '(pending)'; - font-family: arial; + font-family: arial, sans-serif; } #mocha .test.pass.medium .duration { - background: #C09853; + background: #c09853; } #mocha .test.pass.slow .duration { - background: #B94A48; + background: #b94a48; } #mocha .test.pass::before { - content: '?'; + content: '✓'; font-size: 12px; display: block; float: left; @@ -112,7 +89,7 @@ body { font-size: 9px; margin-left: 5px; padding: 2px 5px; - color: white; + color: #fff; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); box-shadow: inset 0 1px 1px rgba(0,0,0,.2); @@ -132,7 +109,7 @@ body { } #mocha .test.pending::before { - content: '?'; + content: '◦'; color: #0b97c4; } @@ -145,7 +122,7 @@ body { } #mocha .test.fail::before { - content: '?'; + content: '✖'; font-size: 12px; display: block; float: left; @@ -155,30 +132,83 @@ body { #mocha .test pre.error { color: #c00; + max-height: 300px; + overflow: auto; } +/** + * (1): approximate for browsers not supporting calc + * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border) + * ^^ seriously + */ #mocha .test pre { - display: inline-block; + display: block; + float: left; + clear: left; font: 12px/1.5 monaco, monospace; margin: 5px; padding: 15px; border: 1px solid #eee; + max-width: 85%; /*(1)*/ + max-width: calc(100% - 42px); /*(2)*/ + word-wrap: break-word; border-bottom-color: #ddd; -webkit-border-radius: 3px; -webkit-box-shadow: 0 1px 3px #eee; + -moz-border-radius: 3px; + -moz-box-shadow: 0 1px 3px #eee; + border-radius: 3px; +} + +#mocha .test h2 { + position: relative; } -#report.pass .test.fail { +#mocha .test a.replay { + position: absolute; + top: 3px; + right: 0; + text-decoration: none; + vertical-align: middle; + display: block; + width: 15px; + height: 15px; + line-height: 15px; + text-align: center; + background: #eee; + font-size: 15px; + -moz-border-radius: 15px; + border-radius: 15px; + -webkit-transition: opacity 200ms; + -moz-transition: opacity 200ms; + transition: opacity 200ms; + opacity: 0.3; + color: #888; +} + +#mocha .test:hover a.replay { + opacity: 1; +} + +#mocha-report.pass .test.fail { display: none; } -#report.fail .test.pass { +#mocha-report.fail .test.pass { display: none; } -#error { +#mocha-report.pending .test.pass, +#mocha-report.pending .test.fail { + display: none; +} +#mocha-report.pending .test.pass.pending { + display: block; +} + +#mocha-error { color: #c00; - font-size: 1.5 em; + font-size: 1.5em; font-weight: 100; letter-spacing: 1px; } @@ -190,6 +220,7 @@ body { font-size: 12px; margin: 0; color: #888; + z-index: 1; } #mocha-stats .progress { @@ -217,8 +248,23 @@ body { padding-top: 11px; } -code .comment { color: #ddd } -code .init { color: #2F6FAD } -code .string { color: #5890AD } -code .keyword { color: #8A6343 } -code .number { color: #2F6FAD } +#mocha-stats canvas { + width: 40px; + height: 40px; +} + +#mocha code .comment { color: #ddd; } +#mocha code .init { color: #2f6fad; } +#mocha code .string { color: #5890ad; } +#mocha code .keyword { color: #8a6343; } +#mocha code .number { color: #2f6fad; } + +@media screen and (max-device-width: 480px) { + #mocha { + margin: 60px 0px; + } + + #mocha #stats { + position: absolute; + } +} diff --git a/browser/mocha.js b/browser/mocha.js index 0d229dc76..564a4f318 100644 --- a/browser/mocha.js +++ b/browser/mocha.js @@ -1,31 +1,5 @@ -/* -(The MIT License) - -Copyright (c) 2011-2013 TJ Holowaychuk - -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(){ - // CommonJS require() function require(p){ @@ -74,20 +48,387 @@ require.relative = function (parent) { require.register("browser/debug.js", function(module, exports, require){ - module.exports = function(type){ return function(){ - } }; + }); // module: browser/debug.js require.register("browser/diff.js", function(module, exports, require){ +/* See LICENSE file for terms of use */ + +/* + * Text diff implementation. + * + * This library supports the following APIS: + * JsDiff.diffChars: Character by character diff + * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * JsDiff.diffLines: Line based diff + * + * JsDiff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ +var JsDiff = (function() { + /*jshint maxparams: 5*/ + function clonePath(path) { + return { newPos: path.newPos, components: path.components.slice(0) }; + } + function removeEmpty(array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + } + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + + return n; + } + + var Diff = function(ignoreWhitespace) { + this.ignoreWhitespace = ignoreWhitespace; + }; + Diff.prototype = { + diff: function(oldString, newString) { + // Handle the identity case (this is due to unrolling editLength == 0 + if (newString === oldString) { + return [{ value: newString }]; + } + if (!newString) { + return [{ value: oldString, removed: true }]; + } + if (!oldString) { + return [{ value: newString, added: true }]; + } + + newString = this.tokenize(newString); + oldString = this.tokenize(oldString); + + var newLen = newString.length, oldLen = oldString.length; + var maxEditLength = newLen + oldLen; + var bestPath = [{ newPos: -1, components: [] }]; + + // Seed editLength = 0 + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { + return bestPath[0].components; + } + + for (var editLength = 1; editLength <= maxEditLength; editLength++) { + for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { + var basePath; + var addPath = bestPath[diagonalPath-1], + removePath = bestPath[diagonalPath+1]; + oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath-1] = undefined; + } + + var canAdd = addPath && addPath.newPos+1 < newLen; + var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = undefined; + continue; + } + + // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { + basePath = clonePath(removePath); + this.pushComponent(basePath.components, oldString[oldPos], undefined, true); + } else { + basePath = clonePath(addPath); + basePath.newPos++; + this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); + } + + var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); + + if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { + return basePath.components; + } else { + bestPath[diagonalPath] = basePath; + } + } + } + }, + + pushComponent: function(components, value, added, removed) { + var last = components[components.length-1]; + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length-1] = + {value: this.join(last.value, value), added: added, removed: removed }; + } else { + components.push({value: value, added: added, removed: removed }); + } + }, + extractCommon: function(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath; + while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { + newPos++; + oldPos++; + + this.pushComponent(basePath.components, newString[newPos], undefined, undefined); + } + basePath.newPos = newPos; + return oldPos; + }, + + equals: function(left, right) { + var reWhitespace = /\S/; + if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { + return true; + } else { + return left === right; + } + }, + join: function(left, right) { + return left + right; + }, + tokenize: function(value) { + return value; + } + }; + + var CharDiff = new Diff(); + + var WordDiff = new Diff(true); + var WordWithSpaceDiff = new Diff(); + WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { + return removeEmpty(value.split(/(\s+|\b)/)); + }; + + var CssDiff = new Diff(true); + CssDiff.tokenize = function(value) { + return removeEmpty(value.split(/([{}:;,]|\s+)/)); + }; + + var LineDiff = new Diff(); + LineDiff.tokenize = function(value) { + return value.split(/^/m); + }; + + return { + Diff: Diff, + + diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, + diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, + diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, + diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, + + diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, + + createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { + var ret = []; + + ret.push('Index: ' + fileName); + ret.push('==================================================================='); + ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); + ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); + + var diff = LineDiff.diff(oldStr, newStr); + if (!diff[diff.length-1].value) { + diff.pop(); // Remove trailing newline add + } + diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function(entry) { return ' ' + entry; }); + } + function eofNL(curRange, i, current) { + var last = diff[diff.length-2], + isLast = i === diff.length-2, + isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); + + // Figure out if this is the last line for the given file and missing NL + if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { + curRange.push('\\ No newline at end of file'); + } + } + + var oldRangeStart = 0, newRangeStart = 0, curRange = [], + oldLine = 1, newLine = 1; + for (var i = 0; i < diff.length; i++) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + if (!oldRangeStart) { + var prev = diff[i-1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = contextLines(prev.lines.slice(-4)); + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); + eofNL(curRange, i, current); + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= 8 && i < diff.length-2) { + // Overlapping + curRange.push.apply(curRange, contextLines(lines)); + } else { + // end the range and output + var contextSize = Math.min(lines.length, 4); + ret.push( + '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) + + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) + + ' @@'); + ret.push.apply(ret, curRange); + ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); + if (lines.length <= 4) { + eofNL(ret, i, current); + } + + oldRangeStart = 0; newRangeStart = 0; curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; + } + } + + return ret.join('\n') + '\n'; + }, + + applyPatch: function(oldStr, uniDiff) { + var diffstr = uniDiff.split('\n'); + var diff = []; + var remEOFNL = false, + addEOFNL = false; + + for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { + if(diffstr[i][0] === '@') { + var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); + diff.unshift({ + start:meh[3], + oldlength:meh[2], + oldlines:[], + newlength:meh[4], + newlines:[] + }); + } else if(diffstr[i][0] === '+') { + diff[0].newlines.push(diffstr[i].substr(1)); + } else if(diffstr[i][0] === '-') { + diff[0].oldlines.push(diffstr[i].substr(1)); + } else if(diffstr[i][0] === ' ') { + diff[0].newlines.push(diffstr[i].substr(1)); + diff[0].oldlines.push(diffstr[i].substr(1)); + } else if(diffstr[i][0] === '\\') { + if (diffstr[i-1][0] === '+') { + remEOFNL = true; + } else if(diffstr[i-1][0] === '-') { + addEOFNL = true; + } + } + } + + var str = oldStr.split('\n'); + for (var i = diff.length - 1; i >= 0; i--) { + var d = diff[i]; + for (var j = 0; j < d.oldlength; j++) { + if(str[d.start-1+j] !== d.oldlines[j]) { + return false; + } + } + Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); + } + + if (remEOFNL) { + while (!str[str.length-1]) { + str.pop(); + } + } else if (addEOFNL) { + str.push(''); + } + return str.join('\n'); + }, + + convertChangesToXML: function(changes){ + var ret = []; + for ( var i = 0; i < changes.length; i++) { + var change = changes[i]; + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + return ret.join(''); + }, + + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + convertChangesToDMP: function(changes){ + var ret = [], change; + for ( var i = 0; i < changes.length; i++) { + change = changes[i]; + ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); + } + return ret; + } + }; +})(); + +if (typeof module !== 'undefined') { + module.exports = JsDiff; +} }); // module: browser/diff.js -require.register("browser/events.js", function(module, exports, require){ +require.register("browser/escape-string-regexp.js", function(module, exports, require){ +'use strict'; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +}; + +}); // module: browser/escape-string-regexp.js + +require.register("browser/events.js", function(module, exports, require){ /** * Module exports. */ @@ -265,18 +606,22 @@ EventEmitter.prototype.emit = function (name) { return true; }; + }); // module: browser/events.js require.register("browser/fs.js", function(module, exports, require){ }); // module: browser/fs.js +require.register("browser/glob.js", function(module, exports, require){ + +}); // module: browser/glob.js + require.register("browser/path.js", function(module, exports, require){ }); // module: browser/path.js require.register("browser/progress.js", function(module, exports, require){ - /** * Expose `Progress`. */ @@ -365,58 +710,63 @@ Progress.prototype.update = function(n){ */ Progress.prototype.draw = function(ctx){ - var percent = Math.min(this.percent, 100) - , size = this._size - , half = size / 2 - , x = half - , y = half - , rad = half - 1 - , fontSize = this._fontSize; - - ctx.font = fontSize + 'px ' + this._font; - - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); - - // outer circle - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); - - // inner circle - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); - - // text - var text = this._text || (percent | 0) + '%' - , w = ctx.measureText(text).width; - - ctx.fillText( - text - , x - w / 2 + 1 - , y + fontSize / 2 - 1); - + try { + var percent = Math.min(this.percent, 100) + , size = this._size + , half = size / 2 + , x = half + , y = half + , rad = half - 1 + , fontSize = this._fontSize; + + ctx.font = fontSize + 'px ' + this._font; + + var angle = Math.PI * 2 * (percent / 100); + ctx.clearRect(0, 0, size, size); + + // outer circle + ctx.strokeStyle = '#9f9f9f'; + ctx.beginPath(); + ctx.arc(x, y, rad, 0, angle, false); + ctx.stroke(); + + // inner circle + ctx.strokeStyle = '#eee'; + ctx.beginPath(); + ctx.arc(x, y, rad - 1, 0, angle, true); + ctx.stroke(); + + // text + var text = this._text || (percent | 0) + '%' + , w = ctx.measureText(text).width; + + ctx.fillText( + text + , x - w / 2 + 1 + , y + fontSize / 2 - 1); + } catch (ex) {} //don't fail if we can't render progress return this; }; }); // module: browser/progress.js require.register("browser/tty.js", function(module, exports, require){ - exports.isatty = function(){ return true; }; exports.getWindowSize = function(){ - return [window.innerHeight, window.innerWidth]; + if ('innerHeight' in global) { + return [global.innerHeight, global.innerWidth]; + } else { + // In a Web Worker, the DOM Window is not available. + return [640, 480]; + } }; + }); // module: browser/tty.js require.register("context.js", function(module, exports, require){ - /** * Expose `Context`. */ @@ -454,10 +804,38 @@ Context.prototype.runnable = function(runnable){ */ Context.prototype.timeout = function(ms){ + if (arguments.length === 0) return this.runnable().timeout(); this.runnable().timeout(ms); return this; }; +/** + * Set test timeout `enabled`. + * + * @param {Boolean} enabled + * @return {Context} self + * @api private + */ + +Context.prototype.enableTimeouts = function (enabled) { + this.runnable().enableTimeouts(enabled); + return this; +}; + + +/** + * Set test slowness threshold `ms`. + * + * @param {Number} ms + * @return {Context} self + * @api private + */ + +Context.prototype.slow = function(ms){ + this.runnable().slow(ms); + return this; +}; + /** * Inspect the context void of `._runnable`. * @@ -476,7 +854,6 @@ Context.prototype.inspect = function(){ }); // module: context.js require.register("hook.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -506,7 +883,9 @@ function Hook(title, fn) { * Inherit from `Runnable.prototype`. */ -Hook.prototype = new Runnable; +function F(){}; +F.prototype = Runnable.prototype; +Hook.prototype = new F; Hook.prototype.constructor = Hook; @@ -528,17 +907,17 @@ Hook.prototype.error = function(err){ this._error = err; }; - }); // module: hook.js require.register("interfaces/bdd.js", function(module, exports, require){ - /** * Module dependencies. */ var Suite = require('../suite') - , Test = require('../test'); + , Test = require('../test') + , utils = require('../utils') + , escapeRe = require('browser/escape-string-regexp'); /** * BDD-style interface: @@ -560,65 +939,79 @@ var Suite = require('../suite') module.exports = function(suite){ var suites = [suite]; - suite.on('pre-require', function(context){ + suite.on('pre-require', function(context, file, mocha){ /** * Execute before running tests. */ - context.before = function(fn){ - suites[0].beforeAll(fn); + context.before = function(name, fn){ + suites[0].beforeAll(name, fn); }; /** * Execute after running tests. */ - context.after = function(fn){ - suites[0].afterAll(fn); + context.after = function(name, fn){ + suites[0].afterAll(name, fn); }; /** * Execute before each test case. */ - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); + context.beforeEach = function(name, fn){ + suites[0].beforeEach(name, fn); }; /** * Execute after each test case. */ - context.afterEach = function(fn){ - suites[0].afterEach(fn); + context.afterEach = function(name, fn){ + suites[0].afterEach(name, fn); }; /** - * Pending describe. + * Describe a "suite" with the given `title` + * and callback `fn` containing nested suites + * and/or tests. */ - context.xdescribe = context.xcontext = function(title, fn){ + context.describe = context.context = function(title, fn){ var suite = Suite.create(suites[0], title); - suite.pending = true; + suite.file = file; suites.unshift(suite); - fn(); + fn.call(suite); suites.shift(); + return suite; }; /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. + * Pending describe. */ - context.describe = context.context = function(title, fn){ + context.xdescribe = + context.xcontext = + context.describe.skip = function(title, fn){ var suite = Suite.create(suites[0], title); + suite.pending = true; suites.unshift(suite); - fn(); + fn.call(suite); suites.shift(); }; + /** + * Exclusive suite. + */ + + context.describe.only = function(title, fn){ + var suite = context.describe(title, fn); + mocha.grep(suite.fullTitle()); + return suite; + }; + /** * Describe a specification or test-case * with the given `title` and callback `fn` @@ -627,15 +1020,31 @@ module.exports = function(suite){ context.it = context.specify = function(title, fn){ var suite = suites[0]; - if (suite.pending) var fn = null; - suite.addTest(new Test(title, fn)); + if (suite.pending) fn = null; + var test = new Test(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.it.only = function(title, fn){ + var test = context.it(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); + return test; }; /** * Pending test case. */ - context.xit = context.xspecify = function(title){ + context.xit = + context.xspecify = + context.it.skip = function(title){ context.it(title); }; }); @@ -644,7 +1053,6 @@ module.exports = function(suite){ }); // module: interfaces/bdd.js require.register("interfaces/exports.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -674,7 +1082,7 @@ module.exports = function(suite){ suite.on('require', visit); - function visit(obj) { + function visit(obj, file) { var suite; for (var key in obj) { if ('function' == typeof obj[key]) { @@ -693,10 +1101,12 @@ module.exports = function(suite){ suites[0].afterEach(fn); break; default: - suites[0].addTest(new Test(key, fn)); + var test = new Test(key, fn); + test.file = file; + suites[0].addTest(test); } } else { - var suite = Suite.create(suites[0], key); + suite = Suite.create(suites[0], key); suites.unshift(suite); visit(obj[key]); suites.shift(); @@ -704,10 +1114,10 @@ module.exports = function(suite){ } } }; + }); // module: interfaces/exports.js require.register("interfaces/index.js", function(module, exports, require){ - exports.bdd = require('./bdd'); exports.tdd = require('./tdd'); exports.qunit = require('./qunit'); @@ -716,13 +1126,14 @@ exports.exports = require('./exports'); }); // module: interfaces/index.js require.register("interfaces/qunit.js", function(module, exports, require){ - /** * Module dependencies. */ var Suite = require('../suite') - , Test = require('../test'); + , Test = require('../test') + , escapeRe = require('browser/escape-string-regexp') + , utils = require('../utils'); /** * QUnit-style interface: @@ -752,38 +1163,38 @@ var Suite = require('../suite') module.exports = function(suite){ var suites = [suite]; - suite.on('pre-require', function(context){ + suite.on('pre-require', function(context, file, mocha){ /** * Execute before running tests. */ - context.before = function(fn){ - suites[0].beforeAll(fn); + context.before = function(name, fn){ + suites[0].beforeAll(name, fn); }; /** * Execute after running tests. */ - context.after = function(fn){ - suites[0].afterAll(fn); + context.after = function(name, fn){ + suites[0].afterAll(name, fn); }; /** * Execute before each test case. */ - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); + context.beforeEach = function(name, fn){ + suites[0].beforeEach(name, fn); }; /** * Execute after each test case. */ - context.afterEach = function(fn){ - suites[0].afterEach(fn); + context.afterEach = function(name, fn){ + suites[0].afterEach(name, fn); }; /** @@ -793,7 +1204,18 @@ module.exports = function(suite){ context.suite = function(title){ if (suites.length > 1) suites.shift(); var suite = Suite.create(suites[0], title); + suite.file = file; suites.unshift(suite); + return suite; + }; + + /** + * Exclusive test-case. + */ + + context.suite.only = function(title, fn){ + var suite = context.suite(title, fn); + mocha.grep(suite.fullTitle()); }; /** @@ -803,7 +1225,28 @@ module.exports = function(suite){ */ context.test = function(title, fn){ - suites[0].addTest(new Test(title, fn)); + var test = new Test(title, fn); + test.file = file; + suites[0].addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn){ + var test = context.test(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); + }; + + /** + * Pending test case. + */ + + context.test.skip = function(title){ + context.test(title); }; }); }; @@ -811,13 +1254,14 @@ module.exports = function(suite){ }); // module: interfaces/qunit.js require.register("interfaces/tdd.js", function(module, exports, require){ - /** * Module dependencies. */ var Suite = require('../suite') - , Test = require('../test'); + , Test = require('../test') + , escapeRe = require('browser/escape-string-regexp') + , utils = require('../utils'); /** * TDD-style interface: @@ -847,38 +1291,38 @@ var Suite = require('../suite') module.exports = function(suite){ var suites = [suite]; - suite.on('pre-require', function(context){ + suite.on('pre-require', function(context, file, mocha){ /** * Execute before each test case. */ - context.setup = function(fn){ - suites[0].beforeEach(fn); + context.setup = function(name, fn){ + suites[0].beforeEach(name, fn); }; /** * Execute after each test case. */ - context.teardown = function(fn){ - suites[0].afterEach(fn); + context.teardown = function(name, fn){ + suites[0].afterEach(name, fn); }; /** * Execute before the suite. */ - context.suiteSetup = function(fn){ - suites[0].beforeAll(fn); + context.suiteSetup = function(name, fn){ + suites[0].beforeAll(name, fn); }; /** * Execute after the suite. */ - context.suiteTeardown = function(fn){ - suites[0].afterAll(fn); + context.suiteTeardown = function(name, fn){ + suites[0].afterAll(name, fn); }; /** @@ -889,11 +1333,33 @@ module.exports = function(suite){ context.suite = function(title, fn){ var suite = Suite.create(suites[0], title); + suite.file = file; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + return suite; + }; + + /** + * Pending suite. + */ + context.suite.skip = function(title, fn) { + var suite = Suite.create(suites[0], title); + suite.pending = true; suites.unshift(suite); - fn(); + fn.call(suite); suites.shift(); }; + /** + * Exclusive test-case. + */ + + context.suite.only = function(title, fn){ + var suite = context.suite(title, fn); + mocha.grep(suite.fullTitle()); + }; + /** * Describe a specification or test-case * with the given `title` and callback `fn` @@ -901,7 +1367,30 @@ module.exports = function(suite){ */ context.test = function(title, fn){ - suites[0].addTest(new Test(title, fn)); + var suite = suites[0]; + if (suite.pending) fn = null; + var test = new Test(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn){ + var test = context.test(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); + }; + + /** + * Pending test case. + */ + + context.test.skip = function(title){ + context.test(title); }; }); }; @@ -919,7 +1408,9 @@ require.register("mocha.js", function(module, exports, require){ * Module dependencies. */ -var path = require('browser/path'); +var path = require('browser/path') + , escapeRe = require('browser/escape-string-regexp') + , utils = require('./utils'); /** * Expose `Mocha`. @@ -927,11 +1418,21 @@ var path = require('browser/path'); exports = module.exports = Mocha; +/** + * To require local UIs and reporters when running in node. + */ + +if (typeof process !== 'undefined' && typeof process.cwd === 'function') { + var join = path.join + , cwd = process.cwd(); + module.paths.push(cwd, join(cwd, 'node_modules')); +} + /** * Expose internals. */ -exports.utils = require('./utils'); +exports.utils = utils; exports.interfaces = require('./interfaces'); exports.reporters = require('./reporters'); exports.Runnable = require('./runnable'); @@ -959,9 +1460,11 @@ function image(name) { * Options: * * - `ui` name "bdd", "tdd", "exports" etc - * - `reporter` reporter instance, defaults to `mocha.reporters.Dot` + * - `reporter` reporter instance, defaults to `mocha.reporters.spec` * - `globals` array of accepted globals * - `timeout` timeout in milliseconds + * - `bail` bail on the first test failure + * - `slow` milliseconds to wait before considering a test slow * - `ignoreLeaks` ignore global leaks * - `grep` string or regexp to filter tests with * @@ -976,10 +1479,42 @@ function Mocha(options) { this.grep(options.grep); this.suite = new exports.Suite('', new exports.Context); this.ui(options.ui); + this.bail(options.bail); this.reporter(options.reporter); - if (options.timeout) this.suite.timeout(options.timeout); + if (null != options.timeout) this.timeout(options.timeout); + this.useColors(options.useColors) + if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts); + if (options.slow) this.slow(options.slow); + + this.suite.on('pre-require', function (context) { + exports.afterEach = context.afterEach || context.teardown; + exports.after = context.after || context.suiteTeardown; + exports.beforeEach = context.beforeEach || context.setup; + exports.before = context.before || context.suiteSetup; + exports.describe = context.describe || context.suite; + exports.it = context.it || context.test; + exports.setup = context.setup || context.beforeEach; + exports.suiteSetup = context.suiteSetup || context.before; + exports.suiteTeardown = context.suiteTeardown || context.after; + exports.suite = context.suite || context.describe; + exports.teardown = context.teardown || context.afterEach; + exports.test = context.test || context.it; + }); } +/** + * Enable or disable bailing on the first failure. + * + * @param {Boolean} [bail] + * @api public + */ + +Mocha.prototype.bail = function(bail){ + if (0 == arguments.length) bail = true; + this.suite.bail(bail); + return this; +}; + /** * Add test `file`. * @@ -993,16 +1528,27 @@ Mocha.prototype.addFile = function(file){ }; /** - * Set reporter to `name`, defaults to "dot". + * Set reporter to `reporter`, defaults to "spec". * - * @param {String} name + * @param {String|Function} reporter name or constructor * @api public */ -Mocha.prototype.reporter = function(name){ - name = name || 'dot'; - this._reporter = require('./reporters/' + name); - if (!this._reporter) throw new Error('invalid reporter "' + name + '"'); +Mocha.prototype.reporter = function(reporter){ + if ('function' == typeof reporter) { + this._reporter = reporter; + } else { + reporter = reporter || 'spec'; + var _reporter; + try { _reporter = require('./reporters/' + reporter); } catch (err) {}; + if (!_reporter) try { _reporter = require(reporter); } catch (err) {}; + if (!_reporter && reporter === 'teamcity') + console.warn('The Teamcity reporter was moved to a package named ' + + 'mocha-teamcity-reporter ' + + '(https://npmjs.org/package/mocha-teamcity-reporter).'); + if (!_reporter) throw new Error('invalid reporter "' + reporter + '"'); + this._reporter = _reporter; + } return this; }; @@ -1016,6 +1562,7 @@ Mocha.prototype.reporter = function(name){ Mocha.prototype.ui = function(name){ name = name || 'bdd'; this._ui = exports.interfaces[name]; + if (!this._ui) try { this._ui = require(name); } catch (err) {}; if (!this._ui) throw new Error('invalid interface "' + name + '"'); this._ui = this._ui(this.suite); return this; @@ -1028,13 +1575,14 @@ Mocha.prototype.ui = function(name){ */ Mocha.prototype.loadFiles = function(fn){ + var self = this; var suite = this.suite; var pending = this.files.length; this.files.forEach(function(file){ file = path.resolve(file); - suite.emit('pre-require', global, file); - suite.emit('require', require(file), file); - suite.emit('post-require', global, file); + suite.emit('pre-require', global, file, self); + suite.emit('require', require(file), file, self); + suite.emit('post-require', global, file, self); --pending || (fn && fn()); }); }; @@ -1064,16 +1612,16 @@ Mocha.prototype._growl = function(runner, reporter) { }; /** - * Add regexp to grep for to the options object + * Add regexp to grep, if `re` is a string it is escaped. * - * @param {RegExp} or {String} re + * @param {RegExp|String} re * @return {Mocha} * @api public */ Mocha.prototype.grep = function(re){ this.options.grep = 'string' == typeof re - ? new RegExp(re) + ? new RegExp(escapeRe(re)) : re; return this; }; @@ -1093,12 +1641,25 @@ Mocha.prototype.invert = function(){ /** * Ignore global leaks. * + * @param {Boolean} ignore + * @return {Mocha} + * @api public + */ + +Mocha.prototype.ignoreLeaks = function(ignore){ + this.options.ignoreLeaks = !!ignore; + return this; +}; + +/** + * Enable global leak checking. + * * @return {Mocha} * @api public */ -Mocha.prototype.ignoreLeaks = function(){ - this.options.ignoreLeaks = true; +Mocha.prototype.checkLeaks = function(){ + this.options.ignoreLeaks = false; return this; }; @@ -1115,62 +1676,273 @@ Mocha.prototype.growl = function(){ }; /** - * Ignore `globals`. + * Ignore `globals` array or string. * - * @param {Array} globals + * @param {Array|String} globals * @return {Mocha} * @api public */ Mocha.prototype.globals = function(globals){ - this.options.globals = globals; + this.options.globals = (this.options.globals || []).concat(globals); return this; }; /** - * Run tests and invoke `fn()` when complete. + * Emit color output. * - * @param {Function} fn - * @return {Runner} + * @param {Boolean} colors + * @return {Mocha} * @api public */ -Mocha.prototype.run = function(fn){ - this.loadFiles(); - var suite = this.suite; - var options = this.options; - var runner = new exports.Runner(suite); - var reporter = new this._reporter(runner); - runner.ignoreLeaks = options.ignoreLeaks; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - return runner.run(fn); +Mocha.prototype.useColors = function(colors){ + this.options.useColors = arguments.length && colors != undefined + ? colors + : true; + return this; }; -}); // module: mocha.js - -require.register("reporters/base.js", function(module, exports, require){ - /** - * Module dependencies. + * Use inline diffs rather than +/-. + * + * @param {Boolean} inlineDiffs + * @return {Mocha} + * @api public */ -var tty = require('browser/tty') - , diff = require('browser/diff'); +Mocha.prototype.useInlineDiffs = function(inlineDiffs) { + this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined + ? inlineDiffs + : false; + return this; +}; /** - * Save timer references to avoid Sinon interfering (see GH-237). + * Set the timeout in milliseconds. + * + * @param {Number} timeout + * @return {Mocha} + * @api public */ -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; +Mocha.prototype.timeout = function(timeout){ + this.suite.timeout(timeout); + return this; +}; /** - * Check if both stdio streams are associated with a tty. + * Set slowness threshold in milliseconds. + * + * @param {Number} slow + * @return {Mocha} + * @api public + */ + +Mocha.prototype.slow = function(slow){ + this.suite.slow(slow); + return this; +}; + +/** + * Enable timeouts. + * + * @param {Boolean} enabled + * @return {Mocha} + * @api public + */ + +Mocha.prototype.enableTimeouts = function(enabled) { + this.suite.enableTimeouts(arguments.length && enabled !== undefined + ? enabled + : true); + return this +}; + +/** + * Makes all tests async (accepting a callback) + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.asyncOnly = function(){ + this.options.asyncOnly = true; + return this; +}; + +/** + * Disable syntax highlighting (in browser). + * @returns {Mocha} + * @api public + */ +Mocha.prototype.noHighlighting = function() { + this.options.noHighlighting = true; + return this; +}; + +/** + * Run tests and invoke `fn()` when complete. + * + * @param {Function} fn + * @return {Runner} + * @api public + */ + +Mocha.prototype.run = function(fn){ + if (this.files.length) this.loadFiles(); + var suite = this.suite; + var options = this.options; + options.files = this.files; + var runner = new exports.Runner(suite); + var reporter = new this._reporter(runner, options); + runner.ignoreLeaks = false !== options.ignoreLeaks; + runner.asyncOnly = options.asyncOnly; + if (options.grep) runner.grep(options.grep, options.invert); + if (options.globals) runner.globals(options.globals); + if (options.growl) this._growl(runner, reporter); + exports.reporters.Base.useColors = options.useColors; + exports.reporters.Base.inlineDiffs = options.useInlineDiffs; + return runner.run(fn); +}; + +}); // module: mocha.js + +require.register("ms.js", function(module, exports, require){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options){ + options = options || {}; + if ('string' == typeof val) return parse(val); + return options['long'] ? longFormat(val) : shortFormat(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 's': + return n * s; + case 'ms': + return n; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function shortFormat(ms) { + if (ms >= d) return Math.round(ms / d) + 'd'; + if (ms >= h) return Math.round(ms / h) + 'h'; + if (ms >= m) return Math.round(ms / m) + 'm'; + if (ms >= s) return Math.round(ms / s) + 's'; + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function longFormat(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) return; + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +}); // module: ms.js + +require.register("reporters/base.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var tty = require('browser/tty') + , diff = require('browser/diff') + , ms = require('../ms') + , utils = require('../utils'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date + , setTimeout = global.setTimeout + , setInterval = global.setInterval + , clearTimeout = global.clearTimeout + , clearInterval = global.clearInterval; + +/** + * Check if both stdio streams are associated with a tty. */ var isatty = tty.isatty(1) && tty.isatty(2); @@ -1185,7 +1957,13 @@ exports = module.exports = Base; * Enable coloring by default. */ -exports.useColors = isatty; +exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined); + +/** + * Inline diffs instead of +/- + */ + +exports.inlineDiffs = false; /** * Default color map. @@ -1213,6 +1991,23 @@ exports.colors = { , 'diff removed': 41 }; +/** + * Default symbol map. + */ + +exports.symbols = { + ok: '✓', + err: '✖', + dot: '․' +}; + +// With node.js on Windows: use symbols available in terminal default fonts +if ('win32' == process.platform) { + exports.symbols.ok = '\u221A'; + exports.symbols.err = '\u00D7'; + exports.symbols.dot = '.'; +} + /** * Color `str` with the given `type`, * allowing colors to be disabled, @@ -1250,34 +2045,31 @@ exports.window = { exports.cursor = { hide: function(){ - process.stdout.write('\u001b[?25l'); + isatty && process.stdout.write('\u001b[?25l'); }, show: function(){ - process.stdout.write('\u001b[?25h'); + isatty && process.stdout.write('\u001b[?25h'); }, deleteLine: function(){ - process.stdout.write('\u001b[2K'); + isatty && process.stdout.write('\u001b[2K'); }, beginningOfLine: function(){ - process.stdout.write('\u001b[0G'); + isatty && process.stdout.write('\u001b[0G'); }, CR: function(){ - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); + if (isatty) { + exports.cursor.deleteLine(); + exports.cursor.beginningOfLine(); + } else { + process.stdout.write('\r'); + } } }; -/** - * A test is considered slow if it - * exceeds the following value in milliseconds. - */ - -exports.slow = 75; - /** * Outut the given `failures` as a list. * @@ -1300,38 +2092,32 @@ exports.list = function(failures){ , index = stack.indexOf(message) + message.length , msg = stack.slice(0, index) , actual = err.actual - , expected = err.expected; + , expected = err.expected + , escape = true; - // actual / expected diff - if ('string' == typeof actual && 'string' == typeof expected) { - var len = Math.max(actual.length, expected.length); - - if (len < 20) msg = errorDiff(err, 'Chars'); - else msg = errorDiff(err, 'Words'); - - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } + // uncaught + if (err.uncaught) { + msg = 'Uncaught ' + msg; + } - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; + // explicitly show diff + if (err.showDiff && sameType(actual, expected)) { + escape = false; + err.actual = actual = utils.stringify(actual); + err.expected = expected = utils.stringify(expected); + } - // indent - msg = msg.replace(/^/gm, ' '); + // actual / expected diff + if (err.showDiff && 'string' == typeof actual && 'string' == typeof expected) { + fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); + var match = message.match(/^([^:]+): expected/); + msg = '\n ' + color('error message', match ? match[1] : msg); - fmt = color('error title', ' %s) %s:\n%s') - + color('error stack', '\n%s\n'); + if (exports.inlineDiffs) { + msg += inlineDiff(err, escape); + } else { + msg += unifiedDiff(err, escape); + } } // indent stack trace without msg @@ -1362,6 +2148,8 @@ function Base(runner) { if (!runner) return; this.runner = runner; + runner.stats = stats; + runner.on('start', function(){ stats.start = new Date; }); @@ -1379,8 +2167,8 @@ function Base(runner) { runner.on('pass', function(test){ stats.passes = stats.passes || 0; - var medium = exports.slow / 2; - test.speed = test.duration > exports.slow + var medium = test.slow() / 2; + test.speed = test.duration > test.slow() ? 'slow' : test.duration > medium ? 'medium' @@ -1414,48 +2202,38 @@ function Base(runner) { */ Base.prototype.epilogue = function(){ - var stats = this.stats - , fmt - , tests; + var stats = this.stats; + var tests; + var fmt; console.log(); - function pluralize(n) { - return 1 == n ? 'test' : 'tests'; + // passes + fmt = color('bright pass', ' ') + + color('green', ' %d passing') + + color('light', ' (%s)'); + + console.log(fmt, + stats.passes || 0, + ms(stats.duration)); + + // pending + if (stats.pending) { + fmt = color('pending', ' ') + + color('pending', ' %d pending'); + + console.log(fmt, stats.pending); } - // failure + // failures if (stats.failures) { - fmt = color('bright fail', ' ?') - + color('fail', ' %d of %d %s failed') - + color('light', ':') + fmt = color('fail', ' %d failing'); console.error(fmt, - stats.failures, - this.runner.total, - pluralize(this.runner.total)); + stats.failures); Base.list(this.failures); console.error(); - return; - } - - // pass - fmt = color('bright pass', ' ?') - + color('green', ' %d %s complete') - + color('light', ' (%dms)'); - - console.log(fmt, - stats.tests || 0, - pluralize(stats.tests), - stats.duration); - - // pending - if (stats.pending) { - fmt = color('pending', ' •') - + color('pending', ' %d %s pending'); - - console.log(fmt, stats.pending, pluralize(stats.pending)); } console.log(); @@ -1475,6 +2253,73 @@ function pad(str, len) { return Array(len - str.length + 1).join(' ') + str; } + +/** + * Returns an inline diff between 2 strings with coloured ANSI output + * + * @param {Error} Error with actual/expected + * @return {String} Diff + * @api private + */ + +function inlineDiff(err, escape) { + var msg = errorDiff(err, 'WordsWithSpace', escape); + + // linenos + var lines = msg.split('\n'); + if (lines.length > 4) { + var width = String(lines.length).length; + msg = lines.map(function(str, i){ + return pad(++i, width) + ' |' + ' ' + str; + }).join('\n'); + } + + // legend + msg = '\n' + + color('diff removed', 'actual') + + ' ' + + color('diff added', 'expected') + + '\n\n' + + msg + + '\n'; + + // indent + msg = msg.replace(/^/gm, ' '); + return msg; +} + +/** + * Returns a unified diff between 2 strings + * + * @param {Error} Error with actual/expected + * @return {String} Diff + * @api private + */ + +function unifiedDiff(err, escape) { + var indent = ' '; + function cleanUp(line) { + if (escape) { + line = escapeInvisibles(line); + } + if (line[0] === '+') return indent + colorLines('diff added', line); + if (line[0] === '-') return indent + colorLines('diff removed', line); + if (line.match(/\@\@/)) return null; + if (line.match(/\\ No newline/)) return null; + else return indent + line; + } + function notBlank(line) { + return line != null; + } + msg = diff.createPatch('string', err.actual, err.expected); + var lines = msg.split('\n').splice(4); + return '\n ' + + colorLines('diff added', '+ expected') + ' ' + + colorLines('diff removed', '- actual') + + '\n\n' + + lines.map(cleanUp).filter(notBlank).join('\n'); +} + /** * Return a character diff for `err`. * @@ -1483,15 +2328,29 @@ function pad(str, len) { * @api private */ -function errorDiff(err, type) { - return diff['diff' + type](err.actual, err.expected).map(function(str){ - if (/^(\n+)$/.test(str.value)) str.value = Array(++RegExp.$1.length).join(''); +function errorDiff(err, type, escape) { + var actual = escape ? escapeInvisibles(err.actual) : err.actual; + var expected = escape ? escapeInvisibles(err.expected) : err.expected; + return diff['diff' + type](actual, expected).map(function(str){ if (str.added) return colorLines('diff added', str.value); if (str.removed) return colorLines('diff removed', str.value); return str.value; }).join(''); } +/** + * Returns a string with all invisible characters in plain text + * + * @param {String} line + * @return {String} + * @api private + */ +function escapeInvisibles(line) { + return line.replace(/\t/g, '') + .replace(/\r/g, '') + .replace(/\n/g, '\n'); +} + /** * Color lines for `str`, using the color `name`. * @@ -1507,10 +2366,24 @@ function colorLines(name, str) { }).join('\n'); } +/** + * Check that a / b have the same type. + * + * @param {Object} a + * @param {Object} b + * @return {Boolean} + * @api private + */ + +function sameType(a, b) { + a = Object.prototype.toString.call(a); + b = Object.prototype.toString.call(b); + return a == b; +} + }); // module: reporters/base.js require.register("reporters/doc.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -1548,7 +2421,7 @@ function Doc(runner) { ++indents; console.log('%s
', indent()); ++indents; - console.log('%s

%s

', indent(), suite.title); + console.log('%s

%s

', indent(), utils.escape(suite.title)); console.log('%s
', indent()); }); @@ -1561,16 +2434,22 @@ function Doc(runner) { }); runner.on('pass', function(test){ - console.log('%s
%s
', indent(), test.title); + console.log('%s
%s
', indent(), utils.escape(test.title)); var code = utils.escape(utils.clean(test.fn.toString())); console.log('%s
%s
', indent(), code); }); + + runner.on('fail', function(test, err){ + console.log('%s
%s
', indent(), utils.escape(test.title)); + var code = utils.escape(utils.clean(test.fn.toString())); + console.log('%s
%s
', indent(), code); + console.log('%s
%s
', indent(), utils.escape(err)); + }); } }); // module: reporters/doc.js require.register("reporters/dot.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -1597,29 +2476,29 @@ function Dot(runner) { var self = this , stats = this.stats , width = Base.window.width * .75 | 0 - , c = '?' - , n = 0; + , n = -1; runner.on('start', function(){ process.stdout.write('\n '); }); runner.on('pending', function(test){ - process.stdout.write(color('pending', c)); + if (++n % width == 0) process.stdout.write('\n '); + process.stdout.write(color('pending', Base.symbols.dot)); }); runner.on('pass', function(test){ if (++n % width == 0) process.stdout.write('\n '); if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', c)); + process.stdout.write(color('bright yellow', Base.symbols.dot)); } else { - process.stdout.write(color(test.speed, c)); + process.stdout.write(color(test.speed, Base.symbols.dot)); } }); runner.on('fail', function(test, err){ if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', c)); + process.stdout.write(color('fail', Base.symbols.dot)); }); runner.on('end', function(){ @@ -1632,13 +2511,15 @@ function Dot(runner) { * Inherit from `Base.prototype`. */ -Dot.prototype = new Base; +function F(){}; +F.prototype = Base.prototype; +Dot.prototype = new F; Dot.prototype.constructor = Dot; + }); // module: reporters/dot.js require.register("reporters/html-cov.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -1689,10 +2570,10 @@ function coverageClass(n) { if (n >= 25) return 'low'; return 'terrible'; } + }); // module: reporters/html-cov.js require.register("reporters/html.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -1713,7 +2594,7 @@ var Date = global.Date , clearInterval = global.clearInterval; /** - * Expose `Doc`. + * Expose `HTML`. */ exports = module.exports = HTML; @@ -1723,14 +2604,14 @@ exports = module.exports = HTML; */ var statsTemplate = ''; /** - * Initialize a new `Doc` reporter. + * Initialize a new `HTML` reporter. * * @param {Runner} runner * @api public @@ -1742,7 +2623,6 @@ function HTML(runner) { var self = this , stats = this.stats , total = runner.total - , root = document.getElementById('mocha') , stat = fragment(statsTemplate) , items = stat.getElementsByTagName('li') , passes = items[1].getElementsByTagName('em')[0] @@ -1751,28 +2631,39 @@ function HTML(runner) { , failuresLink = items[2].getElementsByTagName('a')[0] , duration = items[3].getElementsByTagName('em')[0] , canvas = stat.getElementsByTagName('canvas')[0] - , report = fragment('
    ') + , report = fragment('
      ') , stack = [report] , progress , ctx - - if (canvas && canvas.getContext) { + , root = document.getElementById('mocha'); + + if (canvas.getContext) { + var ratio = window.devicePixelRatio || 1; + canvas.style.width = canvas.width; + canvas.style.height = canvas.height; + canvas.width *= ratio; + canvas.height *= ratio; ctx = canvas.getContext('2d'); + ctx.scale(ratio, ratio); progress = new Progress; } if (!root) return error('#mocha div missing, add it to your document'); // pass toggle - on(passesLink, 'click', function () { - var className = /pass/.test(report.className) ? '' : ' pass'; - report.className = report.className.replace(/fail|pass/g, '') + className; + on(passesLink, 'click', function(){ + unhide(); + var name = /pass/.test(report.className) ? '' : ' pass'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) hideSuitesWithout('test pass'); }); // failure toggle - on(failuresLink, 'click', function () { - var className = /fail/.test(report.className) ? '' : ' fail'; - report.className = report.className.replace(/fail|pass/g, '') + className; + on(failuresLink, 'click', function(){ + unhide(); + var name = /fail/.test(report.className) ? '' : ' fail'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) hideSuitesWithout('test fail'); }); root.appendChild(stat); @@ -1784,7 +2675,7 @@ function HTML(runner) { if (suite.root) return; // suite - var url = location.protocol + '//' + location.host + location.pathname + '?grep=^' + utils.escapeRegexp(suite.fullTitle()); + var url = self.suiteURL(suite); var el = fragment('
    • %s

    • ', url, escape(suite.title)); // container @@ -1799,14 +2690,12 @@ function HTML(runner) { }); runner.on('fail', function(test, err){ - if ('hook' == test.type || err.uncaught) runner.emit('test end', test); + if ('hook' == test.type) runner.emit('test end', test); }); runner.on('test end', function(test){ - window.scrollTo(0, document.body.scrollHeight); - // TODO: add to stats - var percent = stats.tests / total * 100 | 0; + var percent = stats.tests / this.total * 100 | 0; if (progress) progress.update(percent).draw(ctx); // update stats @@ -1817,11 +2706,12 @@ function HTML(runner) { // test if ('passed' == test.state) { - var el = fragment('
    • %e%ems

    • ', test.speed, test.title, test.duration); + var url = self.testURL(test); + var el = fragment('
    • %e%ems

    • ', test.speed, test.title, test.duration, url); } else if (test.pending) { var el = fragment('
    • %e

    • ', test.title); } else { - var el = fragment('
    • %e

    • ', test.title); + var el = fragment('
    • %e

    • ', test.title, encodeURIComponent(test.fullTitle())); var str = test.err.stack || test.err.toString(); // FF / Opera do not add the message @@ -1848,7 +2738,7 @@ function HTML(runner) { on(h2, 'click', function(){ pre.style.display = 'none' == pre.style.display - ? 'inline-block' + ? 'block' : 'none'; }); @@ -1857,16 +2747,46 @@ function HTML(runner) { pre.style.display = 'none'; } - stack[0].appendChild(el); + // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. + if (stack[0]) stack[0].appendChild(el); }); } +/** + * Makes a URL, preserving querystring ("search") parameters. + * @param {string} s + * @returns {string} your new URL + */ +var makeUrl = function makeUrl(s) { + var search = window.location.search; + return (search ? search + '&' : '?' ) + 'grep=' + encodeURIComponent(s); +}; + +/** + * Provide suite URL + * + * @param {Object} [suite] + */ +HTML.prototype.suiteURL = function(suite){ + return makeUrl(suite.fullTitle()); +}; + +/** + * Provide test URL + * + * @param {Object} [test] + */ + +HTML.prototype.testURL = function(test){ + return makeUrl(test.fullTitle()); +}; + /** * Display error `msg`. */ function error(msg) { - document.body.appendChild(fragment('
      %s
      ', msg)); + document.body.appendChild(fragment('
      %s
      ', msg)); } /** @@ -1888,6 +2808,30 @@ function fragment(html) { return div.firstChild; } +/** + * Check for suites that do not have elements + * with `classname`, and hide them. + */ + +function hideSuitesWithout(classname) { + var suites = document.getElementsByClassName('suite'); + for (var i = 0; i < suites.length; i++) { + var els = suites[i].getElementsByClassName(classname); + if (0 == els.length) suites[i].className += ' hidden'; + } +} + +/** + * Unhide .hidden suites. + */ + +function unhide() { + var els = document.getElementsByClassName('suite hidden'); + for (var i = 0; i < els.length; ++i) { + els[i].className = els[i].className.replace('suite hidden', 'suite'); + } +} + /** * Set `el` text to `str`. */ @@ -1915,7 +2859,6 @@ function on(el, event, fn) { }); // module: reporters/html.js require.register("reporters/index.js", function(module, exports, require){ - exports.Base = require('./base'); exports.Dot = require('./dot'); exports.Doc = require('./doc'); @@ -1927,17 +2870,16 @@ exports.Min = require('./min'); exports.Spec = require('./spec'); exports.Nyan = require('./nyan'); exports.XUnit = require('./xunit'); +exports.Markdown = require('./markdown'); exports.Progress = require('./progress'); exports.Landing = require('./landing'); exports.JSONCov = require('./json-cov'); exports.HTMLCov = require('./html-cov'); exports.JSONStream = require('./json-stream'); -exports.Teamcity = require('./teamcity'); }); // module: reporters/index.js require.register("reporters/json-cov.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -2019,12 +2961,16 @@ function map(cov) { ret.sloc += data.sloc; } + ret.files.sort(function(a, b) { + return a.filename.localeCompare(b.filename); + }); + if (ret.sloc > 0) { ret.coverage = (ret.hits / ret.sloc) * 100; } return ret; -}; +} /** * Map jscoverage data for a single source file @@ -2090,7 +3036,6 @@ function clean(test) { }); // module: reporters/json-cov.js require.register("reporters/json-stream.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -2127,7 +3072,9 @@ function List(runner) { }); runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); + test = clean(test); + test.err = err.message; + console.log(JSON.stringify(['fail', test])); }); runner.on('end', function(){ @@ -2151,10 +3098,10 @@ function clean(test) { , duration: test.duration } } + }); // module: reporters/json-stream.js require.register("reporters/json.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -2181,6 +3128,7 @@ function JSONReporter(runner) { Base.call(this, runner); var tests = [] + , pending = [] , failures = [] , passes = []; @@ -2196,14 +3144,21 @@ function JSONReporter(runner) { failures.push(test); }); + runner.on('pending', function(test){ + pending.push(test); + }); + runner.on('end', function(){ var obj = { - stats: self.stats - , tests: tests.map(clean) - , failures: failures.map(clean) - , passes: passes.map(clean) + stats: self.stats, + tests: tests.map(clean), + pending: pending.map(clean), + failures: failures.map(clean), + passes: passes.map(clean) }; + runner.testResults = obj; + process.stdout.write(JSON.stringify(obj, null, 2)); }); } @@ -2219,15 +3174,30 @@ function JSONReporter(runner) { function clean(test) { return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + err: errorJSON(test.err || {}) } } + +/** + * Transform `error` into a JSON object. + * @param {Error} err + * @return {Object} + */ + +function errorJSON(err) { + var res = {}; + Object.getOwnPropertyNames(err).forEach(function(key) { + res[key] = err[key]; + }, err); + return res; +} + }); // module: reporters/json.js require.register("reporters/landing.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -2275,7 +3245,7 @@ function Landing(runner) { , width = Base.window.width * .75 | 0 , total = runner.total , stream = process.stdout - , plane = color('plane', '?') + , plane = color('plane', '✈') , crashed = -1 , n = 0; @@ -2285,7 +3255,7 @@ function Landing(runner) { } runner.on('start', function(){ - stream.write('\n '); + stream.write('\n\n\n '); cursor.hide(); }); @@ -2297,17 +3267,17 @@ function Landing(runner) { // show the crash if ('failed' == test.state) { - plane = color('plane crash', '?'); + plane = color('plane crash', '✈'); crashed = col; } // render landing strip - stream.write('\u001b[4F\n\n'); + stream.write('\u001b['+(width+1)+'D\u001b[2A'); stream.write(runway()); stream.write('\n '); - stream.write(color('runway', Array(col).join('?'))); + stream.write(color('runway', Array(col).join('⋅'))); stream.write(plane) - stream.write(color('runway', Array(width - col).join('?') + '\n')); + stream.write(color('runway', Array(width - col).join('⋅') + '\n')); stream.write(runway()); stream.write('\u001b[0m'); }); @@ -2323,13 +3293,15 @@ function Landing(runner) { * Inherit from `Base.prototype`. */ -Landing.prototype = new Base; +function F(){}; +F.prototype = Base.prototype; +Landing.prototype = new F; Landing.prototype.constructor = Landing; + }); // module: reporters/landing.js require.register("reporters/list.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -2373,7 +3345,7 @@ function List(runner) { }); runner.on('pass', function(test){ - var fmt = color('checkmark', ' ?') + var fmt = color('checkmark', ' '+Base.symbols.dot) + color('pass', ' %s: ') + color(test.speed, '%dms'); cursor.CR(); @@ -2392,7 +3364,9 @@ function List(runner) { * Inherit from `Base.prototype`. */ -List.prototype = new Base; +function F(){}; +F.prototype = Base.prototype; +List.prototype = new F; List.prototype.constructor = List; @@ -2424,7 +3398,6 @@ function Markdown(runner) { var self = this , stats = this.stats - , total = runner.total , level = 0 , buf = ''; @@ -2469,7 +3442,7 @@ function Markdown(runner) { runner.on('suite', function(suite){ ++level; var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; + buf += '' + '\n'; buf += title(suite.title) + '\n'; }); @@ -2491,10 +3464,10 @@ function Markdown(runner) { process.stdout.write(buf); }); } + }); // module: reporters/markdown.js require.register("reporters/min.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -2531,13 +3504,15 @@ function Min(runner) { * Inherit from `Base.prototype`. */ -Min.prototype = new Base; +function F(){}; +F.prototype = Base.prototype; +Min.prototype = new F; Min.prototype.constructor = Min; + }); // module: reporters/min.js require.register("reporters/nyan.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -2560,7 +3535,6 @@ exports = module.exports = NyanCat; function NyanCat(runner) { Base.call(this, runner); - var self = this , stats = this.stats , width = Base.window.width * .75 | 0 @@ -2576,19 +3550,19 @@ function NyanCat(runner) { runner.on('start', function(){ Base.cursor.hide(); - self.draw('start'); + self.draw(); }); runner.on('pending', function(test){ - self.draw('pending'); + self.draw(); }); runner.on('pass', function(test){ - self.draw('pass'); + self.draw(); }); runner.on('fail', function(test, err){ - self.draw('fail'); + self.draw(); }); runner.on('end', function(){ @@ -2599,17 +3573,16 @@ function NyanCat(runner) { } /** - * Draw the nyan cat with runner `status`. + * Draw the nyan cat * - * @param {String} status * @api private */ -NyanCat.prototype.draw = function(status){ +NyanCat.prototype.draw = function(){ this.appendRainbow(); this.drawScoreboard(); this.drawRainbow(); - this.drawNyanCat(status); + this.drawNyanCat(); this.tick = !this.tick; }; @@ -2674,57 +3647,61 @@ NyanCat.prototype.drawRainbow = function(){ }; /** - * Draw the nyan cat with `status`. + * Draw the nyan cat * - * @param {String} status * @api private */ -NyanCat.prototype.drawNyanCat = function(status) { +NyanCat.prototype.drawNyanCat = function() { var self = this; var startWidth = this.scoreboardWidth + this.trajectories[0].length; + var color = '\u001b[' + startWidth + 'C'; + var padding = ''; - [0, 1, 2, 3].forEach(function(index) { - write('\u001b[' + startWidth + 'C'); - - switch (index) { - case 0: - write('_,------,'); - write('\n'); - break; - case 1: - var padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - break; - case 2: - var padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - switch (status) { - case 'pass': - face = '( ^ .^)'; - break; - case 'fail': - face = '( o .o)'; - break; - default: - face = '( - .-)'; - } - write(tail + '|' + padding + face + ' '); - write('\n'); - break; - case 3: - var padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - break; - } - }); + write(color); + write('_,------,'); + write('\n'); + + write(color); + padding = self.tick ? ' ' : ' '; + write('_|' + padding + '/\\_/\\ '); + write('\n'); + + write(color); + padding = self.tick ? '_' : '__'; + var tail = self.tick ? '~' : '^'; + var face; + write(tail + '|' + padding + this.face() + ' '); + write('\n'); + + write(color); + padding = self.tick ? ' ' : ' '; + write(padding + '"" "" '); + write('\n'); this.cursorUp(this.numberOfLines); }; +/** + * Draw nyan cat face. + * + * @return {String} + * @api private + */ + +NyanCat.prototype.face = function() { + var stats = this.stats; + if (stats.failures) { + return '( x .x)'; + } else if (stats.pending) { + return '( o .o)'; + } else if(stats.passes) { + return '( ^ .^)'; + } else { + return '( - .-)'; + } +}; + /** * Move cursor up `n`. * @@ -2795,14 +3772,15 @@ function write(string) { * Inherit from `Base.prototype`. */ -NyanCat.prototype = new Base; +function F(){}; +F.prototype = Base.prototype; +NyanCat.prototype = new F; NyanCat.prototype.constructor = NyanCat; }); // module: reporters/nyan.js require.register("reporters/progress.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -2840,12 +3818,13 @@ function Progress(runner, options) { , width = Base.window.width * .50 | 0 , total = runner.total , complete = 0 - , max = Math.max; + , max = Math.max + , lastN = -1; // default chars options.open = options.open || '['; - options.complete = options.complete || '?'; - options.incomplete = options.incomplete || '?'; + options.complete = options.complete || '▬'; + options.incomplete = options.incomplete || Base.symbols.dot; options.close = options.close || ']'; options.verbose = false; @@ -2863,6 +3842,12 @@ function Progress(runner, options) { , n = width * percent | 0 , i = width - n; + if (lastN === n && !options.verbose) { + // Don't re-render the line if it hasn't changed + return; + } + lastN = n; + cursor.CR(); process.stdout.write('\u001b[J'); process.stdout.write(color('progress', ' ' + options.open)); @@ -2887,14 +3872,15 @@ function Progress(runner, options) { * Inherit from `Base.prototype`. */ -Progress.prototype = new Base; +function F(){}; +F.prototype = Base.prototype; +Progress.prototype = new F; Progress.prototype.constructor = Progress; }); // module: reporters/progress.js require.register("reporters/spec.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -2942,10 +3928,6 @@ function Spec(runner) { if (1 == indents) console.log(); }); - runner.on('test', function(test){ - process.stdout.write(indent() + color('pass', ' ? ' + test.title + ': ')); - }); - runner.on('pending', function(test){ var fmt = indent() + color('pending', ' - %s'); console.log(fmt, test.title); @@ -2954,13 +3936,13 @@ function Spec(runner) { runner.on('pass', function(test){ if ('fast' == test.speed) { var fmt = indent() - + color('checkmark', ' ?') + + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s '); cursor.CR(); console.log(fmt, test.title); } else { var fmt = indent() - + color('checkmark', ' ?') + + color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s ') + color(test.speed, '(%dms)'); cursor.CR(); @@ -2980,14 +3962,15 @@ function Spec(runner) { * Inherit from `Base.prototype`. */ -Spec.prototype = new Base; +function F(){}; +F.prototype = Base.prototype; +Spec.prototype = new F; Spec.prototype.constructor = Spec; }); // module: reporters/spec.js require.register("reporters/tap.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -3014,10 +3997,12 @@ function TAP(runner) { var self = this , stats = this.stats - , total = runner.total - , n = 1; + , n = 1 + , passes = 0 + , failures = 0; runner.on('start', function(){ + var total = runner.grepTotal(runner.suite); console.log('%d..%d', 1, total); }); @@ -3030,13 +4015,20 @@ function TAP(runner) { }); runner.on('pass', function(test){ + passes++; console.log('ok %d %s', n, title(test)); }); runner.on('fail', function(test, err){ + failures++; console.log('not ok %d %s', n, title(test)); - console.log(err); - console.log(err.stack.replace(/^/gm, ' ')); + if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); + }); + + runner.on('end', function(){ + console.log('# tests ' + (passes + failures)); + console.log('# pass ' + passes); + console.log('# fail ' + failures); }); } @@ -3054,77 +4046,7 @@ function title(test) { }); // module: reporters/tap.js -require.register("reporters/teamcity.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Teamcity`. - */ - -exports = module.exports = Teamcity; - -/** - * Initialize a new `Teamcity` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Teamcity(runner) { - Base.call(this, runner); - var stats = this.stats; - - runner.on('start', function() { - console.log("##teamcity[testSuiteStarted name='mocha.suite']"); - }); - - runner.on('test', function(test) { - console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); - }); - - runner.on('fail', function(test, err) { - console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); - }); - - runner.on('pending', function(test) { - console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); - }); - - runner.on('test end', function(test) { - console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); - }); - - runner.on('end', function() { - console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); - }); -} - -/** - * Escape the given `str`. - */ - -function escape(str) { - return str - .replace(/\|/g, "||") - .replace(/\n/g, "|n") - .replace(/\r/g, "|r") - .replace(/\[/g, "|[") - .replace(/\]/g, "|]") - .replace(/\u0085/g, "|x") - .replace(/\u2028/g, "|l") - .replace(/\u2029/g, "|p") - .replace(/'/g, "|'"); -} - -}); // module: reporters/teamcity.js - require.register("reporters/xunit.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -3162,6 +4084,10 @@ function XUnit(runner) { , tests = [] , self = this; + runner.on('pending', function(test){ + tests.push(test); + }); + runner.on('pass', function(test){ tests.push(test); }); @@ -3176,9 +4102,9 @@ function XUnit(runner) { , tests: stats.tests , failures: stats.failures , errors: stats.failures - , skip: stats.tests - stats.failures - stats.passes + , skipped: stats.tests - stats.failures - stats.passes , timestamp: (new Date).toUTCString() - , time: stats.duration / 1000 + , time: (stats.duration / 1000) || 0 }, false)); tests.forEach(test); @@ -3190,7 +4116,9 @@ function XUnit(runner) { * Inherit from `Base.prototype`. */ -XUnit.prototype = new Base; +function F(){}; +F.prototype = Base.prototype; +XUnit.prototype = new F; XUnit.prototype.constructor = XUnit; @@ -3202,13 +4130,12 @@ function test(test) { var attrs = { classname: test.parent.fullTitle() , name: test.title - , time: test.duration / 1000 + , time: (test.duration / 1000) || 0 }; if ('failed' == test.state) { var err = test.err; - attrs.message = escape(err.message); - console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); + console.log(tag('testcase', attrs, false, tag('failure', {}, false, cdata(escape(err.message) + "\n" + err.stack)))); } else if (test.pending) { console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); } else { @@ -3245,13 +4172,13 @@ function cdata(str) { }); // module: reporters/xunit.js require.register("runnable.js", function(module, exports, require){ - /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runnable'); + , debug = require('browser/debug')('mocha:runnable') + , milliseconds = require('./ms'); /** * Save timer references to avoid Sinon interfering (see GH-237). @@ -3263,6 +4190,12 @@ var Date = global.Date , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; +/** + * Object#toString(). + */ + +var toString = Object.prototype.toString; + /** * Expose `Runnable`. */ @@ -3283,33 +4216,71 @@ function Runnable(title, fn) { this.async = fn && fn.length; this.sync = ! this.async; this._timeout = 2000; + this._slow = 75; + this._enableTimeouts = true; this.timedOut = false; + this._trace = new Error('done() called multiple times') } /** * Inherit from `EventEmitter.prototype`. */ -Runnable.prototype = new EventEmitter; +function F(){}; +F.prototype = EventEmitter.prototype; +Runnable.prototype = new F; Runnable.prototype.constructor = Runnable; /** * Set & get timeout `ms`. * - * @param {Number} ms + * @param {Number|String} ms * @return {Runnable|Number} ms or self * @api private */ Runnable.prototype.timeout = function(ms){ if (0 == arguments.length) return this._timeout; + if (ms === 0) this._enableTimeouts = false; + if ('string' == typeof ms) ms = milliseconds(ms); debug('timeout %d', ms); this._timeout = ms; if (this.timer) this.resetTimeout(); return this; }; +/** + * Set & get slow `ms`. + * + * @param {Number|String} ms + * @return {Runnable|Number} ms or self + * @api private + */ + +Runnable.prototype.slow = function(ms){ + if (0 === arguments.length) return this._slow; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('timeout %d', ms); + this._slow = ms; + return this; +}; + +/** + * Set and & get timeout `enabled`. + * + * @param {Boolean} enabled + * @return {Runnable|Boolean} enabled or self + * @api private + */ + +Runnable.prototype.enableTimeouts = function(enabled){ + if (arguments.length === 0) return this._enableTimeouts; + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + /** * Return the full title generated by recursively * concatenating the parent's full title. @@ -3355,16 +4326,26 @@ Runnable.prototype.inspect = function(){ */ Runnable.prototype.resetTimeout = function(){ - var self = this - , ms = this.timeout(); + var self = this; + var ms = this.timeout() || 1e9; + if (!this._enableTimeouts) return; this.clearTimeout(); - if (ms) { - this.timer = setTimeout(function(){ - self.callback(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); - } + this.timer = setTimeout(function(){ + if (!self._enableTimeouts) return; + self.callback(new Error('timeout of ' + ms + 'ms exceeded')); + self.timedOut = true; + }, ms); +}; + +/** + * Whitelist these globals for this test run + * + * @api private + */ +Runnable.prototype.globals = function(arr){ + var self = this; + this._allowedGlobals = arr; }; /** @@ -3376,49 +4357,50 @@ Runnable.prototype.resetTimeout = function(){ Runnable.prototype.run = function(fn){ var self = this - , ms = this.timeout() , start = new Date , ctx = this.ctx , finished , emitted; - if (ctx) ctx.runnable(this); - - // timeout - if (this.async) { - if (ms) { - this.timer = setTimeout(function(){ - done(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); - } - } + // Some times the ctx exists but it is not runnable + if (ctx && ctx.runnable) ctx.runnable(this); // called multiple times function multiple(err) { if (emitted) return; emitted = true; - self.emit('error', err || new Error('done() called multiple times')); + self.emit('error', err || new Error('done() called multiple times; stacktrace may be inaccurate')); } // finished function done(err) { + var ms = self.timeout(); if (self.timedOut) return; - if (finished) return multiple(err); + if (finished) return multiple(err || self._trace); self.clearTimeout(); self.duration = new Date - start; finished = true; + if (!err && self.duration > ms && self._enableTimeouts) err = new Error('timeout of ' + ms + 'ms exceeded'); fn(err); } // for .resetTimeout() this.callback = done; - // async + // explicit async with `done` argument if (this.async) { + this.resetTimeout(); + try { this.fn.call(ctx, function(err){ - if (err instanceof Error) return done(err); + if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); + if (null != err) { + if (Object.prototype.toString.call(err) === '[object Object]') { + return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err))); + } else { + return done(new Error('done() invoked with non-Error: ' + err)); + } + } done(); }); } catch (err) { @@ -3427,20 +4409,41 @@ Runnable.prototype.run = function(fn){ return; } - // sync + if (this.asyncOnly) { + return done(new Error('--async-only option in use without declaring `done()`')); + } + + // sync or promise-returning try { - if (!this.pending) this.fn.call(ctx); - this.duration = new Date - start; - fn(); + if (this.pending) { + done(); + } else { + callFn(this.fn); + } } catch (err) { - fn(err); + done(err); + } + + function callFn(fn) { + var result = fn.call(ctx); + if (result && typeof result.then === 'function') { + self.resetTimeout(); + result + .then(function() { + done() + }, + function(reason) { + done(reason || new Error('Promise rejected with no or falsy reason')) + }); + } else { + done(); + } } }; }); // module: runnable.js require.register("runner.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -3450,8 +4453,20 @@ var EventEmitter = require('browser/events').EventEmitter , Test = require('./test') , utils = require('./utils') , filter = utils.filter - , keys = utils.keys - , noop = function(){}; + , keys = utils.keys; + +/** + * Non-enumerable globals. + */ + +var globals = [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'XMLHttpRequest', + 'Date' +]; /** * Expose `Runner`. @@ -3474,6 +4489,7 @@ module.exports = Runner; * - `hook end` (hook) hook complete * - `pass` (test) test passed * - `fail` (test, err) test failed + * - `pending` (test) test pending * * @api public */ @@ -3481,20 +4497,32 @@ module.exports = Runner; function Runner(suite) { var self = this; this._globals = []; + this._abort = false; this.suite = suite; this.total = suite.total(); this.failures = 0; this.on('test end', function(test){ self.checkGlobals(test); }); this.on('hook end', function(hook){ self.checkGlobals(hook); }); this.grep(/.*/); - this.globals(utils.keys(global).concat(['errno'])); + this.globals(this.globalProps().concat(extraGlobals())); } +/** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + * + * @param {Function} fn + * @api private + */ + +Runner.immediately = global.setImmediate || process.nextTick; + /** * Inherit from `EventEmitter.prototype`. */ -Runner.prototype = new EventEmitter; +function F(){}; +F.prototype = EventEmitter.prototype; +Runner.prototype = new F; Runner.prototype.constructor = Runner; @@ -3538,6 +4566,25 @@ Runner.prototype.grepTotal = function(suite) { return total; }; +/** + * Return a list of global properties. + * + * @return {Array} + * @api private + */ + +Runner.prototype.globalProps = function() { + var props = utils.keys(global); + + // non-enumerables + for (var i = 0; i < globals.length; ++i) { + if (~utils.indexOf(props, globals[i])) continue; + props.push(globals[i]); + } + + return props; +}; + /** * Allow the given `arr` of globals. * @@ -3549,9 +4596,7 @@ Runner.prototype.grepTotal = function(suite) { Runner.prototype.globals = function(arr){ if (0 == arguments.length) return this._globals; debug('globals %j', arr); - utils.forEach(arr, function(arr){ - this._globals.push(arr); - }, this); + this._globals = this._globals.concat(arr); return this; }; @@ -3563,8 +4608,19 @@ Runner.prototype.globals = function(arr){ Runner.prototype.checkGlobals = function(test){ if (this.ignoreLeaks) return; - var leaks = filterLeaks(this._globals); + var ok = this._globals; + + var globals = this.globalProps(); + var leaks; + if (test) { + ok = ok.concat(test._allowedGlobals || []); + } + + if(this.prevGlobalsLength == globals.length) return; + this.prevGlobalsLength = globals.length; + + leaks = filterLeaks(ok, globals); this._globals = this._globals.concat(leaks); if (leaks.length > 1) { @@ -3585,19 +4641,29 @@ Runner.prototype.checkGlobals = function(test){ Runner.prototype.fail = function(test, err){ ++this.failures; test.state = 'failed'; + if ('string' == typeof err) { err = new Error('the string "' + err + '" was thrown, throw an Error :)'); } + this.emit('fail', test, err); }; /** * Fail the given `hook` with `err`. * - * Hook failures (currently) hard-end due - * to that fact that a failing hook will - * surely cause subsequent tests to fail, - * causing jumbled reporting. + * Hook failures work in the following pattern: + * - If bail, then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter + * execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks * * @param {Hook} hook * @param {Error} err @@ -3606,7 +4672,9 @@ Runner.prototype.fail = function(test, err){ Runner.prototype.failHook = function(hook, err){ this.fail(hook, err); - this.emit('end'); + if (this.suite.bail()) { + this.emit('end'); + } }; /** @@ -3620,15 +4688,17 @@ Runner.prototype.failHook = function(hook, err){ Runner.prototype.hook = function(name, fn){ var suite = this.suite , hooks = suite['_' + name] - , ms = suite._timeout , self = this , timer; function next(i) { var hook = hooks[i]; if (!hook) return fn(); + if (self.failures && suite.bail()) return fn(); self.currentRunnable = hook; + hook.ctx.currentTest = self.test; + self.emit('hook', hook); hook.on('error', function(err){ @@ -3639,20 +4709,26 @@ Runner.prototype.hook = function(name, fn){ hook.removeAllListeners('error'); var testError = hook.error(); if (testError) self.fail(self.test, testError); - if (err) return self.failHook(hook, err); + if (err) { + self.failHook(hook, err); + + // stop executing hooks, notify callee of hook err + return fn(err); + } self.emit('hook end', hook); + delete hook.ctx.currentTest; next(++i); }); } - process.nextTick(function(){ + Runner.immediately(function(){ next(0); }); }; /** * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err)`. + * in order, and callback `fn(err, errSuite)`. * * @param {String} name * @param {Array} suites @@ -3674,8 +4750,9 @@ Runner.prototype.hooks = function(name, suites, fn){ self.hook(name, function(err){ if (err) { + var errSuite = self.suite; self.suite = orig; - return fn(err); + return fn(err, errSuite); } next(suites.pop()); @@ -3737,6 +4814,8 @@ Runner.prototype.runTest = function(fn){ var test = this.test , self = this; + if (this.asyncOnly) test.asyncOnly = true; + try { test.on('error', function(err){ self.fail(test, err); @@ -3758,13 +4837,42 @@ Runner.prototype.runTest = function(fn){ Runner.prototype.runTests = function(suite, fn){ var self = this - , tests = suite.tests + , tests = suite.tests.slice() , test; - function next(err) { + + function hookErr(err, errSuite, after) { + // before/after Each hook for errSuite failed: + var orig = self.suite; + + // for failed 'after each' hook start from errSuite parent, + // otherwise start from errSuite itself + self.suite = after ? errSuite.parent : errSuite; + + if (self.suite) { + // call hookUp afterEach + self.hookUp('afterEach', function(err2, errSuite2) { + self.suite = orig; + // some hooks may fail even now + if (err2) return hookErr(err2, errSuite2, true); + // report error suite + fn(errSuite); + }); + } else { + // there is no need calling other 'after each' hooks + self.suite = orig; + fn(errSuite); + } + } + + function next(err, errSuite) { // if we bail after first err if (self.failures && suite._bail) return fn(); + if (self._abort) return fn(); + + if (err) return hookErr(err, errSuite, true); + // next test test = tests.shift(); @@ -3785,7 +4893,10 @@ Runner.prototype.runTests = function(suite, fn){ // execute test and hook(s) self.emit('test', self.test = test); - self.hookDown('beforeEach', function(){ + self.hookDown('beforeEach', function(err, errSuite){ + + if (err) return hookErr(err, errSuite, false); + self.currentRunnable = self.test; self.runTest(function(err){ test = self.test; @@ -3828,21 +4939,37 @@ Runner.prototype.runSuite = function(suite, fn){ this.emit('suite', this.suite = suite); - function next() { + function next(errSuite) { + if (errSuite) { + // current suite failed on a hook from errSuite + if (errSuite == suite) { + // if errSuite is current suite + // continue to the next sibling suite + return done(); + } else { + // errSuite is among the parents of current suite + // stop execution of errSuite and all sub-suites + return done(errSuite); + } + } + + if (self._abort) return done(); + var curr = suite.suites[i++]; if (!curr) return done(); self.runSuite(curr, next); } - function done() { + function done(errSuite) { self.suite = suite; self.hook('afterAll', function(){ self.emit('suite end', suite); - fn(); + fn(errSuite); }); } - this.hook('beforeAll', function(){ + this.hook('beforeAll', function(err){ + if (err) return done(); self.runTests(suite, next); }); }; @@ -3855,13 +4982,26 @@ Runner.prototype.runSuite = function(suite, fn){ */ Runner.prototype.uncaught = function(err){ - debug('uncaught exception %s', err.message); - var runnable = this.currentRunnable; - if (!runnable || 'failed' == runnable.state) return; - runnable.clearTimeout(); + if (err) { + debug('uncaught exception %s', err !== function () { + return this; + }.call(err) ? err : ( err.message || err )); + } else { + debug('uncaught undefined exception'); + err = new Error('Caught undefined error, did you throw without specifying what?'); + } err.uncaught = true; + + var runnable = this.currentRunnable; + if (!runnable) return; + + var wasAlreadyDone = runnable.state; this.fail(runnable, err); + runnable.clearTimeout(); + + if (wasAlreadyDone) return; + // recover from test if ('test' == runnable.type) { this.emit('test end', runnable); @@ -3886,13 +5026,12 @@ Runner.prototype.run = function(fn){ var self = this , fn = fn || function(){}; - debug('start'); - - // uncaught callback - function uncaught(err) { + function uncaught(err){ self.uncaught(err); } + debug('start'); + // callback this.on('end', function(){ debug('end'); @@ -3913,16 +5052,43 @@ Runner.prototype.run = function(fn){ return this; }; +/** + * Cleanly abort execution + * + * @return {Runner} for chaining + * @api public + */ +Runner.prototype.abort = function(){ + debug('aborting'); + this._abort = true; +}; + /** * Filter leaks with the given globals flagged as `ok`. * * @param {Array} ok + * @param {Array} globals * @return {Array} * @api private */ -function filterLeaks(ok) { - return filter(keys(global), function(key){ +function filterLeaks(ok, globals) { + return filter(globals, function(key){ + // Firefox and Chrome exposes iframes as index inside the window object + if (/^d+/.test(key)) return false; + + // in firefox + // if runner runs in an iframe, this iframe's window.getInterface method not init at first + // it is assigned in some seconds + if (global.navigator && /^getInterface/.test(key)) return false; + + // an iframe could be approached by window[iframeIndex] + // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak + if (global.navigator && /^\d+/.test(key)) return false; + + // Opera and IE expose global variables for HTML element IDs (issue #243) + if (/^mocha-/.test(key)) return false; + var matched = filter(ok, function(ok){ if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); return key == ok; @@ -3930,16 +5096,42 @@ function filterLeaks(ok) { return matched.length == 0 && (!global.navigator || 'onerror' !== key); }); } + +/** + * Array of globals dependent on the environment. + * + * @return {Array} + * @api private + */ + + function extraGlobals() { + if (typeof(process) === 'object' && + typeof(process.version) === 'string') { + + var nodeVersion = process.version.split('.').reduce(function(a, v) { + return a << 8 | v; + }); + + // 'errno' was renamed to process._errno in v0.9.11. + + if (nodeVersion < 0x00090B) { + return ['errno']; + } + } + + return []; + } + }); // module: runner.js require.register("suite.js", function(module, exports, require){ - /** * Module dependencies. */ var EventEmitter = require('browser/events').EventEmitter , debug = require('browser/debug')('mocha:suite') + , milliseconds = require('./ms') , utils = require('./utils') , Hook = require('./hook'); @@ -3980,9 +5172,11 @@ exports.create = function(parent, title){ * @api private */ -function Suite(title, ctx) { +function Suite(title, parentContext) { this.title = title; - this.ctx = ctx; + var context = function() {}; + context.prototype = parentContext; + this.ctx = new context(); this.suites = []; this.tests = []; this.pending = false; @@ -3992,6 +5186,8 @@ function Suite(title, ctx) { this._afterAll = []; this.root = !title; this._timeout = 2000; + this._enableTimeouts = true; + this._slow = 75; this._bail = false; } @@ -3999,7 +5195,9 @@ function Suite(title, ctx) { * Inherit from `EventEmitter.prototype`. */ -Suite.prototype = new EventEmitter; +function F(){}; +F.prototype = EventEmitter.prototype; +Suite.prototype = new F; Suite.prototype.constructor = Suite; @@ -4015,6 +5213,8 @@ Suite.prototype.clone = function(){ debug('clone'); suite.ctx = this.ctx; suite.timeout(this.timeout()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); suite.bail(this.bail()); return suite; }; @@ -4029,12 +5229,44 @@ Suite.prototype.clone = function(){ Suite.prototype.timeout = function(ms){ if (0 == arguments.length) return this._timeout; - if (String(ms).match(/s$/)) ms = parseFloat(ms) * 1000; + if (ms === 0) this._enableTimeouts = false; + if ('string' == typeof ms) ms = milliseconds(ms); debug('timeout %d', ms); this._timeout = parseInt(ms, 10); return this; }; +/** + * Set timeout `enabled`. + * + * @param {Boolean} enabled + * @return {Suite|Boolean} self or enabled + * @api private + */ + +Suite.prototype.enableTimeouts = function(enabled){ + if (arguments.length === 0) return this._enableTimeouts; + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Set slow `ms` or short-hand such as "2s". + * + * @param {Number|String} ms + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.slow = function(ms){ + if (0 === arguments.length) return this._slow; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('slow %d', ms); + this._slow = ms; + return this; +}; + /** * Sets whether to bail after first error. * @@ -4058,11 +5290,19 @@ Suite.prototype.bail = function(bail){ * @api private */ -Suite.prototype.beforeAll = function(fn){ +Suite.prototype.beforeAll = function(title, fn){ if (this.pending) return this; - var hook = new Hook('"before all" hook', fn); + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"before all" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); hook.ctx = this.ctx; this._beforeAll.push(hook); this.emit('beforeAll', hook); @@ -4077,11 +5317,19 @@ Suite.prototype.beforeAll = function(fn){ * @api private */ -Suite.prototype.afterAll = function(fn){ +Suite.prototype.afterAll = function(title, fn){ if (this.pending) return this; - var hook = new Hook('"after all" hook', fn); + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"after all" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); hook.ctx = this.ctx; this._afterAll.push(hook); this.emit('afterAll', hook); @@ -4096,11 +5344,19 @@ Suite.prototype.afterAll = function(fn){ * @api private */ -Suite.prototype.beforeEach = function(fn){ +Suite.prototype.beforeEach = function(title, fn){ if (this.pending) return this; - var hook = new Hook('"before each" hook', fn); + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"before each" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); hook.ctx = this.ctx; this._beforeEach.push(hook); this.emit('beforeEach', hook); @@ -4115,11 +5371,19 @@ Suite.prototype.beforeEach = function(fn){ * @api private */ -Suite.prototype.afterEach = function(fn){ +Suite.prototype.afterEach = function(title, fn){ if (this.pending) return this; - var hook = new Hook('"after each" hook', fn); + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"after each" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); hook.ctx = this.ctx; this._afterEach.push(hook); this.emit('afterEach', hook); @@ -4137,6 +5401,8 @@ Suite.prototype.afterEach = function(fn){ Suite.prototype.addSuite = function(suite){ suite.parent = this; suite.timeout(this.timeout()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); suite.bail(this.bail()); this.suites.push(suite); this.emit('suite', suite); @@ -4154,6 +5420,8 @@ Suite.prototype.addSuite = function(suite){ Suite.prototype.addTest = function(test){ test.parent = this; test.timeout(this.timeout()); + test.enableTimeouts(this.enableTimeouts()); + test.slow(this.slow()); test.ctx = this.ctx; this.tests.push(test); this.emit('test', test); @@ -4210,7 +5478,6 @@ Suite.prototype.eachTest = function(fn){ }); // module: suite.js require.register("test.js", function(module, exports, require){ - /** * Module dependencies. */ @@ -4241,20 +5508,24 @@ function Test(title, fn) { * Inherit from `Runnable.prototype`. */ -Test.prototype = new Runnable; +function F(){}; +F.prototype = Runnable.prototype; +Test.prototype = new F; Test.prototype.constructor = Test; }); // module: test.js require.register("utils.js", function(module, exports, require){ - /** * Module dependencies. */ var fs = require('browser/fs') , path = require('browser/path') + , basename = path.basename + , exists = fs.existsSync || path.existsSync + , glob = require('browser/glob') , join = path.join , debug = require('browser/debug')('mocha:watch'); @@ -4272,7 +5543,7 @@ var ignore = ['node_modules', '.git']; * @api private */ -exports.escape = function(html) { +exports.escape = function(html){ return String(html) .replace(/&/g, '&') .replace(/"/g, '"') @@ -4289,11 +5560,27 @@ exports.escape = function(html) { * @api private */ -exports.forEach = function(arr, fn, scope) { +exports.forEach = function(arr, fn, scope){ for (var i = 0, l = arr.length; i < l; i++) fn.call(scope, arr[i], i); }; +/** + * Array#map (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @param {Object} scope + * @api private + */ + +exports.map = function(arr, fn, scope){ + var result = []; + for (var i = 0, l = arr.length; i < l; i++) + result.push(fn.call(scope, arr[i], i)); + return result; +}; + /** * Array#indexOf (<=IE8) * @@ -4303,7 +5590,7 @@ exports.forEach = function(arr, fn, scope) { * @api private */ -exports.indexOf = function (arr, obj, start) { +exports.indexOf = function(arr, obj, start){ for (var i = start || 0, l = arr.length; i < l; i++) { if (arr[i] === obj) return i; @@ -4317,15 +5604,14 @@ exports.indexOf = function (arr, obj, start) { * @param {Array} array * @param {Function} fn * @param {Object} initial value - * @param {Object} scope * @api private */ -exports.reduce = function(arr, fn, val, scope) { +exports.reduce = function(arr, fn, val){ var rval = val; for (var i = 0, l = arr.length; i < l; i++) { - rval = fn.call(scope, rval, arr[i], i, arr); + rval = fn(rval, arr[i], i, arr); } return rval; @@ -4336,17 +5622,15 @@ exports.reduce = function(arr, fn, val, scope) { * * @param {Array} array * @param {Function} fn - * @param {Object} scope * @api private */ -exports.filter = function(arr, fn, scope) { +exports.filter = function(arr, fn){ var ret = []; for (var i = 0, l = arr.length; i < l; i++) { var val = arr[i]; - if (fn.call(scope, val, i, arr)) - ret.push(val); + if (fn(val, i, arr)) ret.push(val); } return ret; @@ -4407,16 +5691,19 @@ function ignored(path){ * @api private */ -exports.files = function(dir, ret){ +exports.files = function(dir, ext, ret){ ret = ret || []; + ext = ext || ['js']; + + var re = new RegExp('\\.(' + ext.join('|') + ')$'); fs.readdirSync(dir) .filter(ignored) .forEach(function(path){ path = join(dir, path); if (fs.statSync(path).isDirectory()) { - exports.files(path, ret); - } else if (path.match(/\.(js|coffee)$/)) { + exports.files(path, ext, ret); + } else if (path.match(re)) { ret.push(path); } }); @@ -4446,78 +5733,224 @@ exports.slug = function(str){ exports.clean = function(str) { str = str - .replace(/^function *\(.*\) *{/, '') + .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '') + .replace(/^function *\(.*\) *{|\(.*\) *=> *{?/, '') .replace(/\s+\}$/, ''); var spaces = str.match(/^\n?( *)/)[1].length - , re = new RegExp('^ {' + spaces + '}', 'gm'); + , tabs = str.match(/^\n?(\t*)/)[1].length + , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm'); str = str.replace(re, ''); - return str.trim(); + return exports.trim(str); }; /** - * Escape regular expression characters in `str`. + * Trim the given `str`. * * @param {String} str * @return {String} * @api private */ -exports.escapeRegexp = function(str){ - return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); +exports.trim = function(str){ + return str.replace(/^\s+|\s+$/g, ''); }; -}); // module: utils.js + /** - * Node shims. + * Parse the given `qs`. * - * These are meant only to allow - * mocha.js to run untouched, not - * to allow running node code in - * the browser. + * @param {String} qs + * @return {Object} + * @api private */ -process = {}; -process.exit = function(status){}; -process.stdout = {}; -global = window; +exports.parseQuery = function(qs){ + return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ + var i = pair.indexOf('=') + , key = pair.slice(0, i) + , val = pair.slice(++i); + + obj[key] = decodeURIComponent(val); + return obj; + }, {}); +}; + +/** + * Highlight the given string of `js`. + * + * @param {String} js + * @return {String} + * @api private + */ + +function highlight(js) { + return js + .replace(//g, '>') + .replace(/\/\/(.*)/gm, '//$1') + .replace(/('.*?')/gm, '$1') + .replace(/(\d+\.\d+)/gm, '$1') + .replace(/(\d+)/gm, '$1') + .replace(/\bnew[ \t]+(\w+)/gm, 'new $1') + .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') +} + +/** + * Highlight the contents of tag `name`. + * + * @param {String} name + * @api private + */ + +exports.highlightTags = function(name) { + var code = document.getElementById('mocha').getElementsByTagName(name); + for (var i = 0, len = code.length; i < len; ++i) { + code[i].innerHTML = highlight(code[i].innerHTML); + } +}; + + +/** + * Stringify `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +exports.stringify = function(obj) { + if (obj instanceof RegExp) return obj.toString(); + return JSON.stringify(exports.canonicalize(obj), null, 2).replace(/,(\n|$)/g, '$1'); +}; /** - * next tick implementation. + * Return a new object that has the keys in sorted order. + * @param {Object} obj + * @param {Array} [stack] + * @return {Object} + * @api private */ -process.nextTick = (function(){ - // postMessage behaves badly on IE8 - if (window.ActiveXObject || !window.postMessage) { - return function(fn){ fn() }; +exports.canonicalize = function(obj, stack) { + stack = stack || []; + + if (exports.indexOf(stack, obj) !== -1) return '[Circular]'; + + var canonicalizedObj; + + if ({}.toString.call(obj) === '[object Array]') { + stack.push(obj); + canonicalizedObj = exports.map(obj, function (item) { + return exports.canonicalize(item, stack); + }); + stack.pop(); + } else if (typeof obj === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + exports.forEach(exports.keys(obj).sort(), function (key) { + canonicalizedObj[key] = exports.canonicalize(obj[key], stack); + }); + stack.pop(); + } else { + canonicalizedObj = obj; } - // based on setZeroTimeout by David Baron - // - http://dbaron.org/log/20100309-faster-timeouts - var timeouts = [] - , name = 'mocha-zero-timeout' + return canonicalizedObj; + }; - window.addEventListener('message', function(e){ - if (e.source == window && e.data == name) { - if (e.stopPropagation) e.stopPropagation(); - if (timeouts.length) timeouts.shift()(); +/** + * Lookup file names at the given `path`. + */ +exports.lookupFiles = function lookupFiles(path, extensions, recursive) { + var files = []; + var re = new RegExp('\\.(' + extensions.join('|') + ')$'); + + if (!exists(path)) { + if (exists(path + '.js')) { + path += '.js'; + } else { + files = glob.sync(path); + if (!files.length) throw new Error("cannot resolve path (or pattern) '" + path + "'"); + return files; } - }, true); + } - return function(fn){ - timeouts.push(fn); - window.postMessage(name, '*'); + try { + var stat = fs.statSync(path); + if (stat.isFile()) return path; } -})(); + catch (ignored) { + return; + } + + fs.readdirSync(path).forEach(function(file){ + file = join(path, file); + try { + var stat = fs.statSync(file); + if (stat.isDirectory()) { + if (recursive) { + files = files.concat(lookupFiles(file, extensions, recursive)); + } + return; + } + } + catch (ignored) { + return; + } + if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') return; + files.push(file); + }); + + return files; +}; + +}); // module: utils.js +// The global object is "self" in Web Workers. +var global = (function() { return this; })(); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; + +/** + * Node shims. + * + * These are meant only to allow + * mocha.js to run untouched, not + * to allow running node code in + * the browser. + */ + +var process = {}; +process.exit = function(status){}; +process.stdout = {}; + +var uncaughtExceptionHandlers = []; + +var originalOnerrorHandler = global.onerror; /** * Remove uncaughtException listener. + * Revert to original onerror handler if previously defined. */ -process.removeListener = function(e){ +process.removeListener = function(e, fn){ if ('uncaughtException' == e) { - window.onerror = null; + if (originalOnerrorHandler) { + global.onerror = originalOnerrorHandler; + } else { + global.onerror = function() {}; + } + var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn); + if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); } } }; @@ -4527,7 +5960,11 @@ process.removeListener = function(e){ process.on = function(e, fn){ if ('uncaughtException' == e) { - window.onerror = fn; + global.onerror = function(err, url, line){ + fn(new Error(err + ' (' + url + ':' + line + ')')); + return true; + }; + uncaughtExceptionHandlers.push(fn); } }; @@ -4535,88 +5972,98 @@ process.on = function(e, fn){ * Expose mocha. */ -window.mocha = require('mocha'); +var Mocha = global.Mocha = require('mocha'), + mocha = global.mocha = new Mocha({ reporter: 'html' }); -// boot -;(function(){ - var utils = mocha.utils - , options = {} - - mocha.suite = new mocha.Suite('', new mocha.Context()); - - /** - * Highlight the given string of `js`. - */ - - function highlight(js) { - return js - .replace(//g, '>') - .replace(/\/\/(.*)/gm, '//$1') - .replace(/('.*?')/gm, '$1') - .replace(/(\d+\.\d+)/gm, '$1') - .replace(/(\d+)/gm, '$1') - .replace(/\bnew *(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') +// The BDD UI is registered by default, but no UI will be functional in the +// browser without an explicit call to the overridden `mocha.ui` (see below). +// Ensure that this default UI does not expose its methods to the global scope. +mocha.suite.removeAllListeners('pre-require'); + +var immediateQueue = [] + , immediateTimeout; + +function timeslice() { + var immediateStart = new Date().getTime(); + while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { + immediateQueue.shift()(); + } + if (immediateQueue.length) { + immediateTimeout = setTimeout(timeslice, 0); + } else { + immediateTimeout = null; } +} - /** - * Highlight code contents. - */ +/** + * High-performance override of Runner.immediately. + */ - function highlightCode() { - var code = document.getElementsByTagName('code'); - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } +Mocha.Runner.immediately = function(callback) { + immediateQueue.push(callback); + if (!immediateTimeout) { + immediateTimeout = setTimeout(timeslice, 0); } +}; + +/** + * Function to allow assertion libraries to throw errors directly into mocha. + * This is useful when running tests in a browser because window.onerror will + * only receive the 'message' attribute of the Error. + */ +mocha.throwError = function(err) { + Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) { + fn(err); + }); + throw err; +}; - /** - * Parse the given `qs`. - */ +/** + * Override ui to ensure that the ui functions are initialized. + * Normally this would happen in Mocha.prototype.loadFiles. + */ - function parse(qs) { - return utils.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); +mocha.ui = function(ui){ + Mocha.prototype.ui.call(this, ui); + this.suite.emit('pre-require', global, null, this); + return this; +}; - obj[key] = decodeURIComponent(val); - return obj; - }, {}); - } +/** + * Setup mocha with the given setting options. + */ - /** - * Setup mocha with the given setting options. - */ +mocha.setup = function(opts){ + if ('string' == typeof opts) opts = { ui: opts }; + for (var opt in opts) this[opt](opts[opt]); + return this; +}; - mocha.setup = function(opts){ - if ('string' === typeof opts) options.ui = opts; - else options = opts; +/** + * Run mocha, returning the Runner. + */ - ui = mocha.interfaces[options.ui]; - if (!ui) throw new Error('invalid mocha interface "' + ui + '"'); - if (options.timeout) mocha.suite.timeout(options.timeout); - ui(mocha.suite); - mocha.suite.emit('pre-require', window); - }; +mocha.run = function(fn){ + var options = mocha.options; + mocha.globals('location'); - /** - * Run mocha, returning the Runner. - */ - - mocha.run = function(fn){ - mocha.suite.emit('run'); - var runner = new mocha.Runner(mocha.suite); - var Reporter = options.reporter || mocha.reporters.HTML; - var reporter = new Reporter(runner); - var query = parse(window.location.search || ""); - if (query.grep) runner.grep(new RegExp(query.grep)); - if (options.ignoreLeaks) runner.ignoreLeaks = true; - if (options.globals) runner.globals(options.globals); - runner.globals(['location']); - runner.on('end', highlightCode); - return runner.run(fn); - }; -})(); + var query = Mocha.utils.parseQuery(global.location.search || ''); + if (query.grep) mocha.grep(query.grep); + if (query.invert) mocha.invert(); + + return Mocha.prototype.run.call(mocha, function(err){ + // The DOM Document is not available in Web Workers. + var document = global.document; + if (document && document.getElementById('mocha') && options.noHighlighting !== true) { + Mocha.utils.highlightTags('code'); + } + if (fn) fn(err); + }); +}; + +/** + * Expose the process shim. + */ + +Mocha.process = process; })(); diff --git a/browser/mocha_init.js b/browser/mocha_init.js deleted file mode 100644 index 085a3a708..000000000 --- a/browser/mocha_init.js +++ /dev/null @@ -1,7 +0,0 @@ -mocha.setup({ - //reporter: mocha.reporters.TAP, - ignoreLeaks: true, - ui: "bdd", - timeout: 2000, - slow: Infinity -}); diff --git a/browser/setup b/browser/setup deleted file mode 100644 index 0f8644bed..000000000 --- a/browser/setup +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/bash -grunt -node bundler.js -browserify main.js -o bundle.js diff --git a/package.json b/package.json index f78fee2e6..db718a1d4 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,8 @@ ], "scripts": { "test": "grunt test", - "prepublish": "grunt build" + "prepublish": "grunt build", + "browsers": "browserify browser/main.js -o browser/bundle.js" }, "homepage": "https://github.com/petkaantonov/bluebird", "repository": { @@ -41,7 +42,7 @@ "grunt-contrib-watch": "latest", "grunt-contrib-connect": "latest", "grunt-contrib-concat": "latest", - "grunt-saucelabs": "~8.3.1", + "grunt-saucelabs": "~8.4.1", "acorn": "~0.6.0", "mocha": "~1.20.1", "q": "~1.0.1", diff --git a/src/race.js b/src/race.js index 5af8b9c71..5aae1c5a7 100644 --- a/src/race.js +++ b/src/race.js @@ -9,7 +9,6 @@ var raceLater = function (promise) { }); }; -var hasOwn = {}.hasOwnProperty; function race(promises, parent) { var maybePromise = tryConvertToPromise(promises, undefined); @@ -30,7 +29,7 @@ function race(promises, parent) { for (var i = 0, len = promises.length; i < len; ++i) { var val = promises[i]; - if (val === undefined && !(hasOwn.call(promises, i))) { + if (val === undefined && !(i in promises)) { continue; } diff --git a/test/mocha/cancel.js b/test/mocha/cancel.js index 87cdcacdd..39812b9a7 100644 --- a/test/mocha/cancel.js +++ b/test/mocha/cancel.js @@ -235,7 +235,7 @@ describe("issues", function(){ a = a.then(function() { f3 = true; - return delay(150); + return delay(2000); }); a = a.then(function() { @@ -248,16 +248,14 @@ describe("issues", function(){ assert(f1); assert(f2); assert(f3); assertCancelled(waitingForLongDelay); assert(!f4); - setTimeout(function() { - done(); - }, 200); + done(); }); assert(a.isCancellable()); setTimeout(function() { assert(a.isCancellable()); a.cancel(); - }, 50); + }, 250); }); }); @@ -276,14 +274,14 @@ describe("simple", function() { describe("Cancelling a promise twice should have no additional effect", function() { specify("With delay", function(done) { - var promise = pending().promise.cancellable().catch(function(){}).then(done).catch(function() { done(new Error('Should not be called')) }); + var promise = pending().promise.cancellable().caught(function(){}).then(done).caught(function() { done(new Error('Should not be called')) }); promise.cancel(); setTimeout(function() { promise.cancel(); }, 50); }); specify("Without delay", function(done) { - var promise = pending().promise.cancellable().catch(function(){}).then(done).catch(function() { done(new Error('Should not be called')) }); + var promise = pending().promise.cancellable().caught(function(){}).then(done).caught(function() { done(new Error('Should not be called')) }); promise.cancel() promise.cancel(); }); diff --git a/test/mocha/timers.js b/test/mocha/timers.js index 372423fb8..549376f5d 100644 --- a/test/mocha/timers.js +++ b/test/mocha/timers.js @@ -98,33 +98,44 @@ describe("timeout", function () { doExpensiveOp().timeout(100); }); - it("should clear timeouts when success", function(done) { - var old = globalObject.clearTimeout; - var handleSet = false; - globalObject.clearTimeout = function(handle) { - handleSet = true; - globalObject.clearTimeout = old; - }; - - Q.delay(10).timeout(100).then(function() { - assert(handleSet); - done(); + var globalsAreReflectedInGlobalObject = (function(window) { + var fn = function(id){return clearTimeout(id);}; + var old = window.clearTimeout; + window.clearTimeout = fn; + var ret = clearTimeout === fn; + window.clearTimeout = old; + return ret; + })(globalObject); + + if (globalsAreReflectedInGlobalObject) { + it("should clear timeouts when success", function(done) { + var old = globalObject.clearTimeout; + var handleSet = false; + globalObject.clearTimeout = function(handle) { + handleSet = true; + globalObject.clearTimeout = old; + }; + + Q.delay(10).timeout(100).then(function() { + assert(handleSet); + done(); + }); }); - }); - it("should clear timeouts when fail", function(done) { - var old = globalObject.clearTimeout; - var handleSet = false; - globalObject.clearTimeout = function(handle) { - handleSet = true; - globalObject.clearTimeout = old; - }; + it("should clear timeouts when fail", function(done) { + var old = globalObject.clearTimeout; + var handleSet = false; + globalObject.clearTimeout = function(handle) { + handleSet = true; + globalObject.clearTimeout = old; + }; - Q.delay(100).timeout(10).then(null, function() { - assert(handleSet); - done(); + Q.delay(100).timeout(10).then(null, function() { + assert(handleSet); + done(); + }); }); - }); + } }); describe("delay", function () {