From f94ca33b9eb7bd4604e42c1ef1cc10318f41651f Mon Sep 17 00:00:00 2001 From: Dobie Wollert Date: Wed, 16 Dec 2015 09:12:35 -0800 Subject: [PATCH] Changes --- app/controllers/clock.js | 42 - app/controllers/db.js | 64 + app/controllers/pms.js | 9 +- app/controllers/timeclock.js | 819 +- app/controllers/timesheet.js | 370 + app/controllers/users.js | 353 +- app/controllers/workorders.js | 967 +- app/model/timeClockException.js | 30 + app/model/timeClockSpan.js | 140 +- app/model/user.js | 20 +- app/model/workorder.js | 95 +- app/routes/exceptions.js | 60 + app/routes/index.js | 9 + app/routes/misc.js | 53 + app/routes/spans.js | 97 + app/routes/users.js | 184 + app/routes/workorders.js | 67 + app/templates/exception.html.tmpl | 74 + app/templates/exception.text.tmpl | 3 + app/templates/partsRequest.html.tmpl | 146 + app/templates/partsRequest.text.tmpl | 58 + app/util/email.js | 100 + config/auth.js | 377 +- config/config.js | 32 +- config/db.js | 30 + config/express.js | 11 +- config/promise.js | 36 + config/routes.js | 308 +- config/validators.js | 25 + node_modules/bluebird/LICENSE | 4 +- node_modules/bluebird/README.md | 644 +- node_modules/bluebird/changelog.md | 1 + node_modules/bluebird/js/browser/bluebird.js | 5277 +++---- .../bluebird/js/browser/bluebird.min.js | 14 +- .../bluebird/js/{main => release}/any.js | 0 node_modules/bluebird/js/release/assert.js | 55 + node_modules/bluebird/js/release/async.js | 157 + node_modules/bluebird/js/release/bind.js | 67 + node_modules/bluebird/js/release/bluebird.js | 11 + node_modules/bluebird/js/release/call_get.js | 123 + node_modules/bluebird/js/release/cancel.js | 125 + .../bluebird/js/release/catch_filter.js | 42 + node_modules/bluebird/js/release/context.js | 69 + .../bluebird/js/release/debuggability.js | 812 + .../bluebird/js/release/direct_resolve.js | 46 + node_modules/bluebird/js/release/each.js | 29 + node_modules/bluebird/js/release/errors.js | 111 + .../bluebird/js/{main => release}/es5.js | 0 .../bluebird/js/{main => release}/filter.js | 0 node_modules/bluebird/js/release/finally.js | 100 + .../bluebird/js/release/generators.js | 204 + node_modules/bluebird/js/release/join.js | 149 + node_modules/bluebird/js/release/map.js | 151 + node_modules/bluebird/js/release/method.js | 55 + node_modules/bluebird/js/release/nodeback.js | 51 + node_modules/bluebird/js/release/nodeify.js | 58 + node_modules/bluebird/js/release/promise.js | 755 + .../bluebird/js/release/promise_array.js | 184 + node_modules/bluebird/js/release/promisify.js | 314 + node_modules/bluebird/js/release/props.js | 118 + .../bluebird/js/{main => release}/queue.js | 0 node_modules/bluebird/js/release/race.js | 49 + node_modules/bluebird/js/release/reduce.js | 162 + node_modules/bluebird/js/release/schedule.js | 35 + node_modules/bluebird/js/release/settle.js | 43 + node_modules/bluebird/js/release/some.js | 148 + .../js/release/synchronous_inspection.js | 96 + node_modules/bluebird/js/release/thenables.js | 82 + node_modules/bluebird/js/release/timers.js | 66 + node_modules/bluebird/js/release/using.js | 225 + node_modules/bluebird/js/release/util.js | 344 + node_modules/bluebird/package.json | 135 +- node_modules/colors/.travis.yml | 6 + node_modules/colors/MIT-LICENSE.txt | 23 + node_modules/colors/ReadMe.md | 167 + node_modules/colors/examples/normal-usage.js | 74 + node_modules/colors/examples/safe-string.js | 76 + node_modules/colors/lib/colors.js | 176 + node_modules/colors/lib/custom/trap.js | 45 + node_modules/colors/lib/custom/zalgo.js | 104 + .../colors/lib/extendStringPrototype.js | 118 + node_modules/colors/lib/index.js | 12 + node_modules/colors/lib/maps/america.js | 12 + node_modules/colors/lib/maps/rainbow.js | 13 + node_modules/colors/lib/maps/random.js | 8 + node_modules/colors/lib/maps/zebra.js | 5 + node_modules/colors/lib/styles.js | 77 + .../colors/lib/system/supports-colors.js | 61 + node_modules/colors/package.json | 79 + node_modules/colors/safe.js | 9 + node_modules/colors/screenshots/colors.png | Bin 0 -> 79787 bytes node_modules/colors/tests/basic-test.js | 50 + node_modules/colors/tests/safe-test.js | 45 + node_modules/colors/themes/generic-logging.js | 12 + node_modules/cycle/README.md | 49 + node_modules/cycle/cycle.js | 170 + node_modules/cycle/package.json | 73 + node_modules/express-validator/.editorconfig | 11 + node_modules/express-validator/.jscsrc | 56 + node_modules/express-validator/.jshintrc | 18 + node_modules/express-validator/.npmignore | 3 + node_modules/express-validator/.travis.yml | 11 + node_modules/express-validator/CHANGELOG.md | 227 + node_modules/express-validator/LICENSE | 21 + node_modules/express-validator/README.md | 380 + node_modules/express-validator/index.js | 1 + .../lib/express_validator.js | 408 + .../node_modules/bluebird/LICENSE | 21 + .../node_modules/bluebird/README.md | 679 + .../node_modules/bluebird/changelog.md | 1723 +++ .../bluebird/js/browser/bluebird.js | 4887 ++++++ .../bluebird/js/browser/bluebird.min.js | 31 + .../node_modules/bluebird/js/main/any.js | 21 + .../node_modules}/bluebird/js/main/assert.js | 0 .../node_modules}/bluebird/js/main/async.js | 78 +- .../node_modules}/bluebird/js/main/bind.js | 9 +- .../bluebird/js/main/bluebird.js | 0 .../bluebird/js/main/call_get.js | 0 .../node_modules}/bluebird/js/main/cancel.js | 0 .../bluebird/js/main/captured_trace.js | 3 +- .../bluebird/js/main/catch_filter.js | 2 +- .../node_modules}/bluebird/js/main/context.js | 0 .../bluebird/js/main/debuggability.js | 19 +- .../bluebird/js/main/direct_resolve.js | 15 +- .../node_modules}/bluebird/js/main/each.js | 0 .../node_modules}/bluebird/js/main/errors.js | 0 .../node_modules/bluebird/js/main/es5.js | 80 + .../node_modules/bluebird/js/main/filter.js | 12 + .../node_modules}/bluebird/js/main/finally.js | 7 +- .../bluebird/js/main/generators.js | 0 .../node_modules}/bluebird/js/main/join.js | 0 .../node_modules}/bluebird/js/main/map.js | 6 +- .../node_modules}/bluebird/js/main/method.js | 0 .../node_modules}/bluebird/js/main/nodeify.js | 9 +- .../bluebird/js/main/progress.js | 0 .../node_modules}/bluebird/js/main/promise.js | 94 +- .../bluebird/js/main/promise_array.js | 2 +- .../bluebird/js/main/promise_resolver.js | 0 .../bluebird/js/main/promisify.js | 38 +- .../node_modules}/bluebird/js/main/props.js | 0 .../node_modules/bluebird/js/main/queue.js | 90 + .../node_modules}/bluebird/js/main/race.js | 0 .../node_modules}/bluebird/js/main/reduce.js | 6 +- .../bluebird/js/main/schedule.js | 26 +- .../node_modules}/bluebird/js/main/settle.js | 0 .../node_modules}/bluebird/js/main/some.js | 0 .../js/main/synchronous_inspection.js | 0 .../bluebird/js/main/thenables.js | 7 +- .../node_modules}/bluebird/js/main/timers.js | 12 +- .../node_modules}/bluebird/js/main/using.js | 17 +- .../node_modules}/bluebird/js/main/util.js | 71 +- .../node_modules/bluebird/package.json | 127 + .../node_modules/lodash/LICENSE | 22 + .../node_modules/lodash/README.md | 121 + .../node_modules/lodash/array.js | 44 + .../node_modules/lodash/array/chunk.js | 46 + .../node_modules/lodash/array/compact.js | 30 + .../node_modules/lodash/array/difference.js | 29 + .../node_modules/lodash/array/drop.js | 39 + .../node_modules/lodash/array/dropRight.js | 40 + .../lodash/array/dropRightWhile.js | 59 + .../node_modules/lodash/array/dropWhile.js | 59 + .../node_modules/lodash/array/fill.js | 44 + .../node_modules/lodash/array/findIndex.js | 53 + .../lodash/array/findLastIndex.js | 53 + .../node_modules/lodash/array/first.js | 22 + .../node_modules/lodash/array/flatten.js | 32 + .../node_modules/lodash/array/flattenDeep.js | 21 + .../node_modules/lodash/array/head.js | 1 + .../node_modules/lodash/array/indexOf.js | 53 + .../node_modules/lodash/array/initial.js | 20 + .../node_modules/lodash/array/intersection.js | 58 + .../node_modules/lodash/array/last.js | 19 + .../node_modules/lodash/array/lastIndexOf.js | 60 + .../node_modules/lodash/array/object.js | 1 + .../node_modules/lodash/array/pull.js | 52 + .../node_modules/lodash/array/pullAt.js | 40 + .../node_modules/lodash/array/remove.js | 64 + .../node_modules/lodash/array/rest.js | 21 + .../node_modules/lodash/array/slice.js | 30 + .../node_modules/lodash/array/sortedIndex.js | 53 + .../lodash/array/sortedLastIndex.js | 25 + .../node_modules/lodash/array/tail.js | 1 + .../node_modules/lodash/array/take.js | 39 + .../node_modules/lodash/array/takeRight.js | 40 + .../lodash/array/takeRightWhile.js | 59 + .../node_modules/lodash/array/takeWhile.js | 59 + .../node_modules/lodash/array/union.js | 24 + .../node_modules/lodash/array/uniq.js | 71 + .../node_modules/lodash/array/unique.js | 1 + .../node_modules/lodash/array/unzip.js | 47 + .../node_modules/lodash/array/unzipWith.js | 41 + .../node_modules/lodash/array/without.js | 27 + .../node_modules/lodash/array/xor.js | 35 + .../node_modules/lodash/array/zip.js | 21 + .../node_modules/lodash/array/zipObject.js | 43 + .../node_modules/lodash/array/zipWith.js | 36 + .../node_modules/lodash/chain.js | 16 + .../node_modules/lodash/chain/chain.js | 35 + .../node_modules/lodash/chain/commit.js | 1 + .../node_modules/lodash/chain/concat.js | 1 + .../node_modules/lodash/chain/lodash.js | 125 + .../node_modules/lodash/chain/plant.js | 1 + .../node_modules/lodash/chain/reverse.js | 1 + .../node_modules/lodash/chain/run.js | 1 + .../node_modules/lodash/chain/tap.js | 29 + .../node_modules/lodash/chain/thru.js | 26 + .../node_modules/lodash/chain/toJSON.js | 1 + .../node_modules/lodash/chain/toString.js | 1 + .../node_modules/lodash/chain/value.js | 1 + .../node_modules/lodash/chain/valueOf.js | 1 + .../node_modules/lodash/chain/wrapperChain.js | 32 + .../lodash/chain/wrapperCommit.js | 32 + .../lodash/chain/wrapperConcat.js | 34 + .../node_modules/lodash/chain/wrapperPlant.js | 45 + .../lodash/chain/wrapperReverse.js | 43 + .../lodash/chain/wrapperToString.js | 17 + .../node_modules/lodash/chain/wrapperValue.js | 20 + .../node_modules/lodash/collection.js | 44 + .../node_modules/lodash/collection/all.js | 1 + .../node_modules/lodash/collection/any.js | 1 + .../node_modules/lodash/collection/at.js | 29 + .../node_modules/lodash/collection/collect.js | 1 + .../lodash/collection/contains.js | 1 + .../node_modules/lodash/collection/countBy.js | 54 + .../node_modules/lodash/collection/detect.js | 1 + .../node_modules/lodash/collection/each.js | 1 + .../lodash/collection/eachRight.js | 1 + .../node_modules/lodash/collection/every.js | 66 + .../node_modules/lodash/collection/filter.js | 61 + .../node_modules/lodash/collection/find.js | 56 + .../lodash/collection/findLast.js | 25 + .../lodash/collection/findWhere.js | 37 + .../node_modules/lodash/collection/foldl.js | 1 + .../node_modules/lodash/collection/foldr.js | 1 + .../node_modules/lodash/collection/forEach.js | 37 + .../lodash/collection/forEachRight.js | 26 + .../node_modules/lodash/collection/groupBy.js | 59 + .../node_modules/lodash/collection/include.js | 1 + .../lodash/collection/includes.js | 57 + .../node_modules/lodash/collection/indexBy.js | 53 + .../node_modules/lodash/collection/inject.js | 1 + .../node_modules/lodash/collection/invoke.js | 42 + .../node_modules/lodash/collection/map.js | 68 + .../node_modules/lodash/collection/max.js | 1 + .../node_modules/lodash/collection/min.js | 1 + .../lodash/collection/partition.js | 66 + .../node_modules/lodash/collection/pluck.js | 31 + .../node_modules/lodash/collection/reduce.js | 44 + .../lodash/collection/reduceRight.js | 29 + .../node_modules/lodash/collection/reject.js | 50 + .../node_modules/lodash/collection/sample.js | 50 + .../node_modules/lodash/collection/select.js | 1 + .../node_modules/lodash/collection/shuffle.js | 24 + .../node_modules/lodash/collection/size.js | 30 + .../node_modules/lodash/collection/some.js | 67 + .../node_modules/lodash/collection/sortBy.js | 71 + .../lodash/collection/sortByAll.js | 52 + .../lodash/collection/sortByOrder.js | 55 + .../node_modules/lodash/collection/sum.js | 1 + .../node_modules/lodash/collection/where.js | 37 + .../node_modules/lodash/date.js | 3 + .../node_modules/lodash/date/now.js | 24 + .../node_modules/lodash/function.js | 28 + .../node_modules/lodash/function/after.js | 48 + .../node_modules/lodash/function/ary.js | 34 + .../node_modules/lodash/function/backflow.js | 1 + .../node_modules/lodash/function/before.js | 42 + .../node_modules/lodash/function/bind.js | 56 + .../node_modules/lodash/function/bindAll.js | 50 + .../node_modules/lodash/function/bindKey.js | 66 + .../node_modules/lodash/function/compose.js | 1 + .../node_modules/lodash/function/curry.js | 51 + .../lodash/function/curryRight.js | 48 + .../node_modules/lodash/function/debounce.js | 181 + .../node_modules/lodash/function/defer.js | 25 + .../node_modules/lodash/function/delay.js | 26 + .../node_modules/lodash/function/flow.js | 25 + .../node_modules/lodash/function/flowRight.js | 25 + .../node_modules/lodash/function/memoize.js | 80 + .../node_modules/lodash/function/modArgs.js | 58 + .../node_modules/lodash/function/negate.js | 32 + .../node_modules/lodash/function/once.js | 24 + .../node_modules/lodash/function/partial.js | 43 + .../lodash/function/partialRight.js | 42 + .../node_modules/lodash/function/rearg.js | 40 + .../node_modules/lodash/function/restParam.js | 58 + .../node_modules/lodash/function/spread.js | 44 + .../node_modules/lodash/function/throttle.js | 62 + .../node_modules/lodash/function/wrap.js | 33 + .../node_modules/lodash/index.js | 12351 ++++++++++++++++ .../lodash/internal/LazyWrapper.js | 26 + .../lodash/internal/LodashWrapper.js | 21 + .../node_modules/lodash/internal/MapCache.js | 24 + .../node_modules/lodash/internal/SetCache.js | 29 + .../lodash/internal/arrayConcat.js | 25 + .../node_modules/lodash/internal/arrayCopy.js | 20 + .../node_modules/lodash/internal/arrayEach.js | 22 + .../lodash/internal/arrayEachRight.js | 21 + .../lodash/internal/arrayEvery.js | 23 + .../lodash/internal/arrayExtremum.js | 30 + .../lodash/internal/arrayFilter.js | 25 + .../node_modules/lodash/internal/arrayMap.js | 21 + .../node_modules/lodash/internal/arrayPush.js | 20 + .../lodash/internal/arrayReduce.js | 26 + .../lodash/internal/arrayReduceRight.js | 24 + .../node_modules/lodash/internal/arraySome.js | 23 + .../node_modules/lodash/internal/arraySum.js | 20 + .../lodash/internal/assignDefaults.js | 13 + .../lodash/internal/assignOwnDefaults.js | 26 + .../lodash/internal/assignWith.js | 32 + .../lodash/internal/baseAssign.js | 19 + .../node_modules/lodash/internal/baseAt.js | 32 + .../lodash/internal/baseCallback.js | 35 + .../node_modules/lodash/internal/baseClone.js | 128 + .../lodash/internal/baseCompareAscending.js | 34 + .../node_modules/lodash/internal/baseCopy.js | 23 + .../lodash/internal/baseCreate.js | 23 + .../node_modules/lodash/internal/baseDelay.js | 21 + .../lodash/internal/baseDifference.js | 55 + .../node_modules/lodash/internal/baseEach.js | 15 + .../lodash/internal/baseEachRight.js | 15 + .../node_modules/lodash/internal/baseEvery.js | 22 + .../lodash/internal/baseExtremum.js | 29 + .../node_modules/lodash/internal/baseFill.js | 31 + .../lodash/internal/baseFilter.js | 22 + .../node_modules/lodash/internal/baseFind.js | 25 + .../lodash/internal/baseFindIndex.js | 23 + .../lodash/internal/baseFlatten.js | 41 + .../node_modules/lodash/internal/baseFor.js | 17 + .../node_modules/lodash/internal/baseForIn.js | 17 + .../lodash/internal/baseForOwn.js | 17 + .../lodash/internal/baseForOwnRight.js | 17 + .../lodash/internal/baseForRight.js | 15 + .../lodash/internal/baseFunctions.js | 27 + .../node_modules/lodash/internal/baseGet.js | 29 + .../lodash/internal/baseIndexOf.js | 27 + .../lodash/internal/baseIsEqual.js | 28 + .../lodash/internal/baseIsEqualDeep.js | 102 + .../lodash/internal/baseIsFunction.js | 15 + .../lodash/internal/baseIsMatch.js | 52 + .../lodash/internal/baseLodash.js | 10 + .../node_modules/lodash/internal/baseMap.js | 23 + .../lodash/internal/baseMatches.js | 30 + .../lodash/internal/baseMatchesProperty.js | 45 + .../node_modules/lodash/internal/baseMerge.js | 56 + .../lodash/internal/baseMergeDeep.js | 67 + .../lodash/internal/baseProperty.js | 14 + .../lodash/internal/basePropertyDeep.js | 19 + .../lodash/internal/basePullAt.js | 30 + .../lodash/internal/baseRandom.js | 18 + .../lodash/internal/baseReduce.js | 24 + .../lodash/internal/baseSetData.js | 17 + .../node_modules/lodash/internal/baseSlice.js | 32 + .../node_modules/lodash/internal/baseSome.js | 23 + .../lodash/internal/baseSortBy.js | 21 + .../lodash/internal/baseSortByOrder.js | 31 + .../node_modules/lodash/internal/baseSum.js | 20 + .../lodash/internal/baseToString.js | 13 + .../node_modules/lodash/internal/baseUniq.js | 60 + .../lodash/internal/baseValues.js | 22 + .../node_modules/lodash/internal/baseWhile.js | 24 + .../lodash/internal/baseWrapperValue.js | 29 + .../lodash/internal/binaryIndex.js | 39 + .../lodash/internal/binaryIndexBy.js | 57 + .../lodash/internal/bindCallback.js | 39 + .../lodash/internal/bufferClone.js | 20 + .../lodash/internal/cacheIndexOf.js | 19 + .../node_modules/lodash/internal/cachePush.js | 20 + .../lodash/internal/charsLeftIndex.js | 18 + .../lodash/internal/charsRightIndex.js | 17 + .../lodash/internal/compareAscending.js | 16 + .../lodash/internal/compareMultiple.js | 44 + .../lodash/internal/composeArgs.js | 34 + .../lodash/internal/composeArgsRight.js | 36 + .../lodash/internal/createAggregator.js | 35 + .../lodash/internal/createAssigner.js | 41 + .../lodash/internal/createBaseEach.js | 31 + .../lodash/internal/createBaseFor.js | 27 + .../lodash/internal/createBindWrapper.js | 22 + .../lodash/internal/createCache.js | 21 + .../lodash/internal/createCompounder.js | 26 + .../lodash/internal/createCtorWrapper.js | 37 + .../lodash/internal/createCurry.js | 23 + .../lodash/internal/createDefaults.js | 22 + .../lodash/internal/createExtremum.js | 33 + .../lodash/internal/createFind.js | 25 + .../lodash/internal/createFindIndex.js | 21 + .../lodash/internal/createFindKey.js | 18 + .../lodash/internal/createFlow.js | 74 + .../lodash/internal/createForEach.js | 20 + .../lodash/internal/createForIn.js | 20 + .../lodash/internal/createForOwn.js | 19 + .../lodash/internal/createHybridWrapper.js | 111 + .../lodash/internal/createObjectMapper.js | 26 + .../lodash/internal/createPadDir.js | 18 + .../lodash/internal/createPadding.js | 29 + .../lodash/internal/createPartial.js | 20 + .../lodash/internal/createPartialWrapper.js | 43 + .../lodash/internal/createReduce.js | 22 + .../lodash/internal/createRound.js | 23 + .../lodash/internal/createSortedIndex.js | 20 + .../lodash/internal/createWrapper.js | 86 + .../lodash/internal/deburrLetter.js | 33 + .../lodash/internal/equalArrays.js | 51 + .../lodash/internal/equalByTag.js | 48 + .../lodash/internal/equalObjects.js | 67 + .../lodash/internal/escapeHtmlChar.js | 22 + .../lodash/internal/escapeRegExpChar.js | 38 + .../lodash/internal/escapeStringChar.js | 22 + .../node_modules/lodash/internal/getData.js | 15 + .../lodash/internal/getFuncName.js | 25 + .../node_modules/lodash/internal/getLength.js | 15 + .../lodash/internal/getMatchData.js | 21 + .../node_modules/lodash/internal/getNative.js | 16 + .../node_modules/lodash/internal/getView.js | 33 + .../lodash/internal/indexOfNaN.js | 23 + .../lodash/internal/initCloneArray.js | 26 + .../lodash/internal/initCloneByTag.js | 63 + .../lodash/internal/initCloneObject.js | 16 + .../lodash/internal/invokePath.js | 26 + .../lodash/internal/isArrayLike.js | 15 + .../node_modules/lodash/internal/isIndex.js | 24 + .../lodash/internal/isIterateeCall.js | 28 + .../node_modules/lodash/internal/isKey.js | 28 + .../lodash/internal/isLaziable.js | 27 + .../node_modules/lodash/internal/isLength.js | 20 + .../lodash/internal/isObjectLike.js | 12 + .../node_modules/lodash/internal/isSpace.js | 14 + .../lodash/internal/isStrictComparable.js | 15 + .../node_modules/lodash/internal/lazyClone.js | 23 + .../lodash/internal/lazyReverse.js | 23 + .../node_modules/lodash/internal/lazyValue.js | 72 + .../node_modules/lodash/internal/mapDelete.js | 14 + .../node_modules/lodash/internal/mapGet.js | 14 + .../node_modules/lodash/internal/mapHas.js | 20 + .../node_modules/lodash/internal/mapSet.js | 18 + .../node_modules/lodash/internal/mergeData.js | 89 + .../lodash/internal/mergeDefaults.js | 15 + .../node_modules/lodash/internal/metaMap.js | 9 + .../lodash/internal/pickByArray.js | 28 + .../lodash/internal/pickByCallback.js | 22 + .../node_modules/lodash/internal/reEscape.js | 4 + .../lodash/internal/reEvaluate.js | 4 + .../lodash/internal/reInterpolate.js | 4 + .../node_modules/lodash/internal/realNames.js | 4 + .../node_modules/lodash/internal/reorder.js | 29 + .../lodash/internal/replaceHolders.js | 28 + .../node_modules/lodash/internal/setData.js | 41 + .../node_modules/lodash/internal/shimKeys.js | 41 + .../lodash/internal/sortedUniq.js | 29 + .../lodash/internal/toIterable.js | 22 + .../node_modules/lodash/internal/toObject.js | 14 + .../node_modules/lodash/internal/toPath.js | 28 + .../lodash/internal/trimmedLeftIndex.js | 19 + .../lodash/internal/trimmedRightIndex.js | 18 + .../lodash/internal/unescapeHtmlChar.js | 22 + .../lodash/internal/wrapperClone.js | 18 + .../node_modules/lodash/lang.js | 32 + .../node_modules/lodash/lang/clone.js | 70 + .../node_modules/lodash/lang/cloneDeep.js | 55 + .../node_modules/lodash/lang/eq.js | 1 + .../node_modules/lodash/lang/gt.js | 25 + .../node_modules/lodash/lang/gte.js | 25 + .../node_modules/lodash/lang/isArguments.js | 34 + .../node_modules/lodash/lang/isArray.js | 40 + .../node_modules/lodash/lang/isBoolean.js | 35 + .../node_modules/lodash/lang/isDate.js | 35 + .../node_modules/lodash/lang/isElement.js | 24 + .../node_modules/lodash/lang/isEmpty.js | 47 + .../node_modules/lodash/lang/isEqual.js | 54 + .../node_modules/lodash/lang/isError.js | 36 + .../node_modules/lodash/lang/isFinite.js | 35 + .../node_modules/lodash/lang/isFunction.js | 38 + .../node_modules/lodash/lang/isMatch.js | 49 + .../node_modules/lodash/lang/isNaN.js | 34 + .../node_modules/lodash/lang/isNative.js | 48 + .../node_modules/lodash/lang/isNull.js | 21 + .../node_modules/lodash/lang/isNumber.js | 41 + .../node_modules/lodash/lang/isObject.js | 28 + .../node_modules/lodash/lang/isPlainObject.js | 71 + .../node_modules/lodash/lang/isRegExp.js | 35 + .../node_modules/lodash/lang/isString.js | 35 + .../node_modules/lodash/lang/isTypedArray.js | 74 + .../node_modules/lodash/lang/isUndefined.js | 21 + .../node_modules/lodash/lang/lt.js | 25 + .../node_modules/lodash/lang/lte.js | 25 + .../node_modules/lodash/lang/toArray.js | 32 + .../node_modules/lodash/lang/toPlainObject.js | 31 + .../node_modules/lodash/math.js | 9 + .../node_modules/lodash/math/add.js | 19 + .../node_modules/lodash/math/ceil.js | 25 + .../node_modules/lodash/math/floor.js | 25 + .../node_modules/lodash/math/max.js | 56 + .../node_modules/lodash/math/min.js | 56 + .../node_modules/lodash/math/round.js | 25 + .../node_modules/lodash/math/sum.js | 50 + .../node_modules/lodash/number.js | 4 + .../node_modules/lodash/number/inRange.js | 47 + .../node_modules/lodash/number/random.js | 70 + .../node_modules/lodash/object.js | 31 + .../node_modules/lodash/object/assign.js | 43 + .../node_modules/lodash/object/create.js | 47 + .../node_modules/lodash/object/defaults.js | 25 + .../lodash/object/defaultsDeep.js | 25 + .../node_modules/lodash/object/extend.js | 1 + .../node_modules/lodash/object/findKey.js | 54 + .../node_modules/lodash/object/findLastKey.js | 54 + .../node_modules/lodash/object/forIn.js | 33 + .../node_modules/lodash/object/forInRight.js | 31 + .../node_modules/lodash/object/forOwn.js | 33 + .../node_modules/lodash/object/forOwnRight.js | 31 + .../node_modules/lodash/object/functions.js | 23 + .../node_modules/lodash/object/get.js | 33 + .../node_modules/lodash/object/has.js | 57 + .../node_modules/lodash/object/invert.js | 60 + .../node_modules/lodash/object/keys.js | 45 + .../node_modules/lodash/object/keysIn.js | 64 + .../node_modules/lodash/object/mapKeys.js | 25 + .../node_modules/lodash/object/mapValues.js | 46 + .../node_modules/lodash/object/merge.js | 54 + .../node_modules/lodash/object/methods.js | 1 + .../node_modules/lodash/object/omit.js | 47 + .../node_modules/lodash/object/pairs.js | 33 + .../node_modules/lodash/object/pick.js | 42 + .../node_modules/lodash/object/result.js | 49 + .../node_modules/lodash/object/set.js | 55 + .../node_modules/lodash/object/transform.js | 61 + .../node_modules/lodash/object/values.js | 33 + .../node_modules/lodash/object/valuesIn.js | 31 + .../node_modules/lodash/package.json | 121 + .../node_modules/lodash/string.js | 25 + .../node_modules/lodash/string/camelCase.js | 27 + .../node_modules/lodash/string/capitalize.js | 21 + .../node_modules/lodash/string/deburr.js | 29 + .../node_modules/lodash/string/endsWith.js | 40 + .../node_modules/lodash/string/escape.js | 48 + .../lodash/string/escapeRegExp.js | 32 + .../node_modules/lodash/string/kebabCase.js | 26 + .../node_modules/lodash/string/pad.js | 47 + .../node_modules/lodash/string/padLeft.js | 27 + .../node_modules/lodash/string/padRight.js | 27 + .../node_modules/lodash/string/parseInt.js | 46 + .../node_modules/lodash/string/repeat.js | 47 + .../node_modules/lodash/string/snakeCase.js | 26 + .../node_modules/lodash/string/startCase.js | 26 + .../node_modules/lodash/string/startsWith.js | 36 + .../node_modules/lodash/string/template.js | 226 + .../lodash/string/templateSettings.js | 67 + .../node_modules/lodash/string/trim.js | 42 + .../node_modules/lodash/string/trimLeft.js | 36 + .../node_modules/lodash/string/trimRight.js | 36 + .../node_modules/lodash/string/trunc.js | 105 + .../node_modules/lodash/string/unescape.js | 33 + .../node_modules/lodash/string/words.js | 38 + .../node_modules/lodash/support.js | 10 + .../node_modules/lodash/utility.js | 18 + .../node_modules/lodash/utility/attempt.js | 32 + .../node_modules/lodash/utility/callback.js | 53 + .../node_modules/lodash/utility/constant.js | 23 + .../node_modules/lodash/utility/identity.js | 20 + .../node_modules/lodash/utility/iteratee.js | 1 + .../node_modules/lodash/utility/matches.js | 33 + .../lodash/utility/matchesProperty.js | 32 + .../node_modules/lodash/utility/method.js | 33 + .../node_modules/lodash/utility/methodOf.js | 32 + .../node_modules/lodash/utility/mixin.js | 82 + .../node_modules/lodash/utility/noop.js | 19 + .../node_modules/lodash/utility/property.js | 31 + .../node_modules/lodash/utility/propertyOf.js | 30 + .../node_modules/lodash/utility/range.js | 66 + .../node_modules/lodash/utility/times.js | 60 + .../node_modules/lodash/utility/uniqueId.js | 27 + node_modules/express-validator/package.json | 125 + .../express-validator/test/asyncTest.js | 111 + .../test/checkBodySchemaTest.js | 117 + .../express-validator/test/checkBodyTest.js | 116 + .../test/checkParamsSchemaTest.js | 132 + .../express-validator/test/checkParamsTest.js | 119 + .../test/checkQuerySchemaTest.js | 123 + .../express-validator/test/checkQueryTest.js | 111 + .../express-validator/test/checkTest.js | 125 + .../test/customSanitizersTest.js | 73 + .../test/formatParamOutputTest.js | 25 + .../express-validator/test/helpers/app.js | 40 + .../express-validator/test/helpers/example.js | 29 + .../test/mappedOutputTest.js | 52 + .../test/nestedInputSanitizeTest.js | 40 + .../express-validator/test/nestedInputTest.js | 61 + .../test/optionalSchemaTest.js | 98 + .../express-validator/test/optionalTest.js | 81 + .../express-validator/test/regexRouteTest.js | 51 + .../test/sanitizeBodyTest.js | 46 + .../test/sanitizeHeadersTest.js | 45 + .../test/sanitizeParamsTest.js | 65 + .../test/sanitizeQueryTest.js | 65 + .../test/sanitizerResultTest.js | 87 + .../express-validator/test/sanitizerTest.js | 104 + .../express-validator/test/withMessageTest.js | 93 + node_modules/eyes/LICENSE | 20 + node_modules/eyes/Makefile | 4 + node_modules/eyes/README.md | 73 + node_modules/eyes/lib/eyes.js | 236 + node_modules/eyes/package.json | 87 + node_modules/eyes/test/eyes-test.js | 56 + node_modules/isstream/.jshintrc | 59 + node_modules/isstream/.npmignore | 1 + node_modules/isstream/.travis.yml | 12 + .../node_modules/nan => isstream}/LICENSE.md | 6 +- node_modules/isstream/README.md | 66 + node_modules/isstream/isstream.js | 27 + node_modules/isstream/package.json | 85 + node_modules/isstream/test.js | 168 + .../mongodb/node_modules/kerberos/.travis.yml | 20 - .../mongodb/node_modules/kerberos/HISTORY.md | 7 - .../mongodb/node_modules/kerberos/LICENSE | 201 - .../mongodb/node_modules/kerberos/README.md | 70 - .../mongodb/node_modules/kerberos/binding.gyp | 46 - .../node_modules/kerberos/build/Makefile | 350 - .../Release/.deps/Release/kerberos.node.d | 1 - .../obj.target/kerberos/lib/base64.o.d | 4 - .../obj.target/kerberos/lib/kerberos.o.d | 57 - .../kerberos/lib/kerberos_context.o.d | 56 - .../obj.target/kerberos/lib/kerberosgss.o.d | 6 - .../obj.target/kerberos/lib/worker.o.d | 53 - .../kerberos/build/Release/kerberos.node | Bin 78976 -> 0 bytes .../kerberos/build/Release/linker.lock | 0 .../Release/obj.target/kerberos/lib/base64.o | Bin 5680 -> 0 bytes .../obj.target/kerberos/lib/kerberos.o | Bin 377020 -> 0 bytes .../kerberos/lib/kerberos_context.o | Bin 187476 -> 0 bytes .../obj.target/kerberos/lib/kerberosgss.o | Bin 27436 -> 0 bytes .../Release/obj.target/kerberos/lib/worker.o | Bin 85728 -> 0 bytes .../kerberos/build/binding.Makefile | 6 - .../node_modules/kerberos/build/config.gypi | 128 - .../node_modules/kerberos/build/gyp-mac-tool | 512 - .../kerberos/build/kerberos.target.mk | 172 - .../mongodb/node_modules/kerberos/index.js | 6 - .../kerberos/lib/auth_processes/mongodb.js | 281 - .../node_modules/kerberos/lib/base64.c | 134 - .../node_modules/kerberos/lib/base64.h | 22 - .../node_modules/kerberos/lib/kerberos.cc | 893 -- .../node_modules/kerberos/lib/kerberos.h | 50 - .../node_modules/kerberos/lib/kerberos.js | 164 - .../kerberos/lib/kerberos_context.cc | 134 - .../kerberos/lib/kerberos_context.h | 64 - .../node_modules/kerberos/lib/kerberosgss.c | 931 -- .../node_modules/kerberos/lib/kerberosgss.h | 73 - .../mongodb/node_modules/kerberos/lib/sspi.js | 15 - .../node_modules/kerberos/lib/win32/base64.c | 121 - .../node_modules/kerberos/lib/win32/base64.h | 18 - .../kerberos/lib/win32/kerberos.cc | 51 - .../kerberos/lib/win32/kerberos.h | 60 - .../kerberos/lib/win32/kerberos_sspi.c | 244 - .../kerberos/lib/win32/kerberos_sspi.h | 106 - .../node_modules/kerberos/lib/win32/worker.cc | 7 - .../node_modules/kerberos/lib/win32/worker.h | 38 - .../lib/win32/wrappers/security_buffer.cc | 101 - .../lib/win32/wrappers/security_buffer.h | 48 - .../lib/win32/wrappers/security_buffer.js | 12 - .../wrappers/security_buffer_descriptor.cc | 182 - .../wrappers/security_buffer_descriptor.h | 46 - .../wrappers/security_buffer_descriptor.js | 3 - .../lib/win32/wrappers/security_context.cc | 856 -- .../lib/win32/wrappers/security_context.h | 74 - .../lib/win32/wrappers/security_context.js | 3 - .../win32/wrappers/security_credentials.cc | 348 - .../lib/win32/wrappers/security_credentials.h | 68 - .../win32/wrappers/security_credentials.js | 22 - .../node_modules/kerberos/lib/worker.cc | 7 - .../node_modules/kerberos/lib/worker.h | 38 - .../kerberos/node_modules/nan/.dntrc | 30 - .../kerberos/node_modules/nan/CHANGELOG.md | 374 - .../kerberos/node_modules/nan/README.md | 367 - .../kerberos/node_modules/nan/appveyor.yml | 38 - .../kerberos/node_modules/nan/doc/.build.sh | 38 - .../node_modules/nan/doc/asyncworker.md | 97 - .../kerberos/node_modules/nan/doc/buffers.md | 54 - .../kerberos/node_modules/nan/doc/callback.md | 52 - .../node_modules/nan/doc/converters.md | 41 - .../kerberos/node_modules/nan/doc/errors.md | 226 - .../node_modules/nan/doc/maybe_types.md | 480 - .../kerberos/node_modules/nan/doc/methods.md | 624 - .../kerberos/node_modules/nan/doc/new.md | 141 - .../node_modules/nan/doc/node_misc.md | 114 - .../node_modules/nan/doc/persistent.md | 292 - .../kerberos/node_modules/nan/doc/scopes.md | 73 - .../kerberos/node_modules/nan/doc/script.md | 38 - .../node_modules/nan/doc/string_bytes.md | 62 - .../node_modules/nan/doc/v8_internals.md | 199 - .../kerberos/node_modules/nan/doc/v8_misc.md | 63 - .../kerberos/node_modules/nan/include_dirs.js | 1 - .../kerberos/node_modules/nan/nan.h | 2136 --- .../kerberos/node_modules/nan/nan_callbacks.h | 88 - .../node_modules/nan/nan_callbacks_12_inl.h | 512 - .../nan/nan_callbacks_pre_12_inl.h | 506 - .../node_modules/nan/nan_converters.h | 64 - .../node_modules/nan/nan_converters_43_inl.h | 42 - .../nan/nan_converters_pre_43_inl.h | 42 - .../nan/nan_implementation_12_inl.h | 399 - .../nan/nan_implementation_pre_12_inl.h | 259 - .../node_modules/nan/nan_maybe_43_inl.h | 224 - .../node_modules/nan/nan_maybe_pre_43_inl.h | 295 - .../kerberos/node_modules/nan/nan_new.h | 332 - .../node_modules/nan/nan_object_wrap.h | 155 - .../node_modules/nan/nan_persistent_12_inl.h | 129 - .../nan/nan_persistent_pre_12_inl.h | 238 - .../node_modules/nan/nan_string_bytes.h | 305 - .../kerberos/node_modules/nan/nan_weak.h | 422 - .../kerberos/node_modules/nan/package.json | 91 - .../kerberos/node_modules/nan/tools/1to2.js | 412 - .../kerberos/node_modules/nan/tools/README.md | 14 - .../node_modules/nan/tools/package.json | 19 - .../node_modules/kerberos/package.json | 55 - .../kerberos/test/kerberos_tests.js | 34 - .../kerberos/test/kerberos_win32_test.js | 15 - .../win32/security_buffer_descriptor_tests.js | 41 - .../test/win32/security_buffer_tests.js | 22 - .../test/win32/security_credentials_tests.js | 55 - node_modules/pkginfo/.npmignore | 2 + node_modules/pkginfo/LICENSE | 19 + node_modules/pkginfo/README.md | 86 + node_modules/pkginfo/docs/docco.css | 194 + node_modules/pkginfo/docs/pkginfo.html | 101 + .../pkginfo/examples/all-properties.js | 19 + .../pkginfo/examples/array-argument.js | 20 + .../pkginfo/examples/multiple-properties.js | 19 + .../pkginfo/examples/object-argument.js | 22 + node_modules/pkginfo/examples/package.json | 10 + .../pkginfo/examples/single-property.js | 19 + .../pkginfo/examples/subdir/package.json | 11 + node_modules/pkginfo/examples/target-dir.js | 20 + node_modules/pkginfo/lib/pkginfo.js | 136 + node_modules/pkginfo/package.json | 82 + node_modules/pkginfo/test/pkginfo-test.js | 83 + node_modules/stack-trace/.npmignore | 1 + node_modules/stack-trace/License | 19 + node_modules/stack-trace/Makefile | 11 + node_modules/stack-trace/Readme.md | 98 + node_modules/stack-trace/lib/stack-trace.js | 111 + node_modules/stack-trace/package.json | 81 + node_modules/validator/.jshintrc | 3 + node_modules/validator/.npmignore | 3 + node_modules/validator/.travis.yml | 7 + node_modules/validator/CHANGELOG.md | 61 + node_modules/validator/LICENSE | 20 + node_modules/validator/Makefile | 34 + node_modules/validator/README.md | 179 + node_modules/validator/bower.json | 19 + node_modules/validator/package.json | 92 + node_modules/validator/test/client-side.js | 26 + node_modules/validator/test/exports.js | 21 + node_modules/validator/test/sanitizers.js | 223 + node_modules/validator/test/validators.js | 2342 +++ node_modules/validator/validator.js | 863 ++ node_modules/validator/validator.min.js | 23 + node_modules/winston/CHANGELOG.md | 188 + node_modules/winston/LICENSE | 19 + node_modules/winston/README.md | 833 ++ node_modules/winston/lib/winston.js | 165 + node_modules/winston/lib/winston/common.js | 483 + node_modules/winston/lib/winston/config.js | 68 + .../winston/lib/winston/config/cli-config.js | 35 + .../winston/lib/winston/config/npm-config.js | 27 + .../lib/winston/config/syslog-config.js | 31 + node_modules/winston/lib/winston/container.js | 127 + node_modules/winston/lib/winston/exception.js | 56 + node_modules/winston/lib/winston/logger.js | 723 + .../winston/lib/winston/transports.js | 29 + .../winston/lib/winston/transports/console.js | 130 + .../winston/lib/winston/transports/file.js | 678 + .../winston/lib/winston/transports/http.js | 232 + .../winston/lib/winston/transports/memory.js | 89 + .../lib/winston/transports/transport.js | 135 + .../winston/node_modules/async/.jshintrc | 24 + .../winston/node_modules/async/.travis.yml | 5 + .../winston/node_modules/async/CHANGELOG.md | 16 + .../winston/node_modules/async/LICENSE | 19 + .../winston/node_modules/async/README.md | 1720 +++ .../winston/node_modules/async/bower.json | 40 + .../winston/node_modules/async/component.json | 17 + .../winston/node_modules/async/lib/async.js | 1283 ++ .../winston/node_modules/async/package.json | 117 + .../async/support/sync-package-managers.js | 53 + node_modules/winston/package.json | 114 + node_modules/winston/test/helpers.js | 256 + .../winston/test/transports/console-test.js | 202 + .../test/transports/file-archive-test.js | 83 + .../test/transports/file-maxfiles-test.js | 102 + .../test/transports/file-maxsize-test.js | 82 + .../winston/test/transports/file-open-test.js | 57 + .../test/transports/file-stress-test.js | 72 + .../test/transports/file-tailrolling-test.js | 92 + .../winston/test/transports/file-test.js | 134 + .../winston/test/transports/http-test.js | 70 + .../winston/test/transports/memory-test.js | 31 + .../winston/test/transports/transport.js | 212 + package.json | 6 +- public/js/app.js | 290 +- public/js/controllers.js | 2550 ++-- public/js/controllers/checkLists.js | 36 +- public/js/controllers/deviceTypes.js | 500 +- public/js/controllers/devices.js | 50 +- public/js/controllers/testRuns.js | 18 +- public/js/directives.js | 1561 +- server.js | 2 +- 805 files changed, 67409 insertions(+), 24609 deletions(-) delete mode 100644 app/controllers/clock.js create mode 100644 app/controllers/db.js create mode 100644 app/controllers/timesheet.js create mode 100644 app/model/timeClockException.js create mode 100644 app/routes/exceptions.js create mode 100644 app/routes/index.js create mode 100644 app/routes/misc.js create mode 100644 app/routes/spans.js create mode 100644 app/routes/users.js create mode 100644 app/routes/workorders.js create mode 100644 app/templates/exception.html.tmpl create mode 100644 app/templates/exception.text.tmpl create mode 100644 app/templates/partsRequest.html.tmpl create mode 100644 app/templates/partsRequest.text.tmpl create mode 100644 app/util/email.js create mode 100644 config/db.js create mode 100644 config/promise.js create mode 100644 config/validators.js create mode 100644 node_modules/bluebird/changelog.md rename node_modules/bluebird/js/{main => release}/any.js (100%) create mode 100644 node_modules/bluebird/js/release/assert.js create mode 100644 node_modules/bluebird/js/release/async.js create mode 100644 node_modules/bluebird/js/release/bind.js create mode 100644 node_modules/bluebird/js/release/bluebird.js create mode 100644 node_modules/bluebird/js/release/call_get.js create mode 100644 node_modules/bluebird/js/release/cancel.js create mode 100644 node_modules/bluebird/js/release/catch_filter.js create mode 100644 node_modules/bluebird/js/release/context.js create mode 100644 node_modules/bluebird/js/release/debuggability.js create mode 100644 node_modules/bluebird/js/release/direct_resolve.js create mode 100644 node_modules/bluebird/js/release/each.js create mode 100644 node_modules/bluebird/js/release/errors.js rename node_modules/bluebird/js/{main => release}/es5.js (100%) rename node_modules/bluebird/js/{main => release}/filter.js (100%) create mode 100644 node_modules/bluebird/js/release/finally.js create mode 100644 node_modules/bluebird/js/release/generators.js create mode 100644 node_modules/bluebird/js/release/join.js create mode 100644 node_modules/bluebird/js/release/map.js create mode 100644 node_modules/bluebird/js/release/method.js create mode 100644 node_modules/bluebird/js/release/nodeback.js create mode 100644 node_modules/bluebird/js/release/nodeify.js create mode 100644 node_modules/bluebird/js/release/promise.js create mode 100644 node_modules/bluebird/js/release/promise_array.js create mode 100644 node_modules/bluebird/js/release/promisify.js create mode 100644 node_modules/bluebird/js/release/props.js rename node_modules/bluebird/js/{main => release}/queue.js (100%) create mode 100644 node_modules/bluebird/js/release/race.js create mode 100644 node_modules/bluebird/js/release/reduce.js create mode 100644 node_modules/bluebird/js/release/schedule.js create mode 100644 node_modules/bluebird/js/release/settle.js create mode 100644 node_modules/bluebird/js/release/some.js create mode 100644 node_modules/bluebird/js/release/synchronous_inspection.js create mode 100644 node_modules/bluebird/js/release/thenables.js create mode 100644 node_modules/bluebird/js/release/timers.js create mode 100644 node_modules/bluebird/js/release/using.js create mode 100644 node_modules/bluebird/js/release/util.js create mode 100644 node_modules/colors/.travis.yml create mode 100644 node_modules/colors/MIT-LICENSE.txt create mode 100644 node_modules/colors/ReadMe.md create mode 100644 node_modules/colors/examples/normal-usage.js create mode 100644 node_modules/colors/examples/safe-string.js create mode 100644 node_modules/colors/lib/colors.js create mode 100644 node_modules/colors/lib/custom/trap.js create mode 100644 node_modules/colors/lib/custom/zalgo.js create mode 100644 node_modules/colors/lib/extendStringPrototype.js create mode 100644 node_modules/colors/lib/index.js create mode 100644 node_modules/colors/lib/maps/america.js create mode 100644 node_modules/colors/lib/maps/rainbow.js create mode 100644 node_modules/colors/lib/maps/random.js create mode 100644 node_modules/colors/lib/maps/zebra.js create mode 100644 node_modules/colors/lib/styles.js create mode 100644 node_modules/colors/lib/system/supports-colors.js create mode 100644 node_modules/colors/package.json create mode 100644 node_modules/colors/safe.js create mode 100644 node_modules/colors/screenshots/colors.png create mode 100644 node_modules/colors/tests/basic-test.js create mode 100644 node_modules/colors/tests/safe-test.js create mode 100644 node_modules/colors/themes/generic-logging.js create mode 100644 node_modules/cycle/README.md create mode 100644 node_modules/cycle/cycle.js create mode 100644 node_modules/cycle/package.json create mode 100644 node_modules/express-validator/.editorconfig create mode 100644 node_modules/express-validator/.jscsrc create mode 100644 node_modules/express-validator/.jshintrc create mode 100644 node_modules/express-validator/.npmignore create mode 100644 node_modules/express-validator/.travis.yml create mode 100644 node_modules/express-validator/CHANGELOG.md create mode 100644 node_modules/express-validator/LICENSE create mode 100644 node_modules/express-validator/README.md create mode 100644 node_modules/express-validator/index.js create mode 100644 node_modules/express-validator/lib/express_validator.js create mode 100644 node_modules/express-validator/node_modules/bluebird/LICENSE create mode 100644 node_modules/express-validator/node_modules/bluebird/README.md create mode 100644 node_modules/express-validator/node_modules/bluebird/changelog.md create mode 100644 node_modules/express-validator/node_modules/bluebird/js/browser/bluebird.js create mode 100644 node_modules/express-validator/node_modules/bluebird/js/browser/bluebird.min.js create mode 100644 node_modules/express-validator/node_modules/bluebird/js/main/any.js rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/assert.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/async.js (63%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/bind.js (91%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/bluebird.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/call_get.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/cancel.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/captured_trace.js (99%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/catch_filter.js (98%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/context.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/debuggability.js (86%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/direct_resolve.js (75%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/each.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/errors.js (100%) create mode 100644 node_modules/express-validator/node_modules/bluebird/js/main/es5.js create mode 100644 node_modules/express-validator/node_modules/bluebird/js/main/filter.js rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/finally.js (91%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/generators.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/join.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/map.js (95%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/method.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/nodeify.js (85%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/progress.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/promise.js (90%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/promise_array.js (98%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/promise_resolver.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/promisify.js (91%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/props.js (100%) create mode 100644 node_modules/express-validator/node_modules/bluebird/js/main/queue.js rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/race.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/reduce.js (96%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/schedule.js (57%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/settle.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/some.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/synchronous_inspection.js (100%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/thenables.js (91%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/timers.js (85%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/using.js (93%) rename node_modules/{ => express-validator/node_modules}/bluebird/js/main/util.js (77%) create mode 100644 node_modules/express-validator/node_modules/bluebird/package.json create mode 100644 node_modules/express-validator/node_modules/lodash/LICENSE create mode 100644 node_modules/express-validator/node_modules/lodash/README.md create mode 100644 node_modules/express-validator/node_modules/lodash/array.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/chunk.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/compact.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/difference.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/drop.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/dropRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/dropRightWhile.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/dropWhile.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/fill.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/findIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/findLastIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/first.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/flatten.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/flattenDeep.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/head.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/indexOf.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/initial.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/intersection.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/last.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/lastIndexOf.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/object.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/pull.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/pullAt.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/remove.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/rest.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/slice.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/sortedIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/sortedLastIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/tail.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/take.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/takeRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/takeRightWhile.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/takeWhile.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/union.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/uniq.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/unique.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/unzip.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/unzipWith.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/without.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/xor.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/zip.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/zipObject.js create mode 100644 node_modules/express-validator/node_modules/lodash/array/zipWith.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/chain.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/commit.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/concat.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/lodash.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/plant.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/reverse.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/run.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/tap.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/thru.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/toJSON.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/toString.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/value.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/valueOf.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/wrapperChain.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/wrapperCommit.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/wrapperConcat.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/wrapperPlant.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/wrapperReverse.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/wrapperToString.js create mode 100644 node_modules/express-validator/node_modules/lodash/chain/wrapperValue.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/all.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/any.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/at.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/collect.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/contains.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/countBy.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/detect.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/each.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/eachRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/every.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/filter.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/find.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/findLast.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/findWhere.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/foldl.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/foldr.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/forEach.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/forEachRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/groupBy.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/include.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/includes.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/indexBy.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/inject.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/invoke.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/map.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/max.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/min.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/partition.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/pluck.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/reduce.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/reduceRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/reject.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/sample.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/select.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/shuffle.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/size.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/some.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/sortBy.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/sortByAll.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/sortByOrder.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/sum.js create mode 100644 node_modules/express-validator/node_modules/lodash/collection/where.js create mode 100644 node_modules/express-validator/node_modules/lodash/date.js create mode 100644 node_modules/express-validator/node_modules/lodash/date/now.js create mode 100644 node_modules/express-validator/node_modules/lodash/function.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/after.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/ary.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/backflow.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/before.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/bind.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/bindAll.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/bindKey.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/compose.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/curry.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/curryRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/debounce.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/defer.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/delay.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/flow.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/flowRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/memoize.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/modArgs.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/negate.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/once.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/partial.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/partialRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/rearg.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/restParam.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/spread.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/throttle.js create mode 100644 node_modules/express-validator/node_modules/lodash/function/wrap.js create mode 100644 node_modules/express-validator/node_modules/lodash/index.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/LazyWrapper.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/LodashWrapper.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/MapCache.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/SetCache.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayConcat.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayCopy.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayEach.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayEachRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayEvery.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayExtremum.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayFilter.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayMap.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayPush.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayReduce.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arrayReduceRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arraySome.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/arraySum.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/assignDefaults.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/assignOwnDefaults.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/assignWith.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseAssign.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseAt.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseCallback.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseClone.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseCompareAscending.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseCopy.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseCreate.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseDelay.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseDifference.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseEach.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseEachRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseEvery.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseExtremum.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseFill.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseFilter.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseFind.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseFindIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseFlatten.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseFor.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseForIn.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseForOwn.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseForOwnRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseForRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseFunctions.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseGet.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseIndexOf.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseIsEqual.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseIsEqualDeep.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseIsFunction.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseIsMatch.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseLodash.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseMap.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseMatches.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseMatchesProperty.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseMerge.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseMergeDeep.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseProperty.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/basePropertyDeep.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/basePullAt.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseRandom.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseReduce.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseSetData.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseSlice.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseSome.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseSortBy.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseSortByOrder.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseSum.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseToString.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseUniq.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseValues.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseWhile.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/baseWrapperValue.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/binaryIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/binaryIndexBy.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/bindCallback.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/bufferClone.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/cacheIndexOf.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/cachePush.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/charsLeftIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/charsRightIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/compareAscending.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/compareMultiple.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/composeArgs.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/composeArgsRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createAggregator.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createAssigner.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createBaseEach.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createBaseFor.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createBindWrapper.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createCache.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createCompounder.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createCtorWrapper.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createCurry.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createDefaults.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createExtremum.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createFind.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createFindIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createFindKey.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createFlow.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createForEach.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createForIn.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createForOwn.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createHybridWrapper.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createObjectMapper.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createPadDir.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createPadding.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createPartial.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createPartialWrapper.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createReduce.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createRound.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createSortedIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/createWrapper.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/deburrLetter.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/equalArrays.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/equalByTag.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/equalObjects.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/escapeHtmlChar.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/escapeRegExpChar.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/escapeStringChar.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/getData.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/getFuncName.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/getLength.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/getMatchData.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/getNative.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/getView.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/indexOfNaN.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/initCloneArray.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/initCloneByTag.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/initCloneObject.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/invokePath.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/isArrayLike.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/isIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/isIterateeCall.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/isKey.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/isLaziable.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/isLength.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/isObjectLike.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/isSpace.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/isStrictComparable.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/lazyClone.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/lazyReverse.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/lazyValue.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/mapDelete.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/mapGet.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/mapHas.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/mapSet.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/mergeData.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/mergeDefaults.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/metaMap.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/pickByArray.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/pickByCallback.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/reEscape.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/reEvaluate.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/reInterpolate.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/realNames.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/reorder.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/replaceHolders.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/setData.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/shimKeys.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/sortedUniq.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/toIterable.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/toObject.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/toPath.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/trimmedLeftIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/trimmedRightIndex.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/unescapeHtmlChar.js create mode 100644 node_modules/express-validator/node_modules/lodash/internal/wrapperClone.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/clone.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/cloneDeep.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/eq.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/gt.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/gte.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isArguments.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isArray.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isBoolean.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isDate.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isElement.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isEmpty.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isEqual.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isError.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isFinite.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isFunction.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isMatch.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isNaN.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isNative.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isNull.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isNumber.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isObject.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isPlainObject.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isRegExp.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isString.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isTypedArray.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/isUndefined.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/lt.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/lte.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/toArray.js create mode 100644 node_modules/express-validator/node_modules/lodash/lang/toPlainObject.js create mode 100644 node_modules/express-validator/node_modules/lodash/math.js create mode 100644 node_modules/express-validator/node_modules/lodash/math/add.js create mode 100644 node_modules/express-validator/node_modules/lodash/math/ceil.js create mode 100644 node_modules/express-validator/node_modules/lodash/math/floor.js create mode 100644 node_modules/express-validator/node_modules/lodash/math/max.js create mode 100644 node_modules/express-validator/node_modules/lodash/math/min.js create mode 100644 node_modules/express-validator/node_modules/lodash/math/round.js create mode 100644 node_modules/express-validator/node_modules/lodash/math/sum.js create mode 100644 node_modules/express-validator/node_modules/lodash/number.js create mode 100644 node_modules/express-validator/node_modules/lodash/number/inRange.js create mode 100644 node_modules/express-validator/node_modules/lodash/number/random.js create mode 100644 node_modules/express-validator/node_modules/lodash/object.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/assign.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/create.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/defaults.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/defaultsDeep.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/extend.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/findKey.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/findLastKey.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/forIn.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/forInRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/forOwn.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/forOwnRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/functions.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/get.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/has.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/invert.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/keys.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/keysIn.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/mapKeys.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/mapValues.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/merge.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/methods.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/omit.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/pairs.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/pick.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/result.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/set.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/transform.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/values.js create mode 100644 node_modules/express-validator/node_modules/lodash/object/valuesIn.js create mode 100644 node_modules/express-validator/node_modules/lodash/package.json create mode 100644 node_modules/express-validator/node_modules/lodash/string.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/camelCase.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/capitalize.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/deburr.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/endsWith.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/escape.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/escapeRegExp.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/kebabCase.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/pad.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/padLeft.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/padRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/parseInt.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/repeat.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/snakeCase.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/startCase.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/startsWith.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/template.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/templateSettings.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/trim.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/trimLeft.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/trimRight.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/trunc.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/unescape.js create mode 100644 node_modules/express-validator/node_modules/lodash/string/words.js create mode 100644 node_modules/express-validator/node_modules/lodash/support.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/attempt.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/callback.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/constant.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/identity.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/iteratee.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/matches.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/matchesProperty.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/method.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/methodOf.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/mixin.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/noop.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/property.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/propertyOf.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/range.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/times.js create mode 100644 node_modules/express-validator/node_modules/lodash/utility/uniqueId.js create mode 100644 node_modules/express-validator/package.json create mode 100644 node_modules/express-validator/test/asyncTest.js create mode 100644 node_modules/express-validator/test/checkBodySchemaTest.js create mode 100644 node_modules/express-validator/test/checkBodyTest.js create mode 100644 node_modules/express-validator/test/checkParamsSchemaTest.js create mode 100644 node_modules/express-validator/test/checkParamsTest.js create mode 100644 node_modules/express-validator/test/checkQuerySchemaTest.js create mode 100644 node_modules/express-validator/test/checkQueryTest.js create mode 100644 node_modules/express-validator/test/checkTest.js create mode 100644 node_modules/express-validator/test/customSanitizersTest.js create mode 100644 node_modules/express-validator/test/formatParamOutputTest.js create mode 100644 node_modules/express-validator/test/helpers/app.js create mode 100644 node_modules/express-validator/test/helpers/example.js create mode 100644 node_modules/express-validator/test/mappedOutputTest.js create mode 100644 node_modules/express-validator/test/nestedInputSanitizeTest.js create mode 100644 node_modules/express-validator/test/nestedInputTest.js create mode 100644 node_modules/express-validator/test/optionalSchemaTest.js create mode 100644 node_modules/express-validator/test/optionalTest.js create mode 100644 node_modules/express-validator/test/regexRouteTest.js create mode 100644 node_modules/express-validator/test/sanitizeBodyTest.js create mode 100644 node_modules/express-validator/test/sanitizeHeadersTest.js create mode 100644 node_modules/express-validator/test/sanitizeParamsTest.js create mode 100644 node_modules/express-validator/test/sanitizeQueryTest.js create mode 100644 node_modules/express-validator/test/sanitizerResultTest.js create mode 100644 node_modules/express-validator/test/sanitizerTest.js create mode 100644 node_modules/express-validator/test/withMessageTest.js create mode 100644 node_modules/eyes/LICENSE create mode 100644 node_modules/eyes/Makefile create mode 100644 node_modules/eyes/README.md create mode 100644 node_modules/eyes/lib/eyes.js create mode 100644 node_modules/eyes/package.json create mode 100644 node_modules/eyes/test/eyes-test.js create mode 100644 node_modules/isstream/.jshintrc create mode 100644 node_modules/isstream/.npmignore create mode 100644 node_modules/isstream/.travis.yml rename node_modules/{mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan => isstream}/LICENSE.md (87%) create mode 100644 node_modules/isstream/README.md create mode 100644 node_modules/isstream/isstream.js create mode 100644 node_modules/isstream/package.json create mode 100644 node_modules/isstream/test.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/.travis.yml delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/HISTORY.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/LICENSE delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/README.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/binding.gyp delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Makefile delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d delete mode 100755 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/linker.lock delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/config.gypi delete mode 100755 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/gyp-mac-tool delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/index.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.c delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/base64.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/sspi.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.cc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/lib/worker.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/.dntrc delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/CHANGELOG.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/README.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/appveyor.yml delete mode 100755 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/.build.sh delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/asyncworker.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/buffers.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/callback.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/converters.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/errors.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/maybe_types.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/methods.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/new.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/node_misc.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/persistent.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/scopes.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/script.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/string_bytes.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/v8_internals.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/doc/v8_misc.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/include_dirs.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_callbacks.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_callbacks_12_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_callbacks_pre_12_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_converters.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_converters_43_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_converters_pre_43_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_maybe_43_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_maybe_pre_43_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_new.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_object_wrap.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_persistent_12_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_persistent_pre_12_inl.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_string_bytes.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/nan_weak.h delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/package.json delete mode 100755 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/tools/1to2.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/tools/README.md delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/node_modules/nan/tools/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/package.json delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js delete mode 100644 node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js create mode 100644 node_modules/pkginfo/.npmignore create mode 100644 node_modules/pkginfo/LICENSE create mode 100644 node_modules/pkginfo/README.md create mode 100644 node_modules/pkginfo/docs/docco.css create mode 100644 node_modules/pkginfo/docs/pkginfo.html create mode 100644 node_modules/pkginfo/examples/all-properties.js create mode 100644 node_modules/pkginfo/examples/array-argument.js create mode 100644 node_modules/pkginfo/examples/multiple-properties.js create mode 100644 node_modules/pkginfo/examples/object-argument.js create mode 100644 node_modules/pkginfo/examples/package.json create mode 100644 node_modules/pkginfo/examples/single-property.js create mode 100644 node_modules/pkginfo/examples/subdir/package.json create mode 100644 node_modules/pkginfo/examples/target-dir.js create mode 100644 node_modules/pkginfo/lib/pkginfo.js create mode 100644 node_modules/pkginfo/package.json create mode 100644 node_modules/pkginfo/test/pkginfo-test.js create mode 100644 node_modules/stack-trace/.npmignore create mode 100644 node_modules/stack-trace/License create mode 100644 node_modules/stack-trace/Makefile create mode 100644 node_modules/stack-trace/Readme.md create mode 100644 node_modules/stack-trace/lib/stack-trace.js create mode 100644 node_modules/stack-trace/package.json create mode 100644 node_modules/validator/.jshintrc create mode 100644 node_modules/validator/.npmignore create mode 100644 node_modules/validator/.travis.yml create mode 100644 node_modules/validator/CHANGELOG.md create mode 100644 node_modules/validator/LICENSE create mode 100644 node_modules/validator/Makefile create mode 100644 node_modules/validator/README.md create mode 100644 node_modules/validator/bower.json create mode 100644 node_modules/validator/package.json create mode 100644 node_modules/validator/test/client-side.js create mode 100644 node_modules/validator/test/exports.js create mode 100644 node_modules/validator/test/sanitizers.js create mode 100644 node_modules/validator/test/validators.js create mode 100644 node_modules/validator/validator.js create mode 100644 node_modules/validator/validator.min.js create mode 100644 node_modules/winston/CHANGELOG.md create mode 100644 node_modules/winston/LICENSE create mode 100644 node_modules/winston/README.md create mode 100644 node_modules/winston/lib/winston.js create mode 100644 node_modules/winston/lib/winston/common.js create mode 100644 node_modules/winston/lib/winston/config.js create mode 100644 node_modules/winston/lib/winston/config/cli-config.js create mode 100644 node_modules/winston/lib/winston/config/npm-config.js create mode 100644 node_modules/winston/lib/winston/config/syslog-config.js create mode 100644 node_modules/winston/lib/winston/container.js create mode 100644 node_modules/winston/lib/winston/exception.js create mode 100755 node_modules/winston/lib/winston/logger.js create mode 100644 node_modules/winston/lib/winston/transports.js create mode 100644 node_modules/winston/lib/winston/transports/console.js create mode 100644 node_modules/winston/lib/winston/transports/file.js create mode 100644 node_modules/winston/lib/winston/transports/http.js create mode 100644 node_modules/winston/lib/winston/transports/memory.js create mode 100644 node_modules/winston/lib/winston/transports/transport.js create mode 100644 node_modules/winston/node_modules/async/.jshintrc create mode 100644 node_modules/winston/node_modules/async/.travis.yml create mode 100644 node_modules/winston/node_modules/async/CHANGELOG.md create mode 100644 node_modules/winston/node_modules/async/LICENSE create mode 100644 node_modules/winston/node_modules/async/README.md create mode 100644 node_modules/winston/node_modules/async/bower.json create mode 100644 node_modules/winston/node_modules/async/component.json create mode 100644 node_modules/winston/node_modules/async/lib/async.js create mode 100644 node_modules/winston/node_modules/async/package.json create mode 100755 node_modules/winston/node_modules/async/support/sync-package-managers.js create mode 100644 node_modules/winston/package.json create mode 100644 node_modules/winston/test/helpers.js create mode 100644 node_modules/winston/test/transports/console-test.js create mode 100644 node_modules/winston/test/transports/file-archive-test.js create mode 100644 node_modules/winston/test/transports/file-maxfiles-test.js create mode 100644 node_modules/winston/test/transports/file-maxsize-test.js create mode 100644 node_modules/winston/test/transports/file-open-test.js create mode 100644 node_modules/winston/test/transports/file-stress-test.js create mode 100644 node_modules/winston/test/transports/file-tailrolling-test.js create mode 100644 node_modules/winston/test/transports/file-test.js create mode 100644 node_modules/winston/test/transports/http-test.js create mode 100644 node_modules/winston/test/transports/memory-test.js create mode 100644 node_modules/winston/test/transports/transport.js diff --git a/app/controllers/clock.js b/app/controllers/clock.js deleted file mode 100644 index c6a8f14..0000000 --- a/app/controllers/clock.js +++ /dev/null @@ -1,42 +0,0 @@ -var mongoose = require('mongoose'), - Clock = mongoose.model('Clock'); - -module.exports = function(piler) { - return { - index: function(req, res, next) { - host = String(req.headers['x-forwarded-host']); - host = host.split(':')[0]; - - if (host != 'clock.atlb.co') { - return next(); - } - - if (!req.user) { - req.session.redirectUrl = req.url - } - - var path = req.path.slice(1); - - res.render('clock.jade', { - css: piler.css.renderTags() - }); - }, - post: function(req, res) { - var clock = new Clock({ - tech: req.user, - action: req.body.action, - lat: req.body.lat, - long: req.body.long, - dt: new Date() - }); - - clock.save(function(err, result) { - if (err) { - return res.json(500, err); - } else { - res.json(result); - } - }); - } - } -} diff --git a/app/controllers/db.js b/app/controllers/db.js new file mode 100644 index 0000000..b530bf6 --- /dev/null +++ b/app/controllers/db.js @@ -0,0 +1,64 @@ +var mongoose = require('mongoose'); + +var TimeClockSpan = mongoose.model('TimeClockSpan'); +var Workorder = mongoose.model('Workorder'); + +var db = {}; + +db.spans = { + forWeek: function(week) { + const startOfWeek = week.clone(); + const endOfWeek = week.clone().endOf('week'); + + const query = { + start: { + $gte: startOfWeek, + $lte: endOfWeek + } + }; + + return TimeClockSpan.find(query); + }, + forWeekByUser: function(week, user) { + const startOfWeek = week.clone(); + const endOfWeek = week.clone().endOf('week'); + + const query = { + start: { + $gte: startOfWeek, + $lte: endOfWeek + }, + user: user + }; + + return TimeClockSpan.find(query); + } +}; + +db.workorders = { + findByIds: function(ids) { + const query = { + _id: { + $in: ids + } + }; + + return Workorder.find(query); + } +}; + +module.exports = db; + + +function findWorkordersById(ids) { + const query = { + _id: { + $in: ids + } + }; + + return Workorder + .find(query) + .populate('client', 'name identifier') + .exec(); +} \ No newline at end of file diff --git a/app/controllers/pms.js b/app/controllers/pms.js index 6585bf7..e1e9027 100644 --- a/app/controllers/pms.js +++ b/app/controllers/pms.js @@ -155,9 +155,9 @@ function getPmsByDate(year, month) { ]; } - return Workorder.aggregateAsync(pipeline) + return Workorder.aggregate(pipeline) + .exec() .then(function(pmsData) { - var data = {}; if (month !== undefined) { @@ -183,12 +183,13 @@ function getPmsByDate(year, month) { } function getClients() { - return Client.find({ deleted: false }) + return Client + .find({ deleted: false }) .lean() .select('name identifier frequencies') .slice('contacts', 1) .sort('name') - .execAsync(); + .exec(); } function filterClientsByFrequency(month, frequency) { diff --git a/app/controllers/timeclock.js b/app/controllers/timeclock.js index 1f0ac1b..9e4bd5b 100644 --- a/app/controllers/timeclock.js +++ b/app/controllers/timeclock.js @@ -5,516 +5,597 @@ var moment = require('moment-timezone'); var _ = require('lodash'); var Promise = require('bluebird'); var TimeClockSpan = mongoose.model('TimeClockSpan'); +var TimeClockException = mongoose.model('TimeClockException'); var Workorder = mongoose.model('Workorder'); +var email = require('../util/email'); +var config = require('../../config/config')['prod']; var NON_BILLABLES = ['shop', 'break', 'pto', 'meeting', 'event', 'weather', 'holiday']; var TASK_TYPES = ['workday', 'workorder', 'nonBillable']; -function MultipleSpansError(spans) { - Error.captureStackTrace(this, MultipleSpansError); +var exceptionTemplate = email.template( + 'exception.html.tmpl', + 'exception.text.tmpl', + 'Exception', + [ + 'techName', + 'date', + 'message' + ] +); - this.name = 'MultipleSpansError'; - this.message = 'Encountered multiple spans when one was expected'; - this.spans = spans; +function MultipleSpansError(spans) { + Error.captureStackTrace(this, MultipleSpansError); + + this.name = 'MultipleSpansError'; + this.message = 'Encountered multiple spans when one was expected'; + this.spans = spans; } MultipleSpansError.prototype = Object.create(Error.prototype); function findUserSpans(user, day) { - var startOfDay = day.clone().startOf('day').utc().toDate(); - var endOfDay = day.clone().endOf('day').utc().toDate(); + var startOfDay = day.clone().startOf('day').toDate(); + var endOfDay = day.clone().endOf('day').toDate(); - var query = { - start: { - '$gte': startOfDay, - '$lte': endOfDay - }, - user: user.id - }; + var query = { + start: { + '$gte': startOfDay, + '$lte': endOfDay + }, + user: user + }; - return TimeClockSpan - .find(query) - .exec(); + return TimeClockSpan + .find(query) + .exec(); } function findUserWorkorders(user, day) { - var startOfDay = day.clone().startOf('day').toDate(); - var endOfDay = day.clone().endOf('day').toDate(); + var startOfDay = day.clone().startOf('day').toDate(); + var endOfDay = day.clone().endOf('day').toDate(); - var query = { - deleted: false, - techs: user.id, - 'scheduling.start': { - '$lte': endOfDay - }, - 'scheduling.end': { - '$gte': startOfDay - } - }; + var query = { + deleted: false, + techs: user.id, + 'scheduling.start': { + '$lte': endOfDay + }, + 'scheduling.end': { + '$gte': startOfDay + } + }; - return Workorder - .find(query) - .populate('client', 'name identifier') - .exec(); + return Workorder + .find(query) + .populate('client', 'name identifier') + .exec(); } function findUserWorkorder(id, user) { - var query = { - _id: id, - techs: user.id, - deleted: false - }; + var query = { + _id: id, + techs: user.id, + deleted: false + }; - return Workorder - .findOne(query) - .populate('client', 'name identifier contacts address') - .exec(); + return Workorder + .findOne(query) + .populate('client', 'name identifier contacts address') + .exec(); } function filterSpans(spans, filter) { - filter = { - type: filter.type ? [].concat(filter.type) : undefined, - status: filter.status ? String(filter.status) : undefined, - workorder: filter.workorder ? String(filter.workorder) : undefined, - reason: filter.reason ? String(filter.reason) : undefined - }; + filter = { + type: filter.type ? [].concat(filter.type) : undefined, + status: filter.status ? String(filter.status) : undefined, + workorder: filter.workorder ? String(filter.workorder) : undefined, + reason: filter.reason ? String(filter.reason) : undefined + }; - return _.chain(spans) - .filter(function(span) { + return _.chain(spans) + .filter(function (span) { - if (filter.type && filter.type.indexOf(span.type) === -1) { - return false; - } + if (filter.type && filter.type.indexOf(span.type) === -1) { + return false; + } - if (filter.status && String(span.status) !== filter.status) { - return false; - } + if (filter.status && String(span.status) !== filter.status) { + return false; + } - if (filter.workorder && String(span.workorder) !== filter.workorder) { - return false; - } + if (filter.workorder && String(span.workorder) !== filter.workorder) { + return false; + } - if (filter.reason && span.reason !== filter.reason) { - return false; - } + if (filter.reason && span.reason !== filter.reason) { + return false; + } - return true; - }) - .sortBy('start') - .value(); + return true; + }) + .sortBy('start') + .value(); } function spansStatus(spans, filter) { - if (filter) { - spans = filterSpans(spans, filter); + if (filter) { + spans = filterSpans(spans, filter); + } + + var result = 'pending'; + _.forEach(spans, function (span) { + if (span.status === 'open') { + result = 'clockedIn'; + return false; + } else { + result = 'clockedOut'; } + }); - var result = 'pending'; - _.forEach(spans, function(span) { - if (span.status === 'open') { - result = 'clockedIn'; - return false; - } else { - result = 'clockedOut'; - } - }); - - return result; + return result; } function validateClockRequest(req) { - return new Promise(function (resolve, reject) { + return new Promise(function (resolve, reject) { - var params = {}; + var params = {}; - var type = req.body.type; - if (!type) { - return reject("Missing required parameter 'type'"); - } + var type = req.body.type; + if (!type) { + return reject("Missing required parameter 'type'"); + } - if (TASK_TYPES.indexOf(type) === -1) { - return reject("Invalid type: '" + type + "'"); - } + if (TASK_TYPES.indexOf(type) === -1) { + return reject("Invalid type: '" + type + "'"); + } - params.type = type; + params.type = type; - if (type === 'workorder') { - var id = req.body.id; - if (!id) { - return reject("Missing required parameter 'id'"); - } + if (type === 'workorder') { + var id = req.body.id; + if (!id) { + return reject("Missing required parameter 'id'"); + } - params.id = id; - } + params.id = id; + } - if (type === 'nonBillable') { - var reason = req.body.reason; - if (!reason) { - return reject("Missing required parameter 'reason'"); - } + if (type === 'nonBillable') { + var reason = req.body.reason; + if (!reason) { + return reject("Missing required parameter 'reason'"); + } - if (NON_BILLABLES.indexOf(reason) === -1) { - return reject("Invalid reason: '" + reason + "'"); - } + if (NON_BILLABLES.indexOf(reason) === -1) { + return reject("Invalid reason: '" + reason + "'"); + } - params.reason = reason; - } + params.reason = reason; + } - resolve(params); - }); + resolve(params); + }); } function validateWorkorderDetailsRequest(req) { - var params = {}; + var params = {}; - var id = req.param('id'); - if (!id) { - return Promise.reject("Missing required parameter 'id'"); - } + var id = req.param('id'); + if (!id) { + return Promise.reject("Missing required parameter 'id'"); + } - params.id = id; + params.id = id; - return Promise.resolve(params); + return Promise.resolve(params); } function handleStatusRequest(spans, workorders) { - var results = {}; + var results = {}; - var workdaySpans = _.filter(spans, { type: 'workday' }); + var workdaySpans = _.filter(spans, {type: 'workday'}); - results.tasks = []; + results.tasks = []; - results.tasks = results.tasks.concat({ - type: 'workday', - status: spansStatus(workdaySpans), - spans: _.map(workdaySpans, spanToResponse) - }); + results.tasks = results.tasks.concat({ + type: 'workday', + status: spansStatus(workdaySpans), + spans: _.map(workdaySpans, spanToResponse) + }); - results.tasks = results.tasks.concat(_.chain(workorders) - .sortBy('scheduling.start') - .map(function(workorder) { - var workorderSpans = filterSpans(spans, { type: 'workorder', workorder: workorder.id }); + results.tasks = results.tasks.concat(_.chain(workorders) + .sortBy('scheduling.start') + .map(function (workorder) { + var workorderSpans = filterSpans(spans, {type: 'workorder', workorder: workorder.id}); - return { - type: 'workorder', - id: workorder.id, - title: workorder.client.name, - start: moment(workorder.scheduling.start).utc().toISOString(), - end: moment(workorder.scheduling.end).utc().toISOString(), - status: spansStatus(workorderSpans), - spans: _.map(workorderSpans, spanToResponse) - }; - }) - .value() - ); + return { + type: 'workorder', + id: workorder.id, + title: workorder.client.name, + start: moment(workorder.scheduling.start).utc().toISOString(), + end: moment(workorder.scheduling.end).utc().toISOString(), + status: spansStatus(workorderSpans), + spans: _.map(workorderSpans, spanToResponse) + }; + }) + .value() + ); - results.tasks = results.tasks.concat(_.chain(NON_BILLABLES) - .map(function(nonBillable) { - var nonBillableSpans = filterSpans(spans, { reason: nonBillable }); + results.tasks = results.tasks.concat(_.chain(NON_BILLABLES) + .map(function (nonBillable) { + var nonBillableSpans = filterSpans(spans, {reason: nonBillable}); - return { - type: 'nonBillable', - reason: nonBillable, - status: spansStatus(nonBillableSpans), - spans: _.map(nonBillableSpans, spanToResponse) - }; - }) - .value() - ); + return { + type: 'nonBillable', + reason: nonBillable, + status: spansStatus(nonBillableSpans), + spans: _.map(nonBillableSpans, spanToResponse) + }; + }) + .value() + ); - return results; + return results; } function handleClockInRequest(params, user, spans, workorders, now) { - var workdayStatus = spansStatus(spans, { type: 'workday' }); + var workdayStatus = spansStatus(spans, {type: 'workday'}); - if (params.type === 'workday') { - if (workdayStatus === 'clockedIn') { - return Promise.reject('Already clocked in'); - } - - var span = new TimeClockSpan({ - user: user.id, - type: 'workday', - status: 'open', - start: now.clone().utc().toDate() - }); - - } else { - if (workdayStatus !== 'clockedIn') { - return Promise.reject('Not clocked into day'); - } - - var allTasksStatus = spansStatus(spans, {type: ['workorder', 'nonBillable']}); - if (allTasksStatus === 'clockedIn') { - return Promise.reject('Already clocked in'); - } - - if (params.type === 'workorder') { - var workorder = _.find(workorders, {id: params.id}); - if (!workorder) { - return Promise.reject('Invalid workorder'); - } - - handleClockInExceptions(user, workorder, spans, now); - - var span = new TimeClockSpan({ - user: user.id, - type: 'workorder', - status: 'open', - start: now.clone().utc().toDate(), - workorder: workorder.id, - client: workorder.client.id - }); - } - - if (params.type === 'nonBillable') { - var span = new TimeClockSpan({ - user: user.id, - type: 'nonBillable', - status: 'open', - start: now.clone().utc().toDate(), - reason: params.reason - }); - } + if (params.type === 'workday') { + if (workdayStatus === 'clockedIn') { + return Promise.reject('Already clocked in'); } - return span.save().then(spanToResponse); + var span = new TimeClockSpan({ + user: user.id, + type: 'workday', + status: 'open', + start: now.clone().utc().toDate() + }); + + } else { + if (workdayStatus !== 'clockedIn') { + return Promise.reject('Not clocked into day'); + } + + var allTasksStatus = spansStatus(spans, {type: ['workorder', 'nonBillable']}); + if (allTasksStatus === 'clockedIn') { + return Promise.reject('Already clocked in'); + } + + if (params.type === 'workorder') { + var workorder = _.find(workorders, {id: params.id}); + if (!workorder) { + return Promise.reject('Invalid workorder'); + } + + handleClockInExceptions(user, workorder, spans, now); + + var span = new TimeClockSpan({ + user: user.id, + type: 'workorder', + status: 'open', + start: now.clone().utc().toDate(), + workorder: workorder.id, + client: workorder.client.id + }); + } + + if (params.type === 'nonBillable') { + var span = new TimeClockSpan({ + user: user.id, + type: 'nonBillable', + status: 'open', + start: now.clone().utc().toDate(), + reason: params.reason + }); + } + } + + return span.save().then(spanToResponse); } function handleClockInExceptions(user, workorder, spans, now) { - var closedWorkordersSpans = filterSpans(spans, { type: 'workorder', status: 'closed' }); - var isFirstWorkorder = closedWorkordersSpans.length == 0; + var closedWorkordersSpans = filterSpans(spans, {type: 'workorder', status: 'closed'}); + var isFirstWorkorder = closedWorkordersSpans.length == 0; - if (isFirstWorkorder) { - var start = moment(workorder.scheduling.start); - var minutes = now.diff(start, 'minutes'); + if (isFirstWorkorder) { + var start = moment(workorder.scheduling.start); + var minutes = now.diff(start, 'minutes'); - if (minutes > 15) { - reportException({ - user: user, - workorder: workorder, - reason: 'User is late to first workorder.' - }); - } - } else { - var previousWorkorderSpan = _.last(closedWorkordersSpans); + if (minutes > 15) { - if (previousWorkorderSpan.workorder != workorder.id) { - console.log(previousWorkorderSpan); + new TimeClockException({ + user: user._id, + date: new Date(), + reason: 'late_to_first_workorder' + }).save(); - var end = moment(previousWorkorderSpan.end); - var minutes = now.diff(end, 'minutes'); - console.log("Time between tasks: ", minutes); - - if (minutes < 5) { - reportException({ - user: user, - workorder: workorder, - reason: 'User clocked in to next workorder too quickly.' - }); - } - - if (minutes > 75) { - reportException({ - user: user, - workorder: workorder, - reason: 'Too much travel time detected between jobs.' - }); - } - } + reportException({ + user: user, + workorder: workorder, + reason: 'User is late to first workorder.' + }); } + } else { + var previousWorkorderSpan = _.last(closedWorkordersSpans); + + if (previousWorkorderSpan.workorder != workorder.id) { + console.log(previousWorkorderSpan); + + var end = moment(previousWorkorderSpan.end); + var minutes = now.diff(end, 'minutes'); + console.log("Time between tasks: ", minutes); + + if (minutes < 5) { + new TimeClockException({ + user: user._id, + date: new Date(), + reason: 'too_little_travel' + }).save(); + + reportException({ + user: user, + workorder: workorder, + reason: 'User clocked in to next workorder too quickly.' + }); + } + + if (minutes > 75) { + new TimeClockException({ + user: user._id, + date: new Date(), + reason: 'too_much_travel' + }).save(); + + reportException({ + user: user, + workorder: workorder, + reason: 'Too much travel time detected between jobs.' + }); + } + } + } } function reportException(exception) { - // TODO: Actually send emails for exceptions. - console.log('--- EXCEPTION ---', exception.reason); + const message = { + to: config.email.exception + }; + + const values = { + techName: `${exception.user.name.first} ${exception.user.name.last}`, + date: moment().format('LLLL'), + message: exception.reason + }; + + email.send(message, exceptionTemplate, values); + + console.log('--- EXCEPTION ---', new Date(), exception.reason); } function handleClockOutRequest(params, user, spans, workorders, now) { - var workdaySpans = filterSpans(spans, { type: 'workday' }); - var workdayStatus = spansStatus(workdaySpans); + var workdaySpans = filterSpans(spans, {type: 'workday'}); + var workdayStatus = spansStatus(workdaySpans); - if (workdayStatus !== 'clockedIn') { - return Promise.reject('Not clocked in'); + if (workdayStatus !== 'clockedIn') { + return Promise.reject('Not clocked in'); + } + + if (params.type === 'workday') { + var allTasksStatus = spansStatus(spans, {type: ['workorder', 'nonBillable']}); + if (allTasksStatus === 'clockedIn') { + return Promise.reject('Cannot clock out while tasks are still open.'); } - if (params.type === 'workday') { - var allTasksStatus = spansStatus(spans, {type: ['workorder', 'nonBillable']}); - if (allTasksStatus === 'clockedIn') { - return Promise.reject('Cannot clock out while tasks are still open.'); - } + var span = ensureSingularSpan(filterSpans(workdaySpans, {status: 'open'})); + } - var span = ensureSingularSpan(filterSpans(workdaySpans, {status: 'open'})); + if (params.type === 'workorder') { + var workorder = _.find(workorders, {id: params.id}); + if (!workorder) { + return Promise.reject('Invalid workorder'); } - if (params.type === 'workorder') { - var workorder = _.find(workorders, {id: params.id}); - if (!workorder) { - return Promise.reject('Invalid workorder'); - } + var workorderSpans = filterSpans(spans, {type: 'workorder', workorder: workorder.id}); + var workorderStatus = spansStatus(workorderSpans); - var workorderSpans = filterSpans(spans, { type: 'workorder', workorder: workorder.id }); - var workorderStatus = spansStatus(workorderSpans); - - if (workorderStatus !== 'clockedIn') { - return Promise.reject('Not clocked in'); - } - - var span = ensureSingularSpan(filterSpans(workorderSpans, {status: 'open'})); + if (workorderStatus !== 'clockedIn') { + return Promise.reject('Not clocked in'); } - if (params.type === 'nonBillable') { - var nonBillableSpans = filterSpans(spans, { type: 'nonBillable', reason: params.reason }); - var nonBillableStatus = spansStatus(nonBillableSpans); + var span = ensureSingularSpan(filterSpans(workorderSpans, {status: 'open'})); + } - if (nonBillableStatus !== 'clockedIn') { - return Promise.reject('Not clocked in'); - } + if (params.type === 'nonBillable') { + var nonBillableSpans = filterSpans(spans, {type: 'nonBillable', reason: params.reason}); + var nonBillableStatus = spansStatus(nonBillableSpans); - var span = ensureSingularSpan(filterSpans(nonBillableSpans, {status: 'open'})); + if (nonBillableStatus !== 'clockedIn') { + return Promise.reject('Not clocked in'); } - span.status = 'closed'; - span.end = now.clone().utc().toDate(); - span.duration = moment(span.end).diff(span.start, 'seconds'); + var span = ensureSingularSpan(filterSpans(nonBillableSpans, {status: 'open'})); + } - return span.save().then(spanToResponse); + span.status = 'closed'; + span.end = now.clone().utc().toDate(); + span.duration = moment(span.end).diff(span.start, 'seconds'); + + return span.save().then(spanToResponse); } function handleWorkorderDetailsRequest(params, user, spans, workorder, today) { - if (!workorder) { - return Promise.reject('Invalid workorder'); + if (!workorder) { + return Promise.reject('Invalid workorder'); + } + + var workorderSpans = filterSpans(spans, {type: 'workorder', workorder: workorder.id}); + var workorderStatus = spansStatus(workorderSpans); + + workorder = workorder.toObject(); + workorder.timeclock = { + type: 'workorder', + id: workorder._id, + title: workorder.client.name, + start: moment(workorder.scheduling.start).utc().toISOString(), + end: moment(workorder.scheduling.end).utc().toISOString(), + status: workorderStatus, + spans: _.map(workorderSpans, spanToResponse), + blocked: false + }; + + if (workorderStatus != 'clockedIn') { + var workdayStatus = spansStatus(spans, {type: 'workday'}); + var otherSpansStatus = spansStatus(spans, {type: ['workorder', 'nonBillable']}); + + if (workdayStatus != 'clockedIn' || otherSpansStatus == 'clockedIn') { + workorder.timeclock.blocked = true; } + } - var workorderSpans = filterSpans(spans, { type: 'workorder', workorder: workorder.id }); - var workorderStatus = spansStatus(workorderSpans); - - workorder = workorder.toObject(); - workorder.timeclock = { - type: 'workorder', - id: workorder._id, - title: workorder.client.name, - start: moment(workorder.scheduling.start).utc().toISOString(), - end: moment(workorder.scheduling.end).utc().toISOString(), - status: workorderStatus, - spans: _.map(workorderSpans, spanToResponse), - blocked: false - }; - - if (workorderStatus != 'clockedIn') { - var workdayStatus = spansStatus(spans, { type: 'workday' }); - var otherSpansStatus = spansStatus(spans, {type: ['workorder', 'nonBillable']}); - - if (workdayStatus != 'clockedIn' || otherSpansStatus == 'clockedIn') { - workorder.timeclock.blocked = true; - } - } - - return workorder; + return workorder; } function spanToResponse(span) { - return { - start: span.start, - end: span.end, - duration: span.duration - }; + return { + start: span.start, + end: span.end, + duration: span.duration + }; } function ensureSingularSpan(spans) { - if (spans.length != 1) { - throw new MultipleSpansError(spans); - } + if (spans.length != 1) { + throw new MultipleSpansError(spans); + } - return spans[0]; + return spans[0]; } function responseHandler(res) { - return function(data) { - res.json(data); - }; + return function (data) { + res.json(data); + }; } function errorHandler(res) { - return function(error) { - if (typeof error === 'string') { - res.json(400, { - error: { - message: error - } - }); - } else { - console.error(error.stack); - res.json(500, 'Internal error'); + return function (error) { + if (typeof error === 'string') { + res.json(400, { + error: { + message: error } - }; + }); + } else { + console.error(error.stack); + res.json(500, 'Internal error'); + } + }; } -module.exports = function() { - return { - index: function(req, res) { +function validateUserId(req) { + const id = req.param('user_id'); + if (!id) { + return Promise.reject("Parameter missing 'user_id'"); + } - //TODO: Check to make sure user has a valid timesheet. + return Promise.resolve(id); +} - var today = moment(); +function validateDate(req, field) { + let date = req.param(field); - var spans = findUserSpans(req.user, today); - var workorders = findUserWorkorders(req.user, today); + if (!date) { + return Promise.reject(`Parameter '${field}' is required.`); + } - Promise.join(spans, workorders, handleStatusRequest) - .then(responseHandler(res)) - .catch(errorHandler(res)); - }, + date = moment(date, 'YYYY-MM-DD'); + if (!date.isValid()) { + return Promise.reject(`Parameter '${field}' is not a valid date.`) + } - clockIn: function(req, res) { + return Promise.resolve(date); +} - //TODO: Check to make sure user has a valid timesheet. +module.exports = function () { + return { + index: function (req, res) { - var today = moment(); + //TODO: Check to make sure user has a valid timesheet. - var params = validateClockRequest(req); - var spans = findUserSpans(req.user, today); - var workorders = findUserWorkorders(req.user, today); + var today = moment(); - Promise.join(params, req.user, spans, workorders, today, handleClockInRequest) - .then(responseHandler(res)) - .catch(errorHandler(res)); - }, + var spans = findUserSpans(req.user.id, today); + var workorders = findUserWorkorders(req.user, today); - clockOut: function(req, res) { + Promise.join(spans, workorders, handleStatusRequest) + .then(responseHandler(res)) + .catch(errorHandler(res)); + }, - //TODO: Check to make sure user has a valid timesheet. + clockIn: function (req, res) { - var today = moment(); + //TODO: Check to make sure user has a valid timesheet. - var params = validateClockRequest(req); - var spans = findUserSpans(req.user, today); - var workorders = findUserWorkorders(req.user, today); + var today = moment(); - Promise.join(params, req.user, spans, workorders, today, handleClockOutRequest) - .then(responseHandler(res)) - .catch(errorHandler(res)); - }, + var params = validateClockRequest(req); + var spans = findUserSpans(req.user.id, today); + var workorders = findUserWorkorders(req.user, today); - workorderDetails: function(req, res) { + Promise.join(params, req.user, spans, workorders, today, handleClockInRequest) + .then(responseHandler(res)) + .catch(errorHandler(res)); + }, - var today = moment(); + clockOut: function (req, res) { - validateWorkorderDetailsRequest(req) - .then(function(params) { - var spans = findUserSpans(req.user, today); - var workorder = findUserWorkorder(params.id, req.user); + //TODO: Check to make sure user has a valid timesheet. - return Promise.join(params, req.user, spans, workorder, today, handleWorkorderDetailsRequest) - }) - .then(responseHandler(res)) - .catch(errorHandler(res)); + Promise + .props({ + id: req.user.id, + date: moment(), + notes: req.body.notes + }) + .then((params) => { + var spans = findUserSpans(req.user.id, params.date); + var workorders = findUserWorkorders(req.user, params.date); + return Promise.join(params, req.user, spans, workorders, params.date, handleClockOutRequest); + }) + .then(responseHandler(res)) + .catch(errorHandler(res)); + }, + spansForUser: function (req, res) { + Promise + .props({ + id: validateUserId(req), + date: validateDate(req, 'date') + }) + .then((params) => findUserSpans(params.id, params.date)) + .then(responseHandler(res)) + .catch(errorHandler(res)); + }, - Promise.join - } - } + workorderDetails: function (req, res) { + + var today = moment(); + + validateWorkorderDetailsRequest(req) + .then(function (params) { + var spans = findUserSpans(req.user, today); + var workorder = findUserWorkorder(params.id, req.user); + + return Promise.join(params, req.user, spans, workorder, today, handleWorkorderDetailsRequest) + }) + .then(responseHandler(res)) + .catch(errorHandler(res)); + }, + + } }; diff --git a/app/controllers/timesheet.js b/app/controllers/timesheet.js new file mode 100644 index 0000000..350994c --- /dev/null +++ b/app/controllers/timesheet.js @@ -0,0 +1,370 @@ +"use strict"; + +var mongoose = require('mongoose'); +var moment = require('moment-timezone'); +var _ = require('lodash'); +var Promise = require('bluebird'); +var TimeClockSpan = mongoose.model('TimeClockSpan'); +var Workorder = mongoose.model('Workorder'); +var User = mongoose.model('User'); +var db = require('./db'); + +const NON_BILLABLE_WORKORDER_TYPES = [ + 'shop', 'break', 'pto', 'meeting', 'event', 'weather' +]; + +const PAYROLL_WORKORDER_TYPE_MAP = { + 'office': 'office', + 'anesthesia': 'anesthesia', + 'biomed': 'biomed', + 'bsp': 'bsp', + 'ice': 'ice', + 'imaging': 'other', + 'sales': 'sales', + 'sterile-processing': 'sterilizer', + 'depot': 'depot', + 'trace-gas': 'other', + 'room-air-exchange': 'other', + 'isolation-panels': 'electric', + 'ups-systems': 'electric', + 'relocation': 'other', + 'ice-maker': 'other', + 'waste-management-system': 'other', + 'medgas': 'other', + 'staffing': 'other', + 'ert': 'electric', + 'shop': 'non-billable', + 'break': 'non-billable', + 'pto': 'non-billable', + 'meeting': 'non-billable', + 'event': 'non-billable', + 'weather': 'non-billable', + 'legacy': 'legacy' +}; + + +function findUserDaysWorked(id) { + var query = { + user: id, + type: 'workday', + status: 'closed' + }; + + return TimeClockSpan + .find(query).exec() + .then((records) => _.chain(records).reduce(accumulateDaysWorked, {}).values()) +} + +function accumulateDaysWorked(result, record) { + const date = moment(record.start).local().startOf('day').format('YYYY-MM-DD'); + + if (!result[date]) { + result[date] = { + date: date, + duration: 0 + }; + } + + if (record.duration) { + result[date].duration += record.duration; + } + + return result; +} + +function responseHandler(res) { + return function (data) { + res.json(data); + }; +} + +function errorHandler(res) { + return function (error) { + if (typeof error === 'string') { + res.json(400, { + error: { + message: error + } + }); + } else { + console.error(error.stack); + res.json(500, 'Internal error'); + } + }; +} + +function validateUserId(req) { + const id = req.param('user_id'); + if (!id) { + return Promise.reject("Parameter missing 'user_id'"); + } + + return Promise.resolve(id); +} + +function validateWeek(req) { + let week = req.param('week'); + + if (!week) { + return Promise.reject("Parameter 'week' is required."); + } + + week = moment(week, 'YYYY-MM-DD'); + if (!week.isValid()) { + return Promise.reject("Parameter 'week' is not a valid date.") + } + + if (week.weekday() !== 0) { + return Promise.reject("Parameter 'week' does not start at the beginning of the week (Sunday)."); + } + + // Return as string. + return Promise.resolve(week); +} + +function summaryHandler(params) { + const spans = findAllSpansForWeek(params.week); + + return buildReport(spans); +} + +function userSummaryHandler(params) { + const spans = findUserSpansForWeek(params.id, params.week); + + return buildReport(spans); +} + +function buildReport(spans) { + const workordersById = spans + .then(extractIds('workorder')) + .then(findWorkordersById) + .then(indexById); + + const usersById = spans + .then(extractIds('user')) + .then(findUsersById) + .then(indexById); + + return Promise.join(spans, workordersById, usersById, generateSummary); +} + +function generateSummary(spans, workordersById, usersById) { + var results = {}; + + function fetchOrCreateUserRecord(userId) { + var record = results[userId]; + if (!record) { + var user = usersById[userId]; + + record = results[userId] = { + user: { + _id: user._id, + name: user.name + }, + hasOpenSpans: false, + workorders: {}, + spans: {}, + clockedTime: 0, + workedTime: 0, + accountingByWorkorder: {}, + accountingByWorkorderType: {}, + accountingByPayroll: {}, + accountingByNonBillable: {}, + }; + } + return record; + } + + function addWorkorder(user, workorder) { + if (!user.workorders[workorder.id]) { + user.workorders[workorder.id] = { + _id: workorder._id, + client: workorder.client, + biomedId: workorder.biomedId, + reason: workorder.reason + } + } + } + + function logTime(collection, key, duration) { + if (!collection[key]) { + collection[key] = { + type: key, + duration: duration + } + } else { + collection[key].duration += duration; + } + } + + _.forEach(spans, (span) => { + var user = fetchOrCreateUserRecord(span.user); + + user.spans[span._id] = span.toObject(); + delete user.spans[span._id].__v; + delete user.spans[span._id].user; + + if (span.status !== 'closed') { + user.hasOpenSpans = true; + return; + } + + if (span.type === 'workday') { + user.clockedTime += span.duration; + } + + if (span.type === 'workorder') { + user.workedTime += span.duration; + + var workorder = workordersById[span.workorder]; + var workorderType = workorder.workorderType; + + // If workorder is actually a non-billable (Stupid), treat it as such... + if (NON_BILLABLE_WORKORDER_TYPES.indexOf(workorderType) > -1) { + logTime(user.accountingByNonBillable, workorderType, span.duration); + } else { + addWorkorder(user, workorder); + + logTime(user.accountingByWorkorderType, workorderType, span.duration); + logTime(user.accountingByPayroll, PAYROLL_WORKORDER_TYPE_MAP[workorderType], span.duration); + logTime(user.accountingByWorkorder, span.workorder, span.duration); + } + } + + if (span.type === 'nonBillable') { + user.workedTime += span.duration; + + logTime(user.accountingByNonBillable, span.reason, span.duration); + } + }); + + _.forEach(results, (user) => { + user.travelTime = Math.max(0, user.clockedTime - user.workedTime); + + user.spans = _.values(user.spans); + + user.accountingByWorkorder = _.values(user.accountingByWorkorder); + user.accountingByWorkorderType = _.values(user.accountingByWorkorderType); + user.accountingByPayroll = _.values(user.accountingByPayroll); + user.accountingByNonBillable = _.values(user.accountingByNonBillable); + }); + + return _.values(results); +} + +function extractIds(field) { + return (data) => _(data) + .pluck(field) + .reject(_.isUndefined) + .uniq((id) => id.toString()) + .value(); +} + +function indexById(data) { + return _.indexBy(data, 'id') +} + +function findWorkordersById(ids) { + const query = { + _id: { + $in: ids + } + }; + + return Workorder + .find(query) + .populate('client', 'name identifier') + .exec(); +} + +function findUsersById(ids) { + const query = { + _id: { + $in: ids + } + }; + + return User.find(query).exec(); +} + +function findAllSpansForWeek(week) { + var startOfWeek = week.clone().startOf('week'); + var endOfWeek = week.clone().endOf('week'); + + console.log(`Finding spans between ${startOfWeek.format()} and ${endOfWeek.format()}`); + + var query = { + start: { + '$gte': startOfWeek.toDate(), + '$lte': endOfWeek.toDate() + } + }; + + return TimeClockSpan.find(query).exec(); +} + +function findUserSpansForWeek(id, week) { + var startOfWeek = week.clone().startOf('week'); + var endOfWeek = week.clone().endOf('week'); + + console.log(`Finding spans between ${startOfWeek.format()} and ${endOfWeek.format()}`); + + var query = { + start: { + '$gte': startOfWeek.toDate(), + '$lte': endOfWeek.toDate() + }, + user: id + }; + + return TimeClockSpan.find(query).exec(); +} + +module.exports = function () { + return { + daysWorked: function (req, res) { + req.check('user_id').notEmpty().isMongoId(); + + var errors = req.validationErrors(); + if (errors) { + return res.json(400, errors); + } + + var params = { + id: req.param('user_id') + }; + + findUserDaysWorked(params.id) + .then(responseHandler(res)) + .catch(errorHandler(res)); + }, + + summary: function (req, res) { + req.check('week').notEmpty().isWeek(); + + var errors = req.validationErrors(); + if (errors) { + return res.json(400, errors); + } + + var params = { + week: moment(req.sanitize('week')) + }; + + summaryHandler(params) + .then(responseHandler(res)) + .catch(errorHandler(res)); + }, + + userSummary: function (req, res) { + Promise + .props({ + id: validateUserId(req), + week: validateWeek(req) + }) + .then(userSummaryHandler) + .then(responseHandler(res)) + .catch(errorHandler(res)); + } + } +}; diff --git a/app/controllers/users.js b/app/controllers/users.js index 052e4dc..0def465 100644 --- a/app/controllers/users.js +++ b/app/controllers/users.js @@ -1,209 +1,226 @@ - var mongoose = require('mongoose'), - async = require('async'), - User = mongoose.model('User'), - Clock = mongoose.model('Clock'); + async = require('async'), + User = mongoose.model('User'), + Clock = mongoose.model('Clock'); var log = require('log4node'); -module.exports = function(config, directory) { +module.exports = function (config, directory) { - function fetch_all_users(callback) { - async.parallel({ - gapps: directory.listUsers, - local: function(callback) { - User.find({ deleted: false }).select('name email groups perms deleted').exec(callback); - } - }, callback); - } + function fetch_all_users(callback) { + async.parallel({ + gapps: directory.listUsers, + local: function (callback) { + User.find({deleted: false}).select('name email groups perms deleted').exec(callback); + } + }, callback); + } - function map_local_users(data, results) { - return function(callback) { - async.each(data, function(item, callback) { - var key = item.email.toLowerCase(); + function map_local_users(data, results) { + return function (callback) { + async.each(data, function (item, callback) { + var key = item.email.toLowerCase(); - if (blacklist.indexOf(key) == -1) - results[key] = item; + if (blacklist.indexOf(key) == -1) + results[key] = item; - callback(); - }, - callback); - }; - } + callback(); + }, + callback); + }; + } - function map_gapps_users(data, results) { - return function(callback) { - async.each(data, function(item, callback) { - var key = item.primaryEmail.toLowerCase(); + function map_gapps_users(data, results) { + return function (callback) { + async.each(data, function (item, callback) { + var key = item.primaryEmail.toLowerCase(); - // Ignore if blacklisted - if (blacklist.indexOf(key) != -1) return callback(); + // Ignore if blacklisted + if (blacklist.indexOf(key) != -1) return callback(); - if (!(key in results)) - results[key] = { - email: item.primaryEmail, - deleted: false, - perms: [ ], - groups: [ ], - name: { - first: item.name.givenName, - last: item.name.familyName - }, - }; + if (!(key in results)) + results[key] = { + email: item.primaryEmail, + deleted: false, + perms: [], + groups: [], + name: { + first: item.name.givenName, + last: item.name.familyName + }, + }; - callback(); - }, - callback); - }; - } + callback(); + }, + callback); + }; + } - function reduce_array(data, results) { - return function(callback) { - for (var item in data) { - results.push(data[item]); - } + function reduce_array(data, results) { + return function (callback) { + for (var item in data) { + results.push(data[item]); + } - results.sort(function(a, b) { - var result = a.name.first.toLowerCase().localeCompare(b.name.first.toLowerCase()); - if (result == 0) - result = a.name.last.toLowerCase().localeCompare(b.name.last.toLowerCase()); + results.sort(function (a, b) { + var result = a.name.first.toLowerCase().localeCompare(b.name.first.toLowerCase()); + if (result == 0) + result = a.name.last.toLowerCase().localeCompare(b.name.last.toLowerCase()); - return result; - }); + return result; + }); - callback(); - }; - } + callback(); + }; + } - function merge_sources(data, callback) { - var map = {}; - var reduce = []; + function merge_sources(data, callback) { + var map = {}; + var reduce = []; - async.series([ - map_local_users(data.local, map), - map_gapps_users(data.gapps.users, map), - reduce_array(map, reduce), - ], - function(err) { - callback(err, reduce); - }); - } + async.series([ + map_local_users(data.local, map), + map_gapps_users(data.gapps.users, map), + reduce_array(map, reduce), + ], + function (err) { + callback(err, reduce); + }); + } - return { - index: function(req, res) { - var criteria = { deleted: false }; + return { + index: function (req, res) { + var criteria = {deleted: false}; - if (req.query.group) { - criteria.groups = req.query.group; - } + if (req.query.group) { + criteria.groups = req.query.group; + } - if (req.query.perms) { - criteria.perms = req.query.perms; - } + if (req.query.perms) { + criteria.perms = req.query.perms; + } - if (req.query.userid) { - criteria._id = req.query.userid; - } + if (req.query.userid) { + criteria._id = req.query.userid; + } - var query = User.find(criteria) - .select('name groups') - .exec(function(err, results) { - if (err) { - res.json(500, err); - } else { - res.json(results); - } - }); - }, + var query = User.find(criteria) + .select('name groups') + .exec(function (err, results) { + if (err) { + res.json(500, err); + } else { + res.json(results); + } + }); + }, - details: function(req, res) { + details: function (req, res) { - async.waterfall([ - fetch_all_users, - merge_sources, - ], - function(err, results) { - if (err) return res.json(500, err); - res.json(results); - }); - }, + async.waterfall([ + fetch_all_users, + merge_sources, + ], + function (err, results) { + if (err) return res.json(500, err); + res.json(results); + }); + }, - create: function(req, res) { - log.info("users.create %j", req.body); + create: function (req, res) { + log.info("users.create %j", req.body); - var user = new User({ - email: req.body.email, - name: req.body.name, - groups: req.body.groups, - perms: req.body.perms, - deleted: false - }); + var user = new User({ + email: req.body.email, + name: req.body.name, + groups: req.body.groups, + perms: req.body.perms, + deleted: false + }); - return user.save(function(err) { - if (err) - log.error("Error: %s", err); + return user.save(function (err) { + if (err) + log.error("Error: %s", err); - return res.json(user); - }); - }, + return res.json(user); + }); + }, - update: function(req, res) { - var id = req.param('user_id'); - log.info("users.update %s %j", id, req.body); + get: function(req, res, next) { + var id = req.param('user_id'); + log.info("users.get %s", id); - return User.findById(id, function(err, user) { - user.email = req.body.email; - user.name = req.body.name; - user.groups = req.body.groups; - user.perms = req.body.perms; + User.findById(id) + .select('email picture perms groups name') + .exec() + .then((user) => { + if (!user) { + return next(new Error('Failed to load user ' + id)); + } + res.json(user); + }) + .catch((err) => { + next(err); + }); + }, - return user.save(function(err) { - if (err) - log.err("Error: %s", err); + update: function (req, res) { + var id = req.param('user_id'); + log.info("users.update %s %j", id, req.body); - return res.json(user); - }); - }); - }, + return User.findById(id, function (err, user) { + user.email = req.body.email; + user.name = req.body.name; + user.groups = req.body.groups; + user.perms = req.body.perms; - clocks: function(req, res) { - var id = req.param('user_id'); + return user.save(function (err) { + if (err) + log.err("Error: %s", err); - var criteria = { - tech: id - }; + return res.json(user); + }); + }); + }, - var query = Clock.find(criteria) - .sort('-dt') - .exec(function(err, results) { - if (err) { - res.json(500, err); - } else { - res.json(results); - } - }); - } - }; + clocks: function (req, res) { + var id = req.param('user_id'); + + var criteria = { + tech: id + }; + + var query = Clock.find(criteria) + .sort('-dt') + .exec(function (err, results) { + if (err) { + res.json(500, err); + } else { + res.json(results); + } + }); + } + }; }; var blacklist = [ - "system@atlanticbiomedical.com", - "admin@atlanticbiomedical.com", - "amazons3@atlanticbiomedical.com", - "api@atlanticbiomedical.com", - "biodexservice@atlanticbiomedical.com", - "cerberusapp@atlanticbiomedical.com", - "chattservice@atlanticbiomedical.com", - "dropbox@atlanticbiomedical.com", - "inquiries@atlanticbiomedical.com", - "office@atlanticbiomedical.com", - "parts@atlanticbiomedical.com", - "schedule@atlanticbiomedical.com", - "webapp@atlanticbiomedical.com", - "banfieldservice@atlanticbiomedical.com", - "chris.sewell@atlanticbiomedical.com", - "devel@atlanticbiomedical.com", - "dobie@atlanticbiomedical.com", + "system@atlanticbiomedical.com", + "admin@atlanticbiomedical.com", + "amazons3@atlanticbiomedical.com", + "api@atlanticbiomedical.com", + "biodexservice@atlanticbiomedical.com", + "cerberusapp@atlanticbiomedical.com", + "chattservice@atlanticbiomedical.com", + "dropbox@atlanticbiomedical.com", + "inquiries@atlanticbiomedical.com", + "office@atlanticbiomedical.com", + "parts@atlanticbiomedical.com", + "schedule@atlanticbiomedical.com", + "webapp@atlanticbiomedical.com", + "banfieldservice@atlanticbiomedical.com", + "chris.sewell@atlanticbiomedical.com", + "devel@atlanticbiomedical.com", + "dobie@atlanticbiomedical.com", // "akirayasha@gmail.com", - "receipts@atlanticbiomedical.com", + "receipts@atlanticbiomedical.com", ]; diff --git a/app/controllers/workorders.js b/app/controllers/workorders.js index c31373c..b18dc44 100644 --- a/app/controllers/workorders.js +++ b/app/controllers/workorders.js @@ -1,547 +1,570 @@ var log = require('log4node'); var mongoose = require('mongoose'), - email = require('emailjs'), - moment = require('moment'), - async = require('async'), - sprintf = require('sprintf').sprintf, - Client = mongoose.model('Client'), - Workorder = mongoose.model('Workorder'), - Counter = mongoose.model('Counter'), - Device = mongoose.model('Device'), - User = mongoose.model('User'); + email = require('emailjs'), + moment = require('moment'), + async = require('async'), + sprintf = require('sprintf').sprintf, + Client = mongoose.model('Client'), + Workorder = mongoose.model('Workorder'), + Counter = mongoose.model('Counter'), + Device = mongoose.model('Device'), + User = mongoose.model('User'); -module.exports = function(config, calendar) { - return { - index: function(req, res) { +module.exports = function (config, calendar) { + return { + index: function (req, res) { - log.info("workorders.index %j", req.query); - - var start = moment(req.query.start).toDate(); - var end = moment(req.query.end).add('days', 1).toDate(); + log.info("workorders.index %j", req.query); - Workorder - .find({ - deleted: false, - 'scheduling.start': { '$gte': start, '$lt': end } - }) - .populate('client', 'name identifier address') - .populate('techs', 'name') - .sort('-scheduling.start client.name') - .exec(function(err, results) { - if (err) { - res.json(500, err); - } else { - res.json(results); - } - }); - }, + var start = moment(req.query.start).toDate(); + var end = moment(req.query.end).add('days', 1).toDate(); - get: function(req, res, next) { - var id = req.param('workorder_id'); - log.info("workorders.get %s", id); + Workorder + .find({ + deleted: false, + 'scheduling.start': {'$gte': start, '$lt': end} + }) + .populate('client', 'name identifier address') + .populate('techs', 'name') + .sort('-scheduling.start client.name') + .exec(function (err, results) { + if (err) { + res.json(500, err); + } else { + res.json(results); + } + }); + }, - Workorder.findById(id) - .populate('client', 'name identifier') - .populate('techs', 'name') - .populate('createdBy', 'name') - .populate('modifiedBy', 'name') - .exec(function(err, workorder) { - if (err) return next(err); - if (!workorder) return next(new Error('Failed to load workorder ' + id)); + get: function (req, res, next) { + var id = req.param('workorder_id'); + log.info("workorders.get %s", id); - res.json(workorder); - }); - }, + Workorder.findById(id) + .populate('client', 'name identifier') + .populate('techs', 'name') + .populate('createdBy', 'name') + .populate('modifiedBy', 'name') + .exec(function (err, workorder) { + if (err) return next(err); + if (!workorder) return next(new Error('Failed to load workorder ' + id)); - create: function(req, res, next) { - log.info("workoreders.create %j", req.body); + res.json(workorder); + }); + }, - var server = email.server.connect({ - user: config.email.user, - password: config.email.password, - host: 'smtp.gmail.com', - ssl: true - }); + create: function (req, res, next) { + log.info("workoreders.create %j", req.body); - var date = new Date(); + var server = email.server.connect({ + user: config.email.user, + password: config.email.password, + host: 'smtp.gmail.com', + ssl: true + }); - var workorder = new Workorder({ - client: req.body.client, - emails: req.body.emails, - createdOn: date, - createdBy: req.user, - reason: req.body.reason, - maintenanceType: req.body.maintenanceType || "", - remarks: req.body.remarks || "", - status: req.body.status, - scheduling: req.body.scheduling, - techs: req.body.techs, - alternativeContact: req.body.alternativeContact, - trackingNumber: req.body.trackingNumber, - devices: req.body.devices - }); + var date = new Date(); - var notify = req.body._notify || ""; + var workorder = new Workorder({ + client: req.body.client, + emails: req.body.emails, + createdOn: date, + createdBy: req.user, + reason: req.body.reason, + maintenanceType: req.body.maintenanceType || "", + remarks: req.body.remarks || "", + status: req.body.status, + scheduling: req.body.scheduling, + techs: req.body.techs, + alternativeContact: req.body.alternativeContact, + trackingNumber: req.body.trackingNumber, + devices: req.body.devices, + workorderType: req.body.workorderType + }); - var client; - var techs; - var devices; - var jsonResult; + var notify = req.body._notify || ""; - async.waterfall([ - function(callback) { - Counter.collection.findAndModify( - { name: 'workorder' }, - [], - { $inc: { seq: 1 } }, - { 'new': true, upsert: true }, - function(err, result) { - workorder.biomedId = result.seq - 1; - callback(err); - }); - }, - function(callback) { - Client.findById(req.body.client, function(err, result) { - client = result; - callback(err); - }); - }, - function(callback) { - Device.find({'_id': { $in: req.body.devices }}) - .populate({path: 'deviceType'}) - .exec(function(err, results) { - devices = results; - callback(err); - }); - }, - function(callback) { - User.find({ - '_id': { $in: workorder.techs } - }, - function(err, result) { - techs = result; - callback(err); - }); - }, - function(callback) { - calendar.scheduleEvent({ - summary: generateSummary(client), - description: generateDescription(client, workorder, req.user, null, null, devices), - location: generateLocation(client), - start: workorder.scheduling.start, - end: workorder.scheduling.end, - attendees: generateAttendees(techs, workorder) - }, function(err, result) { - if (result) { - workorder.calendarId = result.id; - } - callback(err); - }); - }, - function(callback) { - if (!notify) - return callback(null); + var client; + var techs; + var devices; + var jsonResult; - var description = generateDescription(client, workorder, req.user, null, techs, devices); - var techDescription = appendNotes(description, client, workorder); + async.waterfall([ + function (callback) { + Counter.collection.findAndModify( + {name: 'workorder'}, + [], + {$inc: {seq: 1}}, + {'new': true, upsert: true}, + function (err, result) { + workorder.biomedId = result.value.seq - 1; + callback(err); + }); + }, + function (callback) { + Client.findById(req.body.client, function (err, result) { + client = result; + callback(err); + }); + }, + function (callback) { + Device.find({'_id': {$in: req.body.devices}}) + .populate({path: 'deviceType'}) + .exec(function (err, results) { + devices = results; + callback(err); + }); + }, + function (callback) { + User.find({ + '_id': {$in: workorder.techs} + }, + function (err, result) { + techs = result; + callback(err); + }); + }, + function (callback) { + calendar.scheduleEvent({ + summary: generateSummary(client), + description: generateDescription(client, workorder, req.user, null, null, devices), + location: generateLocation(client), + start: workorder.scheduling.start, + end: workorder.scheduling.end, + attendees: generateAttendees(techs, workorder) + }, function (err, result) { + if (result) { + workorder.calendarId = result.id; + } + callback(err); + }); + }, + function (callback) { + if (!notify) + return callback(null); - var to = req.body.emails; - var techTo = generateToLine(techs); + var description = generateDescription(client, workorder, req.user, null, techs, devices); + var techDescription = appendNotes(description, client, workorder); - var subject = 'Workorder created: ' + workorder.biomedId; + var to = req.body.emails; + var techTo = generateToLine(techs); - async.waterfall([ - function(cb) { - if (to && to.length > 0) { - var msg = { - text: description, - from: config.email.user, - to: to, - subject: subject - }; - server.send(msg, function(err, message) { cb(err); }); - } else { - cb(); - } - }, - function(cb) { - if (techTo) { - var msg = { - text: techDescription, - from: config.email.user, - to: techTo, - subject: subject - }; - server.send(msg, function(err, message) { cb(err); }); - } else { - cb(); - } - } - ], callback); - }, - function(callback) { - workorder.save(function(err, result) { callback(err, result); }); - }, - function(result, callback) { - jsonResult = result; + var subject = 'Workorder created: ' + workorder.biomedId; - Client.findByIdAndUpdate(req.body.client, { $push: { 'workorders': result.id } }, - function(err, ignored) { callback(err, result) }); - }, - function(result, callback) { - if (workorder.maintenanceType) { - var key = 'pms.' + date.getFullYear() + '-' + date.getMonth() + '.' + workorder.maintenanceType; - var cmd = { $inc: {} }; - cmd.$inc[key] = 1; - Client.findByIdAndUpdate(req.body.client, cmd, function(err, ignored) { callback(err, result) }); - } else { - callback(null, result); - } - }, - ], - function(err, result) { - if (!err) { - res.json(jsonResult); - } else { - throw err; - } - }); - }, + async.waterfall([ + function (cb) { + if (to && to.length > 0) { + var msg = { + text: description, + from: config.email.user, + to: to, + subject: subject + }; + server.send(msg, function (err, message) { + cb(err); + }); + } else { + cb(); + } + }, + function (cb) { + if (techTo) { + var msg = { + text: techDescription, + from: config.email.user, + to: techTo, + subject: subject + }; + server.send(msg, function (err, message) { + cb(err); + }); + } else { + cb(); + } + } + ], callback); + }, + function (callback) { + workorder.save(function (err, result) { + callback(err, result); + }); + }, + function (result, callback) { + jsonResult = result; - update: function(req, res, next) { - var server = email.server.connect({ - user: config.email.user, - password: config.email.password, - host: 'smtp.gmail.com', - ssl: true - }); + Client.findByIdAndUpdate(req.body.client, {$push: {'workorders': result.id}}, + function (err, ignored) { + callback(err, result) + }); + }, + function (result, callback) { + if (workorder.maintenanceType) { + var key = 'pms.' + date.getFullYear() + '-' + date.getMonth() + '.' + workorder.maintenanceType; + var cmd = {$inc: {}}; + cmd.$inc[key] = 1; + Client.findByIdAndUpdate(req.body.client, cmd, function (err, ignored) { + callback(err, result) + }); + } else { + callback(null, result); + } + }, + ], + function (err, result) { + if (!err) { + res.json(jsonResult); + } else { + throw err; + } + }); + }, - var modifiedOn = new Date(); - var id = req.param('workorder_id'); + update: function (req, res, next) { + var server = email.server.connect({ + user: config.email.user, + password: config.email.password, + host: 'smtp.gmail.com', + ssl: true + }); - log.info("workorders.update %s %j", id, req.body); + var modifiedOn = new Date(); + var id = req.param('workorder_id'); - var workorder; - var client; - var techs; - var devices; - var createdBy; - var modifiedBy; + log.info("workorders.update %s %j", id, req.body); - var notify = req.body._notify || ""; + var workorder; + var client; + var techs; + var devices; + var createdBy; + var modifiedBy; - async.waterfall([ - function(callback) { - Workorder.findById(id, function(err, result) { - workorder = result; + var notify = req.body._notify || ""; - workorder.emails = req.body.emails; - workorder.modifiedBy = req.user; - workorder.modifiedOn = modifiedOn; - workorder.reason = req.body.reason; - workorder.maintenanceType = req.body.maintenanceType || ""; - workorder.remarks = req.body.remarks; - workorder.scheduling = req.body.scheduling; - workorder.status = req.body.status; - workorder.techs = req.body.techs - .filter(function(e) { return e; }) - .map(function(t) { return t._id; }); - workorder.invoiceNumber = req.body.invoiceNumber; - workorder.invoicedOn = req.body.invoicedOn; - workorder.checkNumber = req.body.checkNumber; - workorder.paidOn = req.body.paidOn; - workorder.alternativeContact = req.body.alternativeContact; - workorder.trackingNumber = req.body.trackingNumber; - workorder.devices = req.body.devices; - callback(err); - }); - }, - function(callback) { - Client.findById(workorder.client, function(err, result) { - client = result; - callback(err); - }); - }, - function(callback) { - Device.find({'_id': { $in: workorder.devices }}) - .populate({path: 'deviceType'}) - .exec(function(err, results) { - devices = results; - callback(err); - }); - }, - function(callback) { - if (workorder.createdBy) { - User.findById(workorder.createdBy, function(err, result) { - createdBy = result; - callback(err); - }); - } else { - callback(null); - } - }, - function(callback) { - if (workorder.modifiedBy) { - User.findById(workorder.modifiedBy, function(err, result) { - modifiedBy = result; - callback(err); - }); - } else { - callback(null); - } - }, - function(callback) { - User.find({ - '_id': { $in: workorder.techs } - }, - function(err, result) { - techs = result; - callback(err); - }); - }, - function(callback) { - calendar.updateEvent({ - summary: generateSummary(client), - description: generateDescription(client, workorder, null, null, null, devices), - location: generateLocation(client), - start: workorder.scheduling.start, - end: workorder.scheduling.end, - attendees: generateAttendees(techs, workorder), - eventId: workorder.calendarId - }, function(err, result) { - callback(err); - }); - }, - function(callback) { - if (!notify) - return callback(null); + async.waterfall([ + function (callback) { + Workorder.findById(id, function (err, result) { + workorder = result; + + workorder.emails = req.body.emails; + workorder.modifiedBy = req.user; + workorder.modifiedOn = modifiedOn; + workorder.reason = req.body.reason; + workorder.maintenanceType = req.body.maintenanceType || ""; + workorder.remarks = req.body.remarks; + workorder.scheduling = req.body.scheduling; + workorder.status = req.body.status; + workorder.techs = req.body.techs + .filter(function (e) { + return e; + }) + .map(function (t) { + return t._id; + }); + workorder.invoiceNumber = req.body.invoiceNumber; + workorder.invoicedTime = req.body.invoicedTime; + workorder.invoicedOn = req.body.invoicedOn; + workorder.checkNumber = req.body.checkNumber; + workorder.paidOn = req.body.paidOn; + workorder.alternativeContact = req.body.alternativeContact; + workorder.trackingNumber = req.body.trackingNumber; + workorder.devices = req.body.devices; + workorder.workorderType = req.body.workorderType; + callback(err); + }); + }, + function (callback) { + Client.findById(workorder.client, function (err, result) { + client = result; + callback(err); + }); + }, + function (callback) { + Device.find({'_id': {$in: workorder.devices}}) + .populate({path: 'deviceType'}) + .exec(function (err, results) { + devices = results; + callback(err); + }); + }, + function (callback) { + if (workorder.createdBy) { + User.findById(workorder.createdBy, function (err, result) { + createdBy = result; + callback(err); + }); + } else { + callback(null); + } + }, + function (callback) { + if (workorder.modifiedBy) { + User.findById(workorder.modifiedBy, function (err, result) { + modifiedBy = result; + callback(err); + }); + } else { + callback(null); + } + }, + function (callback) { + User.find({ + '_id': {$in: workorder.techs} + }, + function (err, result) { + techs = result; + callback(err); + }); + }, + function (callback) { + calendar.updateEvent({ + summary: generateSummary(client), + description: generateDescription(client, workorder, null, null, null, devices), + location: generateLocation(client), + start: workorder.scheduling.start, + end: workorder.scheduling.end, + attendees: generateAttendees(techs, workorder), + eventId: workorder.calendarId + }, function (err, result) { + callback(err); + }); + }, + function (callback) { + if (!notify) + return callback(null); - var description = generateDescription(client, workorder, createdBy, modifiedBy, techs, devices); - var techDescription = appendNotes(description, client, workorder); + var description = generateDescription(client, workorder, createdBy, modifiedBy, techs, devices); + var techDescription = appendNotes(description, client, workorder); - var to = req.body.emails; - var techTo = generateToLine(techs); + var to = req.body.emails; + var techTo = generateToLine(techs); - var subject = 'Workorder updated: ' + workorder.biomedId; + var subject = 'Workorder updated: ' + workorder.biomedId; - async.waterfall([ - function(cb) { - if (to && to.length > 0) { - var msg = { - text: description, - from: config.email.user, - to: to, - subject: subject - }; - server.send(msg, function(err, message) { cb(err); }); - } else { - cb(); - } - }, - function(cb) { - if (techTo) { - var msg = { - text: techDescription, - from: config.email.user, - to: techTo, - subject: subject - }; - server.send(msg, function(err, message) { cb(err); }); - } else { - cb(); - } - } - ], callback); - }, - function(callback) { - workorder.save(function(err) { - callback(err); - }) - } - ], - function(err) { - if (err) - log.error("Error: %s", err); + async.waterfall([ + function (cb) { + if (to && to.length > 0) { + var msg = { + text: description, + from: config.email.user, + to: to, + subject: subject + }; + server.send(msg, function (err, message) { + cb(err); + }); + } else { + cb(); + } + }, + function (cb) { + if (techTo) { + var msg = { + text: techDescription, + from: config.email.user, + to: techTo, + subject: subject + }; + server.send(msg, function (err, message) { + cb(err); + }); + } else { + cb(); + } + } + ], callback); + }, + function (callback) { + workorder.save(function (err) { + callback(err); + }) + } + ], + function (err) { + if (err) + log.error("Error: %s", err); - res.json(workorder); - }); - }, + res.json(workorder); + }); + }, - destroy: function(req, res, next) { - var id = req.param('workorder_id'); + destroy: function (req, res, next) { + var id = req.param('workorder_id'); - log.info("workorders.destroy %s", id); + log.info("workorders.destroy %s", id); - return Workorder.findById(id, function(err, workorder) { - workorder.deleted = true; + return Workorder.findById(id, function (err, workorder) { + workorder.deleted = true; - return workorder.save(function(err) { - if (!err) { - calendar.deleteEvent(workorder.calendarId, function(err) { - return res.json(workorder); - }); - } else { - log.warn("Error: %s", err); - return res.json(workorder); - } - }) - }); - } - }; + return workorder.save(function (err) { + if (!err) { + calendar.deleteEvent(workorder.calendarId, function (err) { + return res.json(workorder); + }); + } else { + log.warn("Error: %s", err); + return res.json(workorder); + } + }) + }); + } + }; }; function generateSummary(client) { - return client.name + ' (' + client.identifier + ')'; + return client.name + ' (' + client.identifier + ')'; } function generateLocation(client) { - var data = { - street1: client.address.street1 || '', - street2: client.address.street2 || '', - city: client.address.city || '', - state: client.address.state || '', - zip: client.address.zip || '' - }; + var data = { + street1: client.address.street1 || '', + street2: client.address.street2 || '', + city: client.address.city || '', + state: client.address.state || '', + zip: client.address.zip || '' + }; - return sprintf("%(street1)s %(street2)s %(city)s, %(state)s. %(zip)s", data); + return sprintf("%(street1)s %(street2)s %(city)s, %(state)s. %(zip)s", data); } function appendNotes(message, client, workorder) { - var template = - "%(message)s\n" + - "Tech Notes:\n" + - " %(notes)s\n" + - "\n" + - "Alternative Contact:\n" + - " %(alternativeContact)s\n" + - "\n"; + var template = + "%(message)s\n" + + "Tech Notes:\n" + + " %(notes)s\n" + + "\n" + + "Alternative Contact:\n" + + " %(alternativeContact)s\n" + + "\n"; - if (client.notes && client.notes['tech']) { - var resources = { - message: message || '', - notes: client.notes['tech'] || '', - alternativeContact: workorder.alternativeContact || '' - }; + if (client.notes && client.notes['tech']) { + var resources = { + message: message || '', + notes: client.notes['tech'] || '', + alternativeContact: workorder.alternativeContact || '' + }; - return sprintf(template, resources); - } else { - return message; - } + return sprintf(template, resources); + } else { + return message; + } } function generateDescription(client, workorder, createdBy, modifiedBy, techs, devices) { - var template = - "Workorder ID:\n" + - " %(biomedId)s\n" + - "\n" + - "Scheduled Time:\n" + - " %(scheduleStart)s - %(scheduleEnd)s\n" + - "\n" + - "Created By:\n" + - " %(createdBy)s\n" + - "\n" + - "Last Edited By:\n" + - " %(modifiedBy)s\n" + - "\n" + - "Customer:\n" + - " %(name)s (%(identifier)s)\n" + - "\n" + - "Contact:\n" + - " %(contact)s\n" + - " %(phone)s\n" + - "\n" + - "Address:\n" + - " %(street1)s\n" + - " %(street2)s\n" + - " %(city)s, %(state)s. %(zip)s\n" + - "\n" + - "Reason:\n" + - " %(reason)s\n" + - "\n" + - "Status:\n" + - " %(status)s\n" + - "\n" + - "Remarks:\n" + - " %(remarks)s\n" + - "\n" + - "Devices:\n" + - "%(devices)s\n"; + var template = + "Workorder ID:\n" + + " %(biomedId)s\n" + + "\n" + + "Scheduled Time:\n" + + " %(scheduleStart)s - %(scheduleEnd)s\n" + + "\n" + + "Created By:\n" + + " %(createdBy)s\n" + + "\n" + + "Last Edited By:\n" + + " %(modifiedBy)s\n" + + "\n" + + "Customer:\n" + + " %(name)s (%(identifier)s)\n" + + "\n" + + "Contact:\n" + + " %(contact)s\n" + + " %(phone)s\n" + + "\n" + + "Address:\n" + + " %(street1)s\n" + + " %(street2)s\n" + + " %(city)s, %(state)s. %(zip)s\n" + + "\n" + + "Reason:\n" + + " %(reason)s\n" + + "\n" + + "Status:\n" + + " %(status)s\n" + + "\n" + + "Remarks:\n" + + " %(remarks)s\n" + + "\n" + + "Devices:\n" + + "%(devices)s\n"; - var format = "MMMM Do YYYY, h:mm a" + var format = "MMMM Do YYYY, h:mm a" - var scheduleStart = moment(workorder.scheduling.start).format(format); - var scheduleEnd = moment(workorder.scheduling.end).format(format); + var scheduleStart = moment(workorder.scheduling.start).format(format); + var scheduleEnd = moment(workorder.scheduling.end).format(format); - var resources = { - biomedId: workorder.biomedId || '', - name: client.name || '', - identifier: client.identifier || '', - street1: client.address.street1 || '', - street2: client.address.street2 || '', - city: client.address.city || '', - state: client.address.state || '', - zip: client.address.zip || '', - reason: workorder.reason || '', - status: workorder.status || '', - remarks: workorder.remarks || '', - scheduleStart: scheduleStart, - scheduleEnd: scheduleEnd, - phone: '', - contact: '', - createdBy: '', - modifiedBy: '', - devices: '' - }; + var resources = { + biomedId: workorder.biomedId || '', + name: client.name || '', + identifier: client.identifier || '', + street1: client.address.street1 || '', + street2: client.address.street2 || '', + city: client.address.city || '', + state: client.address.state || '', + zip: client.address.zip || '', + reason: workorder.reason || '', + status: workorder.status || '', + remarks: workorder.remarks || '', + scheduleStart: scheduleStart, + scheduleEnd: scheduleEnd, + phone: '', + contact: '', + createdBy: '', + modifiedBy: '', + devices: '' + }; - if (client.contacts[0]) { - resources.phone = client.contacts[0].phone || ''; - resources.contact = client.contacts[0].name || ''; - } + if (client.contacts[0]) { + resources.phone = client.contacts[0].phone || ''; + resources.contact = client.contacts[0].name || ''; + } - if (createdBy) { - resources.createdBy = createdBy.name.first + " " + createdBy.name.last; - } + if (createdBy) { + resources.createdBy = createdBy.name.first + " " + createdBy.name.last; + } - if (modifiedBy) { - resources.modifiedBy = modifiedBy.name.first + " " + modifiedBy.name.last; - } + if (modifiedBy) { + resources.modifiedBy = modifiedBy.name.first + " " + modifiedBy.name.last; + } - if (devices) { - for (var i = 0; i < devices.length; i++) { - var device = devices[i]; + if (devices) { + for (var i = 0; i < devices.length; i++) { + var device = devices[i]; - resources.devices += "\t(" + device.biomedId + ") " + device.deviceType.make + " " + device.deviceType.model + "\n"; - } - } + resources.devices += "\t(" + device.biomedId + ") " + device.deviceType.make + " " + device.deviceType.model + "\n"; + } + } - var result = sprintf(template, resources); - console.log(result); + var result = sprintf(template, resources); + console.log(result); - return result; + return result; } function generateAttendees(techs, workorder) { - return techs.map(function(t) { return t.email; }).concat(workorder.emails); + return techs.map(function (t) { + return t.email; + }).concat(workorder.emails); } function generateToLine(techs) { - if (!techs) { - return null; - } + if (!techs) { + return null; + } - var result = ''; - for (var i in techs) { - var tech = techs[i] + var result = ''; + for (var i in techs) { + var tech = techs[i] - if (i > 0) { - result += ", "; - } + if (i > 0) { + result += ", "; + } - result += tech.name.first + " " + tech.name.last + " <" + tech.email + ">" - } - return result; + result += tech.name.first + " " + tech.name.last + " <" + tech.email + ">" + } + return result; } diff --git a/app/model/timeClockException.js b/app/model/timeClockException.js new file mode 100644 index 0000000..914ac9e --- /dev/null +++ b/app/model/timeClockException.js @@ -0,0 +1,30 @@ +"use strict"; + +var mongoose = require('mongoose'); +var Schema = mongoose.Schema; +var ObjectId = Schema.ObjectId; + +const EXCEPTION_REASONS = [ + 'late_to_first_workorder', + 'too_little_travel', + 'too_much_travel' +]; + +var schema = new Schema({ + user: { + type: ObjectId, + ref: 'User', + required: true + }, + date: { + type: Date, + required: true + }, + reason: { + type: String, + enum: EXCEPTION_REASONS, + required: true + } +}); + +module.exports = mongoose.model('TimeClockException', schema); diff --git a/app/model/timeClockSpan.js b/app/model/timeClockSpan.js index 1a392b0..4035a42 100644 --- a/app/model/timeClockSpan.js +++ b/app/model/timeClockSpan.js @@ -1,58 +1,106 @@ "use strict"; +var moment = require('moment'); var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var schema = new Schema({ + user: { + type: ObjectId, + ref: 'User', + required: true + }, - user: { - type: ObjectId, - ref: 'User' - }, - - client: { - type: ObjectId, - ref: 'Client' - }, - - workorder: { - type: ObjectId, - ref: 'Workorder' - }, - - status: { - type: String, - enum: ['open', 'closed'] - }, - - start: { - type: Date - }, - - end: { - type: Date - }, - - duration: { - type: Number, - min: 0 - }, - - type: { - type: String, - enum: [ 'workorder', 'workday', 'nonBillable' ] - }, - - reason: { - type: String, - enum: ['shop', 'break', 'pto', 'meeting', 'event', 'weather', 'holiday'] - }, - - notes: { - type: String, - trim: true + client: { + type: ObjectId, + ref: 'Client', + required: function() { + return this.type === 'workorder'; } + }, + + workorder: { + type: ObjectId, + ref: 'Workorder', + required: function() { + return this.type === 'workorder'; + } + }, + + status: { + type: String, + enum: ['open', 'closed'], + required: true + }, + + start: { + type: Date, + required: true + }, + + end: { + type: Date, + required: function() { + return this.status === 'closed'; + } + }, + + duration: { + type: Number, + min: 0 + }, + + type: { + type: String, + enum: ['workorder', 'workday', 'nonBillable'], + required: true + }, + + reason: { + type: String, + enum: ['shop', 'break', 'pto', 'meeting', 'event', 'weather', 'holiday'], + required: function() { + return this.type === 'nonBillable'; + } + }, + + notes: { + type: String, + trim: true, + required: function() { + return this.type === 'workorder' && this.status === 'closed'; + } + } +}); + +schema.pre('save', function (next) { + if (this.status === 'open') { + this.end = undefined; + } + + if (this.type === 'workorder') { + this.reason = undefined; + } + + if (this.type !== 'workorder') { + this.workorder = undefined; + this.client = undefined; + } + + if (this.start && this.end) { + this.duration = moment(this.end).diff(this.start, 'seconds'); + } + + next(); +}); + +schema.pre('validate', function (next) { + if (this.start > this.end) { + return next(new Error('End date must be greater than start date.')); + } + + next(); }); module.exports = mongoose.model('TimeClockSpan', schema); diff --git a/app/model/user.js b/app/model/user.js index de373c1..cc8fda6 100644 --- a/app/model/user.js +++ b/app/model/user.js @@ -11,10 +11,26 @@ var userSchema = new Schema({ picture: String, refreshToken: String, accessToken: String, - groups: [String], perms: [String], - deleted: { type: Boolean, default: false } + + employmentType: { + type: String, + enum: ['hourly', 'salary'], + default: 'hourly', + required: true + }, + + unpaidTravel: { + type: Number, + default: 0, + required: true + }, + + deleted: { + type: Boolean, + default: false + } }); userSchema.methods.hasPermission = function(perm) { diff --git a/app/model/workorder.js b/app/model/workorder.js index dbc0d3e..4d6788f 100644 --- a/app/model/workorder.js +++ b/app/model/workorder.js @@ -1,37 +1,70 @@ var mongoose = require('mongoose') - Schema = mongoose.Schema, - ObjectId = Schema.ObjectId; +Schema = mongoose.Schema, + ObjectId = Schema.ObjectId; var workorderSchema = new Schema({ - biomedId: Number, - client: { type: ObjectId, ref: 'Client' }, - emails: [String], - createdOn: Date, - createdBy: { type: ObjectId, ref: 'User' }, - modifiedBy: { type: ObjectId, ref: 'User' }, - reason: String, - maintenanceType: String, - remarks: String, - status: String, - scheduling: { - start: Date, - end: Date - }, - calendarId: String, - techs: [{ type: ObjectId, ref: 'User' }], - history: [{ - oldValues: {}, - newValues: {}, - modifiedBy: { type: ObjectId, ref: 'User' } - }], - deleted: { type: Boolean, default: false }, - invoiceNumber: String, - invoicedOn: Date, - checkNumber: String, - paidOn: Date, - alternativeContact: String, - trackingNumber: String, - devices: [{ type: ObjectId, ref: 'Device' }] + biomedId: Number, + client: {type: ObjectId, ref: 'Client'}, + emails: [String], + createdOn: Date, + createdBy: {type: ObjectId, ref: 'User'}, + modifiedBy: {type: ObjectId, ref: 'User'}, + reason: String, + maintenanceType: String, + remarks: String, + status: String, + scheduling: { + start: Date, + end: Date + }, + calendarId: String, + techs: [{type: ObjectId, ref: 'User'}], + history: [{ + oldValues: {}, + newValues: {}, + modifiedBy: {type: ObjectId, ref: 'User'} + }], + deleted: {type: Boolean, default: false}, + invoiceNumber: String, + invoicedTime: String, + invoicedOn: Date, + checkNumber: String, + paidOn: Date, + alternativeContact: String, + trackingNumber: String, + devices: [{type: ObjectId, ref: 'Device'}], + workorderType: { + type: String, + enum: [ + 'office', + 'anesthesia', + 'biomed', + 'bsp', + 'ice', + 'imaging', + 'sales', + 'sterile-processing', + 'depot', + 'trace-gas', + 'room-air-exchange', + 'isolation-panels', + 'ups-systems', + 'relocation', + 'ice-maker', + 'waste-management-system', + 'medgas', + 'staffing', + 'ert', + 'shop', + 'break', + 'pto', + 'meeting', + 'event', + 'weather', + 'legacy' + ], + default: 'legacy' + }, }); module.exports = mongoose.model('Workorder', workorderSchema); diff --git a/app/routes/exceptions.js b/app/routes/exceptions.js new file mode 100644 index 0000000..f8e13e0 --- /dev/null +++ b/app/routes/exceptions.js @@ -0,0 +1,60 @@ +"use strict"; + +const moment = require('moment-timezone'); +const _ = require('lodash'); + +/** + * GET /api/exceptions + */ +function index(req, res) { + req.check('user').isMongoId(); + req.check('date').optional().isISO8601(); + req.check('week').optional().isISO8601(); + + if (!req.query.date && !req.query.week) { + return res.json({ + error: { + message: 'Must specify a date filter.' + } + }); + } + + const query = { + user: req.query.user + }; + + if (req.query.date) { + const date = moment(req.query.date); + + const startOfDay = date.clone().startOf('day'); + const endOfDay = date.clone().endOf('day'); + + query.date = { + $gte: startOfDay, + $lte: endOfDay + }; + } + + if (req.query.week) { + const week = moment(req.query.week); + + const startOfWeek = week.clone().startOf('week'); + const endOfWeek = week.clone().endOf('week'); + + query.date = { + $gte: startOfWeek, + $lte: endOfWeek + }; + } + + var results = req.db.TimeClockException + .find(query) + .sort('date') + .exec(); + + res.promise(results); +} + +module.exports = { + index +}; diff --git a/app/routes/index.js b/app/routes/index.js new file mode 100644 index 0000000..7b7bb70 --- /dev/null +++ b/app/routes/index.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = { + exceptions: require('./exceptions'), + misc: require('./misc'), + spans: require('./spans'), + users: require('./users'), + workorders: require('./workorders') +}; diff --git a/app/routes/misc.js b/app/routes/misc.js new file mode 100644 index 0000000..b421eed --- /dev/null +++ b/app/routes/misc.js @@ -0,0 +1,53 @@ +"use strict"; + + +const email = require('../util/email'); +const moment = require('moment-timezone'); +const _ = require('lodash'); +var config = require('../../config/config')['prod']; + +var partsRequestTemplate = email.template( + 'partsRequest.html.tmpl', + 'partsRequest.text.tmpl', + 'Parts Request', + [ + 'techName', + 'requestDate', + 'customerId', + 'customerName', + 'customerContact', + 'customerPhone', + 'biomedId', + 'manufacture', + 'model', + 'serialNumber', + 'vendor', + 'vendorPhone', + 'partNumber', + 'description', + 'specialNotes' + ] +); + + +/** + * POST /api/misc/partsRequest + */ +function partsRequest(req, res) { + const message = { + to: config.email.partsRequest + }; + + const defaultValues = { + techName: `${req.user.name.first} ${req.user.name.last}`, + requestDate: moment().format('LLLL') + }; + + const values = _.assign({}, req.body, defaultValues); + + res.promise(email.send(message, partsRequestTemplate, values)); +} + +module.exports = { + partsRequest +}; diff --git a/app/routes/spans.js b/app/routes/spans.js new file mode 100644 index 0000000..019000e --- /dev/null +++ b/app/routes/spans.js @@ -0,0 +1,97 @@ +"use strict"; + +const moment = require('moment-timezone'); +const _ = require('lodash'); + +/** + * GET /api/spans + */ +function index(req, res) { + req.check('user').optional().isMongoId(); + req.check('workorder').optional().isMongoId(); + req.check('date').optional().isISO8601(); + req.check('week').optional().isISO8601(); + + if (!req.query.user && !req.query.workorder) { + return res.json({ + error: { + message: 'Must specify a type filter.' + } + }); + } + + if (req.query.user && !req.query.date && !req.query.week) { + return res.json({ + error: { + message: 'Must specify a date filter.' + } + }); + } + + const query = {}; + + if (req.query.user) { + query.user = req.query.user; + } + + if (req.query.workorder) { + query.workorder = req.query.workorder; + } + + if (req.query.date) { + const date = moment(req.query.date); + + const startOfDay = date.clone().startOf('day'); + const endOfDay = date.clone().endOf('day'); + + query.start = { + $gte: startOfDay, + $lte: endOfDay + }; + } + + if (req.query.week) { + const week = moment(req.query.week); + + const startOfWeek = week.clone().startOf('week'); + const endOfWeek = week.clone().endOf('week'); + + query.start = { + $gte: startOfWeek, + $lte: endOfWeek + }; + } + + var results = req.db.TimeClockSpan + .find(query) + .sort('start') + .exec(); + + res.promise(results); +} + +/** + * POST /api/spans/:user_id + */ +function update(req, res) { + req.check('id').isMongoId(); + + var data = req.body; + delete data._id; + delete data.__v; + + const result = req.db.TimeClockSpan + .findById(req.params.id) + .exec() + .then((entity) => { + _.assign(entity, data); + return entity.save(); + }); + + res.promise(result); +} + +module.exports = { + index, + update +}; diff --git a/app/routes/users.js b/app/routes/users.js new file mode 100644 index 0000000..b6ca491 --- /dev/null +++ b/app/routes/users.js @@ -0,0 +1,184 @@ +"use strict"; + +const Promise = require('bluebird'); +const moment = require('moment-timezone'); +const _ = require('lodash'); + +function filterFields(user) { + const obj = user.toObject(); + delete obj.accessToken; + delete obj.refreshToken; + return obj +} + + +/** + * GET /api/users/:id + */ +function fetch(req, res) { + let result; + + if (req.params.id === 'me') { + result = Promise.resolve(req.user); + } else { + result = req.db.User.findById(req.params.id); + } + + res.promise(result.then(filterFields)); +} + +/** + * POST /api/users/:id + */ +function update(req, res) { + req.check('id').isMongoId(); + + var data = req.body; + delete data._id; + delete data.__v; + delete data.name; + delete data.email; + delete data.accessToken; + delete data.refreshToken; + delete data.deleted; + + const result = req.db.User + .findById(req.params.id) + .exec() + .then((entity) => { + _.assign(entity, data); + return entity.save(); + }) + .then(filterFields); + + res.promise(result); +} + +/** + * GET /api/users/:id/daysWorked + */ +function daysWorked(req, res) { + const id = req.params.id === 'me' ? req.user.id : req.params.id; + + const query = { + user: id, + type: 'workday' + }; + + const result = req.db.TimeClockSpan + .find(query) + .exec() + .then((records) => _.chain(records).reduce(accumulateDaysWorked, []).values()); + + res.promise(result); +} + +/** + * GET /api/users/:id/weeksWorked + */ +function weeksWorked(req, res) { + const id = req.params.id === 'me' ? req.user.id : req.params.id; + + const query = { + user: id, + type: 'workday' + }; + + const result = req.db.TimeClockSpan + .find(query) + .exec() + .then((records) => _.chain(records).reduce(accumulateWeeksWorked, []).values()); + + res.promise(result); +} + +/** + * GET /api/users/:id/timeClock + */ +function timeClock(req, res) { + const id = req.params.id === 'me' ? req.user.id : req.params.id; + const date = moment(req.query.date); + const startOfDay = date.clone().startOf('day'); + const endOfDay = date.clone().endOf('day'); + + var spans = req.db.TimeClockSpan + .find({ + user: id, + start: { + $gte: startOfDay, + $lte: endOfDay + } + }) + .sort({ start: 1 }) + .exec(); + + var exceptions = req.db.TimeClockException + .find({ + user: id, + date: { + $gte: startOfDay, + $lte: endOfDay + } + }) + .exec(); + + var workorders = spans + .then(extractIds('workorder')) + .then((ids) => { + return req.db.Workorder + .find({ + _id: { + $in: ids + } + }) + .populate('client', 'name identifier') + .exec(); + }) + .then(indexById); + + res.promise(Promise.props({ + spans, + exceptions, + workorders + })); +} + +function accumulateDaysWorked(result, record) { + const date = moment(record.start).local().startOf('day').format('YYYY-MM-DD'); + + if (result.indexOf(date) === -1) { + result.push(date); + } + + return result; +} + +function accumulateWeeksWorked(result, record) { + const date = moment(record.start).local().startOf('week').format('YYYY-MM-DD'); + + if (result.indexOf(date) === -1) { + result.push(date); + } + + return result; +} + +function extractIds(field) { + return (data) => _(data) + .pluck(field) + .reject(_.isUndefined) + .uniq((id) => id.toString()) + .value(); +} + +function indexById(data) { + return _.indexBy(data, 'id') +} + +module.exports = { + fetch, + update, + daysWorked, + weeksWorked, + timeClock +}; diff --git a/app/routes/workorders.js b/app/routes/workorders.js new file mode 100644 index 0000000..eb77bf5 --- /dev/null +++ b/app/routes/workorders.js @@ -0,0 +1,67 @@ +"use strict"; + +const Promise = require('bluebird'); +const moment = require('moment-timezone'); +const _ = require('lodash'); + +/** + * GET /api/workorders/:id/timeClock + */ +function timeClock(req, res) { + req.check('id').isMongoId(); + + const id = req.params.id; + + const spans = req.db.TimeClockSpan + .find({ + workorder: id + }) + .exec(); + + const users = spans + .then(extractIds('user')) + .then((ids) => { + return req.db.User + .find({ + _id: { + $in: ids + } + }) + .select('name picture') + .exec(); + }) + .then(indexById); + + const duration = spans + .then((spans) => { + let result = 0; + spans.forEach((span) => { + if (span.duration) { + result += span.duration; + } + }); + return result; + }); + + res.promise(Promise.props({ + duration, + spans, + users + })); +} + +function extractIds(field) { + return (data) => _(data) + .pluck(field) + .reject(_.isUndefined) + .uniq((id) => id.toString()) + .value(); +} + +function indexById(data) { + return _.indexBy(data, 'id') +} + +module.exports = { + timeClock +}; diff --git a/app/templates/exception.html.tmpl b/app/templates/exception.html.tmpl new file mode 100644 index 0000000..ca8100b --- /dev/null +++ b/app/templates/exception.html.tmpl @@ -0,0 +1,74 @@ + + + + + + + + + + + +
+ + + + +
+ + + + + + + + + + + + + +
+ + + + +
+

Atlantic Biomedical

+
+
+ + + + +
+

Tech Exception

+
+
+ + + + + + +
+
+ + + + +
+ + + + + + + +
The following exception was made by <%- techName %> at <%- date %>
<%- message %>
+
+
+
+
+ + diff --git a/app/templates/exception.text.tmpl b/app/templates/exception.text.tmpl new file mode 100644 index 0000000..0ca2de9 --- /dev/null +++ b/app/templates/exception.text.tmpl @@ -0,0 +1,3 @@ +The following exception was made by <%- techName %> on <%- date %> + +<%- message %> diff --git a/app/templates/partsRequest.html.tmpl b/app/templates/partsRequest.html.tmpl new file mode 100644 index 0000000..6b29596 --- /dev/null +++ b/app/templates/partsRequest.html.tmpl @@ -0,0 +1,146 @@ + + + + + + + + + + + +
+ + + + +
+ + + + + + + + + + + + + +
+ + + + +
+

Atlantic Biomedical

+
+
+ + + + +
+

Parts Request

+
+
+ + + + + + +
+
+ + + + +
+ + + + + + + + + + + + + + + + <% if (customerContact) { %> + + + + + <% } %> + <% if (customerPhone) { %> + + + + + <% } %> + <% if (biomedId) { %> + + + + + <% } %> + + + + + + + + + + + + + + + + + + + + <% if (vendorPhone) { %> + + + + + <% } %> + + + + + + + + + + + + + + <% if (specialNotes) { %> + + + + + + + <% } %> +
The following request for parts was made by <%- techName %> on <%- requestDate %>

Customer

ID<%- customerId %>
Name<%- customerName %>
Contact<%- customerContact %>
Phone Number<%- customerPhone %>
Atlantic Biomedical ID<%- biomedId %>

Part Details

Manufacture<%- manufacture %>
Model<%- model %>
Serial Number<%- serialNumber %>
Vendor<%- vendor %>
Vendor Phone Number<%- vendorPhone %>
Part Number<%- partNumber %>

Other Details

Brief Description
<%- description %>
Special Notes
<%- specialNotes %>
+
+
+
+
+ + diff --git a/app/templates/partsRequest.text.tmpl b/app/templates/partsRequest.text.tmpl new file mode 100644 index 0000000..ca59bc1 --- /dev/null +++ b/app/templates/partsRequest.text.tmpl @@ -0,0 +1,58 @@ +The following request for parts was made by <%- techName %> on <%- requestDate %> + +Customer +ID: + <%- customerId %> + +Name: + <%- customerName %> + +<% if (customerContact) { %> +Contact: + <%- customerContact %> + +<% } %> +<% if (customerPhone) { %> +Phone Number: + <%- customerPhone %> + +<% } %> +<% if (biomedId) { %> +Atlantic Biomedical ID: + <%- biomedId %> + +<% } %> + + +Part Details +Manufacture: + <%- manufacture %> + +Model: + <%- model %> + + +Serial Number: + <%- serialNumber %> + +Vendor: + <%- vendor %> + +<% if (vendorPhone) { %> +Vendor Phone Number: + <%- vendorPhone %> + +<% } %> + +Part Number: + <%- partNumber %> + + +Other Details +Brief Description: +<%- description %> +<% if (specialNotes) { %> + +Special Notes: +<%- specialNotes %> +<% } %> diff --git a/app/util/email.js b/app/util/email.js new file mode 100644 index 0000000..66fe4ae --- /dev/null +++ b/app/util/email.js @@ -0,0 +1,100 @@ +'use strict'; + +const email = require('emailjs'); +const _ = require('lodash'); +const path = require('path'); +const Promise = require('bluebird'); + +const fs = Promise.promisifyAll(require('fs')); +var config = require('../../config/config')['prod']; + +const DEFAULT_HEADERS = { + from: 'api@atlanticbiomedical.com' +}; + +function template(htmlFile, textFile, subjectTemplate, defaultValues) { + if (_.isArray(defaultValues)) { + defaultValues = _.reduce(defaultValues, (result, key) => { + result[key] = ''; + return result; + }, {}); + } + + const builder = template => { + template = _.template(template); + return (values) => { + values = _.assign({}, defaultValues, values); + return template(values); + }; + }; + + var htmlTemplate = fs.readFileAsync(path.join(__dirname, '../templates', htmlFile)); + var textTemplate = fs.readFileAsync(path.join(__dirname, '../templates', textFile)); + + return Promise + .props({ + html: htmlTemplate, + text: textTemplate, + subject: subjectTemplate + }) + .then(templates => { + return { + html: builder(templates.html), + text: builder(templates.text), + subject: builder(templates.subject) + } + }); +} + +function send(headers, template, values) { + var message = _.assign({}, DEFAULT_HEADERS, headers); + message = prepairHeaders(message); + + return template.then(tmpl => { + message.text = tmpl.text(values); + message.subject = tmpl.subject(values); + message.attachment = [ + {data: tmpl.html(values), alternative: true} + ]; + + const server = email.server.connect({ + user: config.email.user, + password: config.email.password, + host: 'smtp.gmail.com', + ssl: true + }); + + return Promise.fromCallback(callback => { + server.send(message, callback); + }); + }) +} + +function prepairHeaders(headers) { + return _.reduce(headers, (result, header, key) => { + if (!_.isArray(header)) { + header = [header]; + } + + if (key === 'subject') { + result[key] = header; + } else { + result[key] = _ + .map(header, entry => { + if (_.isPlainObject(entry)) { + return `${entry.name} <${entry.email}>`; + } else { + return `<${entry}>`; + } + }) + .join(', '); + } + + return result; + }, {}); +} + +module.exports = { + send, + template +}; diff --git a/config/auth.js b/config/auth.js index cd59319..de863ed 100644 --- a/config/auth.js +++ b/config/auth.js @@ -8,203 +8,214 @@ var moment = require('moment'); var ACCESS_TOKEN_URL = 'https://accounts.google.com/o/oauth2/token'; var PEOPLE_API_URL = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect'; -module.exports = function(app, passport, config) { +module.exports = function (app, passport, config) { - function createJWT(user) { - var payload = { - sub: user._id, - iat: moment().unix(), - exp: moment().add(14, 'days').unix() - }; + function createJWT(user) { + var payload = { + sub: user._id, + iat: moment().unix(), + exp: moment().add(14, 'days').unix() + }; - return jwt.encode(payload, config.auth.jwtSecret); - } + return jwt.encode(payload, config.auth.jwtSecret); + } - app.post('/auth2', function(req, res) { - var params = { - code: req.body.code, - client_id: req.body.clientId, - client_secret: config.auth.clientSecret, - redirect_uri: req.body.redirectUri, - grant_type: 'authorization_code' - }; + app.post('/auth2', function (req, res) { + var params = { + code: req.body.code, + client_id: req.body.clientId, + client_secret: config.auth.clientSecret, + redirect_uri: req.body.redirectUri, + grant_type: 'authorization_code' + }; - request.post(ACCESS_TOKEN_URL, { json: true, form: params }, function(err, response, token) { - console.log(token); + request.post(ACCESS_TOKEN_URL, {json: true, form: params}, function (err, response, token) { + console.log(token); - var accessToken = token.access_token; - var headers = { - Authorization: 'Bearer ' + accessToken - }; + var accessToken = token.access_token; + var headers = { + Authorization: 'Bearer ' + accessToken + }; - request.get({ url: PEOPLE_API_URL, headers: headers, json: true }, function(err, response, profile) { - if (profile.error) { - return res.status(500).send({ message: profile.error.message }); - } + request.get({url: PEOPLE_API_URL, headers: headers, json: true}, function (err, response, profile) { + if (profile.error) { + return res.status(500).send({message: profile.error.message}); + } - User.findOne({ email: profile.email.toLowerCase() }, function(err, user) { - if (err) { - return res.status(500).send(err); - } + User.findOne({email: profile.email.toLowerCase()}, function (err, user) { + if (err) { + return res.status(500).send(err); + } - if (!user || !user.hasPermission('system.login')) { - return res.status(403).send({ message: "You are not authorized to access this portal."}); - } +// if (!user || !user.hasPermission('system.login')) { +// return res.status(403).send({message: "You are not authorized to access this portal."}); +// } - user.accessToken = token.access_token; + user.accessToken = token.access_token; - if (token.refresh_token) { - user.refreshToken = token.refresh_token; - } + if (token.refresh_token) { + user.refreshToken = token.refresh_token; + } - if (profile.given_name) { - user.name.first = profile.given_name; - } + if (profile.given_name) { + user.name.first = profile.given_name; + } - if (profile.family_name) { - user.name.last = profile.family_name; - } + if (profile.family_name) { + user.name.last = profile.family_name; + } - if (profile.picture) { - user.picture = profile.picture.replace('sz=50', 'sz=200'); - } + if (profile.picture) { + user.picture = profile.picture.replace('?sz=50', ''); + } - user.save() - .then(function() { - res.send({ token: createJWT(user) }); - }); - }); - }); - }) - }); - - - - app.get('/auth', function(req, res, next) { - console.dir(req.headers); - req.session.redirectUrl = req.headers['referer']; - - passport.authenticate('google', { - accessType: 'offline', - scope: [ - 'https://www.googleapis.com/auth/userinfo.profile', - 'https://www.googleapis.com/auth/userinfo.email', - 'https://www.googleapis.com/auth/calendar' - ]})(req, res, next); - }); - - app.get('/auth/callback', function(req, res, next) { - - var callbackHost = req.headers['x-forwarded-host']; - if (!callbackHost) { - callbackHost = "localhost:9000"; - } - - var options = { - callbackURL: 'http://' + callbackHost + '/auth/callback' - }; - passport.authenticate('google', options, function(err, user, info) { - var redirectUrl = '/'; - - if (err) { return next(err); } - if (!user) { return res.redirect('/login/error'); } - - log.setPrefix("[%d] %l "); - log.info("User Logged In: %s %s", user.name.first, user.name.last); - - res.cookie('atlbid', JSON.stringify(user._id), {signed:true}); - - if (req.session.redirectUrl) { - redirectUrl = req.session.redirectUrl; - req.session.redirectUrl = null; - } - - if (redirectUrl.indexOf('/login') != -1) { - redirectUrl = '/'; - } - - req.logIn(user, function(err) { - if (err) { return next(err); } - }); - - res.redirect(redirectUrl); - })(req, res, next); - }); - - function createAuthenticator(error) { - return function(req, res, next) { - var onError = function() { - error(req, res, next); - }; - - var onSuccess = function(user) { - log.setPrefix(function(level) { - return '[' + new Date().toUTCString() + '] ' + level.toUpperCase() + ' ' + user.name.first + ' ' + user.name.last + ' | '; - }); - next(); - } - - if (!req.isAuthenticated()) { - if (!req.headers.authorization) { - return onError(); - } - - var token = req.headers.authorization.split(' ')[1]; - var payload = null; - try { - payload = jwt.decode(token, config.auth.jwtSecret); - } catch (err) { - return onError(); - } - - if (payload.exp <= moment().unix()) { - return onError(); - } - - User.findById(payload.sub, function(err, user) { - console.log('Loaded User'); - req.user = user; - - onSuccess(user); - }); - } else { - onSuccess(req.user); - } - } - } - - return { - requiresUiLogin: createAuthenticator(function(req, res, next) { - res.redirect('/login'); - }), - - requiresApiAccess: createAuthenticator(function(req, res, next) { - res.send(403); - }) - }; - -/* - return { - requiresUiLogin: function(req, res, next) { - if (!req.isAuthenticated()) { - return res.redirect('/login'); - } - - log.setPrefix(function(level) { - return '[' + new Date().toUTCString() + '] ' + level.toUpperCase() + ' ' + req.user.name.first + ' ' + req.user.name.last + ' | '; + user.save() + .then(function () { + res.send({token: createJWT(user)}); }); - next(); - }, - requiresApiAccess: function(req, res, next) { - if (!req.isAuthenticated()) { - return res.send(403); - } + }); + }); + }) + }); - log.setPrefix(function(level) { - return '[' + new Date().toUTCString() + '] ' + level.toUpperCase() + ' ' + req.user.name.first + ' ' + req.user.name.last + ' | '; - }); - next(); - } - }; -*/ + + app.get('/auth', function (req, res, next) { + console.dir(req.headers); + req.session.redirectUrl = req.headers['referer']; + + passport.authenticate('google', { + accessType: 'offline', + scope: [ + 'https://www.googleapis.com/auth/userinfo.profile', + 'https://www.googleapis.com/auth/userinfo.email', + 'https://www.googleapis.com/auth/calendar' + ] + })(req, res, next); + }); + + app.get('/auth/callback', function (req, res, next) { + + var callbackHost = req.headers['x-forwarded-host']; + if (!callbackHost) { + callbackHost = "localhost:9000"; + } + + var options = { + callbackURL: 'http://' + callbackHost + '/auth/callback' + }; + passport.authenticate('google', options, function (err, user, info) { + var redirectUrl = '/'; + + if (err) { + return next(err); + } + if (!user) { + return res.redirect('/login/error'); + } + + log.setPrefix("[%d] %l "); + log.info("User Logged In: %s %s", user.name.first, user.name.last); + + res.cookie('atlbid', JSON.stringify(user._id), {signed: true}); + + if (req.session.redirectUrl) { + redirectUrl = req.session.redirectUrl; + req.session.redirectUrl = null; + } + + if (redirectUrl.indexOf('/login') != -1) { + redirectUrl = '/'; + } + + req.logIn(user, function (err) { + if (err) { + return next(err); + } + }); + + res.redirect(redirectUrl); + })(req, res, next); + }); + + function createAuthenticator(error) { + return function (req, res, next) { + var onError = function () { + error(req, res, next); + }; + + var onSuccess = function (user) { + log.setPrefix(function (level) { + return '[' + new Date().toUTCString() + '] ' + level.toUpperCase() + ' ' + user.name.first + ' ' + user.name.last + ' | '; + }); + next(); + } + + if (!req.isAuthenticated()) { + if (!req.headers.authorization) { + return onError(); + } + + var token = req.headers.authorization.split(' ')[1]; + var payload = null; + try { + payload = jwt.decode(token, config.auth.jwtSecret); + } catch (err) { + return onError(); + } + + console.log(payload); + + if (payload.exp <= moment().unix()) { + return onError(); + } + + User.findById(payload.sub, function (err, user) { + if (user) { + console.log('Loaded User'); + req.user = user; + onSuccess(user); + } else { + onError(); + } + }); + } else { + onSuccess(req.user); + } + } + } + + return { + requiresUiLogin: createAuthenticator(function (req, res, next) { + res.redirect('/login'); + }), + + requiresApiAccess: createAuthenticator(function (req, res, next) { + res.send(403); + }) + }; + + /* + return { + requiresUiLogin: function(req, res, next) { + if (!req.isAuthenticated()) { + return res.redirect('/login'); + } + + log.setPrefix(function(level) { + return '[' + new Date().toUTCString() + '] ' + level.toUpperCase() + ' ' + req.user.name.first + ' ' + req.user.name.last + ' | '; + }); + next(); + }, + requiresApiAccess: function(req, res, next) { + if (!req.isAuthenticated()) { + return res.send(403); + } + + log.setPrefix(function(level) { + return '[' + new Date().toUTCString() + '] ' + level.toUpperCase() + ' ' + req.user.name.first + ' ' + req.user.name.last + ' | '; + }); + next(); + } + }; + */ }; diff --git a/config/config.js b/config/config.js index 698bfee..5e05563 100644 --- a/config/config.js +++ b/config/config.js @@ -1,44 +1,22 @@ module.exports = { - development: { - root: require('path').normalize(__dirname + '/..'), - debug: true, - database: 'mongodb://wootbox.wootroot.me/biomed_prod', - auth: { - clientId: '223145213165.apps.googleusercontent.com', - clientSecret: '8MRNar9E_pRTOGTQonPzYOW_', - callback: 'http://devel.portal.atlanticbiomedical.com/auth/callback', - accessToken: 'ya29.AHES6ZR-vUVEh7CZzsEeGFSHqFfXtU1-LHyEAidi0CKhDGQ', - refreshToken: '1/exRXjTaGNlWEo-HZZWyn4NTwJ4TY3wKb-_npce21c50' - }, - email: { - user: 'api@atlanticbiomedical.com', - password: 'success4' - }, - mysql: { - host: 'biomed.akira.gs', - user: 'biomed_prod', - password: 'wUw3RB8rrXX4HwKj', - database: 'biomed_prod' - } - }, prod: { root: require('path').normalize(__dirname + '/..'), debug: true, - database: 'mongodb://localhost/biomed_prod', + database: 'mongodb://localhost/biomed', auth: { clientId: '333768673996-8epedo3je5h59n4l97v4dv8nofs7qnee.apps.googleusercontent.com', clientSecret: 'afu9KhKxckWJ3Tk6uxzp9Pg6', callback: 'http://localhost:9000/auth/callback', -// accessToken: 'ya29.AHES6ZT1Sj1vpgidR2I_ksLdlV_VeZUjkitnZ01cP6VRrknjUEVbuw', -// refreshToken: '1/XQW9P9FNYm6jikTsV8HOIuPAo1APYhwTH5CLhq9263g' - accessToken: 'ya29.1.AADtN_Xjt0PK6YVs8q5csiQFXQg2ZDtrVhsH6P4a5zm0mHqhGx0Nnjx4Jk68Gw', refreshToken: '1/_5SkDLYmsi4XNaQyAzld-W5-GEqEqt5byH6VkI-j5QI', jwtSecret: '97v4dvcsiQFXQg28nofedo3jemsi4XNaQy5h59n4l97m0mHqhGx0Nnjxv4dv8n' }, email: { user: 'api@atlanticbiomedical.com', - password: 'success4' + password: 'success4', + + partsRequest: 'akirayasha@gmail.com', + exception: 'akirayasha@gmail.com' }, mysql: { host: 'localhost', diff --git a/config/db.js b/config/db.js new file mode 100644 index 0000000..08e1e00 --- /dev/null +++ b/config/db.js @@ -0,0 +1,30 @@ +'use strict'; + +const mongoose = require('mongoose'); +const models = [ + 'CheckList', + 'Client', + 'Counter', + 'Device', + 'DeviceType', + 'Pm', + 'Post', + 'Tag', + 'TestRun', + 'TimeClockException', + 'TimeClockSpan', + 'User', + 'Workorder' +]; + +module.exports = function() { + return function(req, res, next) { + req.db = {}; + + models.forEach((model) => { + req.db[model] = mongoose.model(model); + }); + + next(); + } +}; diff --git a/config/express.js b/config/express.js index e0d2e20..10160f5 100644 --- a/config/express.js +++ b/config/express.js @@ -1,6 +1,9 @@ var express = require('express'); var cors = require('cors'); var ClusterStore = require('strong-cluster-connect-store')(express.session); +var validators = require('./validators'); +var db = require('./db'); +var promise = require('./promise'); module.exports = function(app, config, passport, piler) { app.set('showStackError', true); @@ -16,6 +19,9 @@ module.exports = function(app, config, passport, piler) { // bodyParser should be above methodOverride app.use(express.bodyParser()); + app.use(validators()); + app.use(db()); + app.use(promise()); app.use(express.methodOverride()); app.use(express.session({ store: new ClusterStore(), secret: 'atlantic_biomed_server_secret' })); @@ -40,9 +46,4 @@ module.exports = function(app, config, passport, piler) { // routes should be last app.use(app.router); }); - -// app.configure('development', function() { -// // enable live update in development mode. -// piler.liveUpdate(); -// }); } diff --git a/config/promise.js b/config/promise.js new file mode 100644 index 0000000..2dbe2ad --- /dev/null +++ b/config/promise.js @@ -0,0 +1,36 @@ +'use strict'; + +const mongoose = require('mongoose'); + +module.exports = function() { + return function(req, res, next) { + res.promise = (promise) => { + promise + .then((data) => { + res.json({ + data + }); + }) + .catch((error) => { + if (typeof error === 'string') { + return res.json(400, { + error: { + message: error + } + }); + } + + if (error.name === 'ValidationError') { + return res.json(400, { + error: error + }); + } + + console.log(error.stack); + res.json(500, 'Internal error'); + }); + }; + + next(); + }; +}; diff --git a/config/routes.js b/config/routes.js index 2291676..33e5f77 100644 --- a/config/routes.js +++ b/config/routes.js @@ -1,140 +1,168 @@ -var log = require('log4node'); - -module.exports = function(app, auth, piler, calendar, directory, config) { - - piler.addCssUrl("//fonts.googleapis.com/css?family=Open+Sans:400,300"); - piler.addCssFile("/css/biomed.less"); - - piler.addJsUrl("//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"); - piler.addJsUrl("//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"); - piler.addJsUrl("//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.js"); - piler.addJsUrl("//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-resource.js"); - piler.addJsUrl("http://d3js.org/d3.v2.js"); - piler.addJsUrl("https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js") - - piler.addJsFile("/js/lib/moment.js"); - piler.addJsFile("/js/lib/bootstrap-datepicker.js"); - piler.addJsFile("/js/lib/dialog.js"); - piler.addJsFile("/js/lib/select2.js"); - piler.addJsFile("/js/lib/dropzone.js"); - piler.addJsFile("/js/lib/hashids.js"); - piler.addJsFile("/js/app.js"); - piler.addJsFile("/js/controllers.js"); - piler.addJsFile("/js/controllers/checkLists.js"); - piler.addJsFile("/js/controllers/devices.js"); - piler.addJsFile("/js/controllers/deviceTypes.js"); - piler.addJsFile("/js/controllers/testRuns.js"); - piler.addJsFile("/js/directives.js"); - piler.addJsFile("/js/filters.js"); - piler.addJsFile("/js/services.js"); - - app.get('/crash', function(req, res) { - console.log('Commiting Suicide for Science!'); - process.nextTick(function() { - throw new Error("Ermergerd!"); - }); - }); - - app.all('/api/*', auth.requiresApiAccess); - - var posts = require('../app/controllers/posts'); - app.get('/api/posts', posts.index); - app.get('/api/posts/:post_id', posts.get); - app.post('/api/posts', posts.create); - app.post('/api/posts/upload', posts.upload); - app.post('/api/posts/:post_id', posts.update); - app.del('/api/posts/:post_id', posts.destroy); - - var clients = require('../app/controllers/clients'); - app.get('/api/clients', clients.index); - app.get('/api/clients/isUnique', clients.isUnique); - app.get('/api/clients/frequencies', clients.frequencies); - app.get('/api/clients/:client_id', clients.get); - app.get('/api/clients/:client_id/workorders', clients.workorders); - app.get('/api/clients/:client_id/tags', clients.tags); - app.get('/api/clients/:client_id/devices', clients.devices); - app.post('/api/clients', clients.create); - app.post('/api/clients/:client_id', clients.update); - app.del('/api/clients/:client_id', clients.destroy); - - var workorders = require('../app/controllers/workorders')(config, calendar); - app.get('/api/workorders', workorders.index); - app.get('/api/workorders/:workorder_id', workorders.get); - app.post('/api/workorders', workorders.create); - app.post('/api/workorders/:workorder_id', workorders.update); - app.del('/api/workorders/:workorder_id', workorders.destroy); - - var devices = require('../app/controllers/devices'); - app.get('/api/devices', devices.index); - app.get('/api/devices/isUnique', devices.isUnique); - app.get('/api/devices/:device_id', devices.get); - app.get('/api/devices/:device_id/test_runs', devices.testRuns); - app.post('/api/devices', devices.create); - app.post('/api/devices/:device_id', devices.update); - - var deviceTypes = require('../app/controllers/deviceTypes'); - app.get('/api/device_types', deviceTypes.index); - app.get('/api/device_types/categories', deviceTypes.categories); - app.get('/api/device_types/makes', deviceTypes.makes); - app.get('/api/device_types/models', deviceTypes.models); - app.post('/api/device_types/images', deviceTypes.upload); - app.get('/api/device_types/:device_type_id', deviceTypes.get); - app.post('/api/device_types', deviceTypes.create); - app.post('/api/device_types/:device_type_id', deviceTypes.update); - - var checkLists = require('../app/controllers/checkLists'); - app.get('/api/check_lists', checkLists.index); - app.get('/api/check_lists/:check_list_id', checkLists.get); - app.post('/api/check_lists', checkLists.create); - app.post('/api/check_lists/:check_list_id', checkLists.update); - - var testRuns = require('../app/controllers/testRuns')(config); - app.get('/api/test_runs', testRuns.index); - app.get('/api/test_runs/:test_run_id', testRuns.get); - app.post('/api/test_runs', testRuns.create); - app.post('/api/test_runs/:test_run_id', testRuns.update); - - var timeclock = require('../app/controllers/timeclock')(); - app.get('/api/timeclock', timeclock.index); - app.post('/api/timeclock/clock_in', timeclock.clockIn); - app.post('/api/timeclock/clock_out', timeclock.clockOut); - app.get('/api/timeclock/workorder/:id', timeclock.workorderDetails); - - var pms = require('../app/controllers/pms'); - app.get('/api/pms', pms.index); - - var schedule = require('../app/controllers/schedule'); - app.get('/api/schedule', schedule.index); - - var users = require('../app/controllers/users')(config, directory); - app.get('/api/users', users.index); - app.get('/api/users/details', users.details); - app.post('/api/users', users.create); - app.post('/api/users/:user_id', users.update); - app.get('/api/users/:user_id/clocks', users.clocks); - - var account = require('../app/controllers/account')(config); - app.get('/api/account', account.profile); - app.post('/api/account/impersonate', account.impersonate); - - var messages = require('../app/controllers/messages')(config); - app.post('/api/messages/send', messages.send); - - var tags = require('../app/controllers/tags')(piler); - app.post('/api/tags', tags.post); - - var clock = require('../app/controllers/clock')(piler); - app.post('/api/clock', clock.post); - - var site = require('../app/controllers/site')(piler); - - var login = require('../app/controllers/login')(piler); - app.get('/login', login.login); - app.get('/login/error', login.error); - app.get('/logout', login.logout); - - var home = require('../app/controllers/home')(piler); - - app.get('/', tags.index, auth.requiresUiLogin, clock.index, site.index, home.index); - app.get('*', tags.index, auth.requiresUiLogin, clock.index, site.index, home.index); -}; +var log = require('log4node'); + +var routes = require('../app/routes'); + +module.exports = function (app, auth, piler, calendar, directory, config) { + + piler.addCssUrl("//fonts.googleapis.com/css?family=Open+Sans:400,300"); + piler.addCssFile("/css/biomed.less"); + + piler.addJsUrl("//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"); + piler.addJsUrl("//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js"); + piler.addJsUrl("//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.js"); + piler.addJsUrl("//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-resource.js"); + piler.addJsUrl("http://d3js.org/d3.v2.js"); + piler.addJsUrl("https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js") + + piler.addJsFile("/js/lib/moment.js"); + piler.addJsFile("/js/lib/bootstrap-datepicker.js"); + piler.addJsFile("/js/lib/dialog.js"); + piler.addJsFile("/js/lib/select2.js"); + piler.addJsFile("/js/lib/dropzone.js"); + piler.addJsFile("/js/lib/hashids.js"); + piler.addJsFile("/js/app.js"); + piler.addJsFile("/js/controllers.js"); + piler.addJsFile("/js/controllers/checkLists.js"); + piler.addJsFile("/js/controllers/devices.js"); + piler.addJsFile("/js/controllers/deviceTypes.js"); + piler.addJsFile("/js/controllers/testRuns.js"); + piler.addJsFile("/js/directives.js"); + piler.addJsFile("/js/filters.js"); + piler.addJsFile("/js/services.js"); + + app.get('/crash', function (req, res) { + console.log('Commiting Suicide for Science!'); + process.nextTick(function () { + throw new Error("Ermergerd!"); + }); + }); + + app.all('/api/*', auth.requiresApiAccess); + + var posts = require('../app/controllers/posts'); + app.get('/api/posts', posts.index); + app.get('/api/posts/:post_id', posts.get); + app.post('/api/posts', posts.create); + app.post('/api/posts/upload', posts.upload); + app.post('/api/posts/:post_id', posts.update); + app.del('/api/posts/:post_id', posts.destroy); + + var clients = require('../app/controllers/clients'); + app.get('/api/clients', clients.index); + app.get('/api/clients/isUnique', clients.isUnique); + app.get('/api/clients/frequencies', clients.frequencies); + app.get('/api/clients/:client_id', clients.get); + app.get('/api/clients/:client_id/workorders', clients.workorders); + app.get('/api/clients/:client_id/tags', clients.tags); + app.get('/api/clients/:client_id/devices', clients.devices); + app.post('/api/clients', clients.create); + app.post('/api/clients/:client_id', clients.update); + app.del('/api/clients/:client_id', clients.destroy); + + var workorders = require('../app/controllers/workorders')(config, calendar); + app.get('/api/workorders', workorders.index); + app.get('/api/workorders/:workorder_id', workorders.get); + app.post('/api/workorders', workorders.create); + app.post('/api/workorders/:workorder_id', workorders.update); + app.del('/api/workorders/:workorder_id', workorders.destroy); + + var devices = require('../app/controllers/devices'); + app.get('/api/devices', devices.index); + app.get('/api/devices/isUnique', devices.isUnique); + app.get('/api/devices/:device_id', devices.get); + app.get('/api/devices/:device_id/test_runs', devices.testRuns); + app.post('/api/devices', devices.create); + app.post('/api/devices/:device_id', devices.update); + + var deviceTypes = require('../app/controllers/deviceTypes'); + app.get('/api/device_types', deviceTypes.index); + app.get('/api/device_types/categories', deviceTypes.categories); + app.get('/api/device_types/makes', deviceTypes.makes); + app.get('/api/device_types/models', deviceTypes.models); + app.post('/api/device_types/images', deviceTypes.upload); + app.get('/api/device_types/:device_type_id', deviceTypes.get); + app.post('/api/device_types', deviceTypes.create); + app.post('/api/device_types/:device_type_id', deviceTypes.update); + + var checkLists = require('../app/controllers/checkLists'); + app.get('/api/check_lists', checkLists.index); + app.get('/api/check_lists/:check_list_id', checkLists.get); + app.post('/api/check_lists', checkLists.create); + app.post('/api/check_lists/:check_list_id', checkLists.update); + + var testRuns = require('../app/controllers/testRuns')(config); + app.get('/api/test_runs', testRuns.index); + app.get('/api/test_runs/:test_run_id', testRuns.get); + app.post('/api/test_runs', testRuns.create); + app.post('/api/test_runs/:test_run_id', testRuns.update); + + var timeclock = require('../app/controllers/timeclock')(); + app.get('/api/timeclock', timeclock.index); + app.post('/api/timeclock/clock_in', timeclock.clockIn); + app.post('/api/timeclock/clock_out', timeclock.clockOut); + app.get('/api/timeclock/users/:user_id', timeclock.spansForUser); + app.get('/api/timeclock/workorder/:id', timeclock.workorderDetails); + + var timesheet = require('../app/controllers/timesheet')(); + app.get('/api/timesheet/summary', timesheet.summary); + app.get('/api/timesheet/:user_id/daysWorked', timesheet.daysWorked); + app.get('/api/timesheet/:user_id/summary', timesheet.userSummary); + + var pms = require('../app/controllers/pms'); + app.get('/api/pms', pms.index); + + var schedule = require('../app/controllers/schedule'); + app.get('/api/schedule', schedule.index); + + var users = require('../app/controllers/users')(config, directory); + app.get('/api/users', users.index); + app.get('/api/users/details', users.details); + app.get('/api/users/:user_id', users.get); + app.post('/api/users', users.create); + app.post('/api/users/:user_id', users.update); + app.get('/api/users/:user_id/clocks', users.clocks); + + var account = require('../app/controllers/account')(config); + app.get('/api/account', account.profile); + app.post('/api/account/impersonate', account.impersonate); + + var messages = require('../app/controllers/messages')(config); + app.post('/api/messages/send', messages.send); + + var tags = require('../app/controllers/tags')(piler); + app.post('/api/tags', tags.post); + + var site = require('../app/controllers/site')(piler); + + var login = require('../app/controllers/login')(piler); + app.get('/login', login.login); + app.get('/login/error', login.error); + app.get('/logout', login.logout); + + var home = require('../app/controllers/home')(piler); + + + + // Exceptions + app.get('/api/v2/exceptions', routes.exceptions.index); + + // Spans + app.get('/api/v2/spans', routes.spans.index); + app.post('/api/v2/spans/:id', routes.spans.update); + + // Users + app.get('/api/v2/users/:id/daysWorked', routes.users.daysWorked); + app.get('/api/v2/users/:id/weeksWorked', routes.users.weeksWorked); + app.get('/api/v2/users/:id/timeClock', routes.users.timeClock); + app.get('/api/v2/users/:id', routes.users.fetch); + app.post('/api/v2/users/:id', routes.users.update); + + // Workorders + app.get('/api/v2/workorders/:id/timeClock', routes.workorders.timeClock); + + // Misc + app.post('/api/v2/misc/partsRequest', routes.misc.partsRequest); + + app.get('/', tags.index, auth.requiresUiLogin, site.index, home.index); + app.get('*', tags.index, auth.requiresUiLogin, site.index, home.index); +}; diff --git a/config/validators.js b/config/validators.js new file mode 100644 index 0000000..9266acb --- /dev/null +++ b/config/validators.js @@ -0,0 +1,25 @@ + +'use strict'; + +var moment = require('moment'); +var expressValidator = require('express-validator'); + +module.exports = function() { + return expressValidator({ + customValidators: { + isWeek + }, + customSanitizers: { + toMoment + } + }); +}; + +function isWeek(str) { + let week = moment(str, 'YYYY-MM-DD'); + return week.isValid() && week.weekday() === 0; +} + +function toMoment(str) { + return moment(str); +} \ No newline at end of file diff --git a/node_modules/bluebird/LICENSE b/node_modules/bluebird/LICENSE index a3966cf..4182a1e 100644 --- a/node_modules/bluebird/LICENSE +++ b/node_modules/bluebird/LICENSE @@ -1,13 +1,13 @@ The MIT License (MIT) -Copyright (c) 2014 Petka Antonov +Copyright (c) 2013-2015 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:

+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. diff --git a/node_modules/bluebird/README.md b/node_modules/bluebird/README.md index 5e92095..2ffd5d0 100644 --- a/node_modules/bluebird/README.md +++ b/node_modules/bluebird/README.md @@ -5,657 +5,25 @@ [![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) [![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) +**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) # Introduction -Bluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance +Bluebird is a fully featured promise library with focus on innovative features and performance +See the [bluebird website](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions. - -# Topics - -- [Features](#features) -- [Quick start](#quick-start) -- [API Reference and examples](API.md) -- [Support](#support) -- [What are promises and why should I use them?](#what-are-promises-and-why-should-i-use-them) -- [Questions and issues](#questions-and-issues) -- [Error handling](#error-handling) -- [Development](#development) - - [Testing](#testing) - - [Benchmarking](#benchmarks) - - [Custom builds](#custom-builds) - - [For library authors](#for-library-authors) -- [What is the sync build?](#what-is-the-sync-build) -- [License](#license) -- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets) -- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) -- [Changelog](changelog.md) -- [Optimization guide](#optimization-guide) - -# Features -bluebird logo - -- [Promises A+](http://promisesaplus.com) -- [Synchronous inspection](API.md#synchronous-inspection) -- [Concurrency coordination](API.md#collections) -- [Promisification on steroids](API.md#promisification) -- [Resource management through a parallel of python `with`/C# `using`](API.md#resource-management) -- [Cancellation and timeouts](API.md#cancellation) -- [Parallel for C# `async` and `await`](API.md#generators) -- Mind blowing utilities such as - - [`.bind()`](API.md#binddynamic-thisarg---promise) - - [`.call()`](API.md#callstring-propertyname--dynamic-arg---promise) - - [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) - - [And](API.md#core) [much](API.md#timers) [more](API.md#utility)! -- [Practical debugging solutions and sane defaults](#error-handling) -- [Sick performance](benchmark/) - -
- -# Quick start - -## Node.js - - npm install bluebird - -Then: - -```js -var Promise = require("bluebird"); -``` - -## Browsers - -There are many ways to use bluebird in browsers: - -- Direct downloads - - Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js) - - Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js) -- You may use browserify on the main export -- You may use the [bower](http://bower.io) package. - -When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available. - -A [minimal bluebird browser build](#custom-builds) is ≈38.92KB minified*, 11.65KB gzipped and has no external dependencies. - -*Google Closure Compiler using Simple. - -#### Browser support - -Browsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported. - -[![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov) - -**Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`. - -Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+. - -After quick start, see [API Reference and examples](API.md) - -
- -# Support - -- Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js) -- IRC: #promises @freenode -- StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird) -- Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open) - -
- -# What are promises and why should I use them? - -You should use promises to turn this: - -```js -fs.readFile("file.json", function(err, val) { - if( err ) { - console.error("unable to read file"); - } - else { - try { - val = JSON.parse(val); - console.log(val.success); - } - catch( e ) { - console.error("invalid json in file"); - } - } -}); -``` - -Into this: - -```js -fs.readFileAsync("file.json").then(JSON.parse).then(function(val) { - console.log(val.success); -}) -.catch(SyntaxError, function(e) { - console.error("invalid json in file"); -}) -.catch(function(e) { - console.error("unable to read file") -}); -``` - -*If you are wondering "there is no `readFileAsync` method on `fs` that returns a promise", see [promisification](API.md#promisification)* - -Actually you might notice the latter has a lot in common with code that would do the same using synchronous I/O: - -```js -try { - var val = JSON.parse(fs.readFileSync("file.json")); - console.log(val.success); -} -//Syntax actually not supported in JS but drives the point -catch(SyntaxError e) { - console.error("invalid json in file"); -} -catch(Error e) { - console.error("unable to read file") -} -``` - -And that is the point - being able to have something that is a lot like `return` and `throw` in synchronous code. - -You can also use promises to improve code that was written with callback helpers: - - -```js -//Copyright Plato http://stackoverflow.com/a/19385911/995876 -//CC BY-SA 2.5 -mapSeries(URLs, function (URL, done) { - var options = {}; - needle.get(URL, options, function (error, response, body) { - if (error) { - return done(error) - } - try { - var ret = JSON.parse(body); - return done(null, ret); - } - catch (e) { - done(e); - } - }); -}, function (err, results) { - if (err) { - console.log(err) - } else { - console.log('All Needle requests successful'); - // results is a 1 to 1 mapping in order of URLs > needle.body - processAndSaveAllInDB(results, function (err) { - if (err) { - return done(err) - } - console.log('All Needle requests saved'); - done(null); - }); - } -}); -``` - -Is more pleasing to the eye when done with promises: - -```js -Promise.promisifyAll(needle); -var options = {}; - -var current = Promise.resolve(); -Promise.map(URLs, function(URL) { - current = current.then(function () { - return needle.getAsync(URL, options); - }); - return current; -}).map(function(responseAndBody){ - return JSON.parse(responseAndBody[1]); -}).then(function (results) { - return processAndSaveAllInDB(results); -}).then(function(){ - console.log('All Needle requests saved'); -}).catch(function (e) { - console.log(e); -}); -``` - -Also promises don't just give you correspondences for synchronous features but can also be used as limited event emitters or callback aggregators. - -More reading: - - - [Promise nuggets](https://promise-nuggets.github.io/) - - [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html) - - [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1) - - [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets) - - [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) +For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x). # Questions and issues -If you find a bug in bluebird or have a feature request, file an issue in the [github issue tracker](https://github.com/petkaantonov/bluebird/issues). Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. - -# Error handling - -This is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled. - -There are two common pragmatic attempts at solving the problem that promise libraries do. - -The more popular one is to have the user explicitly communicate that they are done and any unhandled rejections should be thrown, like so: - -```js -download().then(...).then(...).done(); -``` - -For handling this problem, in my opinion, this is completely unacceptable and pointless. The user must remember to explicitly call `.done` and that cannot be justified when the problem is forgetting to create an error handler in the first place. - -The second approach, which is what bluebird by default takes, is to call a registered handler if a rejection is unhandled by the start of a second turn. The default handler is to write the stack trace to `stderr` or `console.error` in browsers. This is close to what happens with synchronous code - your code doesn't work as expected and you open console and see a stack trace. Nice. - -Of course this is not perfect, if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages. In that case you can use the `.done()` method to signal that any hanging exceptions should be thrown. - -If you want to override the default handler for these possibly unhandled rejections, you can pass yours like so: - -```js -Promise.onPossiblyUnhandledRejection(function(error){ - throw error; -}); -``` - -If you want to also enable long stack traces, call: - -```js -Promise.longStackTraces(); -``` - -right after the library is loaded. - -In node.js use the environment flag `BLUEBIRD_DEBUG`: - -``` -BLUEBIRD_DEBUG=1 node server.js -``` - -to enable long stack traces in all instances of bluebird. - -Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, even after using every trick to optimize them. - -Long stack traces are enabled by default in the debug build. - -#### Expected and unexpected errors - -A practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about. - -Now, Javascript does have a perfectly fine and working way of creating error type hierarchies. It is still quite awkward to use them with the built-in `try-catch` however: - -```js -try { - //code -} -catch(e) { - if( e instanceof WhatIWantError) { - //handle - } - else { - throw e; - } -} -``` - -Without such checking, unexpected errors would be silently swallowed. However, with promises, bluebird brings the future (hopefully) here now and extends the `.catch` to [accept potential error type eligibility](API.md#catchfunction-errorclass-function-handler---promise). - -For instance here it is expected that some evil or incompetent entity will try to crash our server from `SyntaxError` by providing syntactically invalid JSON: - -```js -getJSONFromSomewhere().then(function(jsonString) { - return JSON.parse(jsonString); -}).then(function(object) { - console.log("it was valid json: ", object); -}).catch(SyntaxError, function(e){ - console.log("don't be evil"); -}); -``` - -Here any kind of unexpected error will automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`. - -Ok, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors? - -Bluebird defines a special error type `OperationalError` (you can get a reference from `Promise.OperationalError`). This type of error is given as rejection reason by promisified methods when -their underlying library gives an untyped, but expected error. Primitives such as strings, and error objects that are directly created like `new Error("database didn't respond")` are considered untyped. - -Example of such library is the node core library `fs`. So if we promisify it, we can catch just the errors we want pretty easily and have programmer errors be redirected to unhandled rejection handler so that we notice them: - -```js -//Read more about promisification in the API Reference: -//API.md -var fs = Promise.promisifyAll(require("fs")); - -fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) { - console.log("Successful json") -}).catch(SyntaxError, function (e) { - console.error("file contains invalid json"); -}).catch(Promise.OperationalError, function (e) { - console.error("unable to read file, because: ", e.message); -}); -``` - -The last `catch` handler is only invoked when the `fs` module explicitly used the `err` argument convention of async callbacks to inform of an expected error. The `OperationalError` instance will contain the original error in its `.cause` property but it does have a direct copy of the `.message` and `.stack` too. In this code any unexpected error - be it in our code or the `fs` module - would not be caught by these handlers and therefore not swallowed. - -Since a `catch` handler typed to `Promise.OperationalError` is expected to be used very often, it has a neat shorthand: - -```js -.error(function (e) { - console.error("unable to read file, because: ", e.message); -}); -``` - -See [API documentation for `.error()`](API.md#error-rejectedhandler----promise) - -Finally, Bluebird also supports predicate-based filters. If you pass a -predicate function instead of an error type, the predicate will receive -the error as an argument. The return result will be used to determine whether -the error handler should be called. - -Predicates should allow for very fine grained control over caught errors: -pattern matching, error typesets with set operations and many other techniques -can be implemented on top of them. - -Example of using a predicate-based filter: - -```js -var Promise = require("bluebird"); -var request = Promise.promisify(require("request")); - -function clientError(e) { - return e.code >= 400 && e.code < 500; -} - -request("http://www.google.com").then(function(contents){ - console.log(contents); -}).catch(clientError, function(e){ - //A client error like 400 Bad Request happened -}); -``` - -**Danger:** The JavaScript language allows throwing primitive values like strings. Throwing primitives can lead to worse or no stack traces. Primitives [are not exceptions](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/). You should consider always throwing Error objects when handling exceptions. - -
- -#### How do long stack traces differ from e.g. Q? - -Bluebird attempts to have more elaborate traces. Consider: - -```js -Error.stackTraceLimit = 25; -Q.longStackSupport = true; -Q().then(function outer() { - return Q().then(function inner() { - return Q().then(function evenMoreInner() { - a.b.c.d(); - }).catch(function catcher(e){ - console.error(e.stack); - }); - }) -}); -``` - -You will see - - ReferenceError: a is not defined - at evenMoreInner (:7:13) - From previous event: - at inner (:6:20) - -Compare to: - -```js -Error.stackTraceLimit = 25; -Promise.longStackTraces(); -Promise.resolve().then(function outer() { - return Promise.resolve().then(function inner() { - return Promise.resolve().then(function evenMoreInner() { - a.b.c.d() - }).catch(function catcher(e){ - console.error(e.stack); - }); - }); -}); -``` - - ReferenceError: a is not defined - at evenMoreInner (:7:13) - From previous event: - at inner (:6:36) - From previous event: - at outer (:5:32) - From previous event: - at :4:21 - at Object.InjectedScript._evaluateOn (:572:39) - at Object.InjectedScript._evaluateAndWrap (:531:52) - at Object.InjectedScript.evaluate (:450:21) - - -A better and more practical example of the differences can be seen in gorgikosev's [debuggability competition](https://github.com/spion/async-compare#debuggability). - -
- -# Development - -For development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies. - -Install [node](http://nodejs.org/) and [npm](https://npmjs.org/) - - git clone git@github.com:petkaantonov/bluebird.git - cd bluebird - npm install - -## Testing - -To run all tests, run - - node tools/test - -If you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+: - - node-dev --harmony tools/test - -You may specify an individual test file to run with the `--run` script flag: - - node tools/test --run=cancel.js - - -This enables output from the test and may give a better idea where the test is failing. The paramter to `--run` can be any file name located in `test/mocha` folder. - -#### Testing in browsers - -To run the test in a browser instead of node, pass the flag `--browser` to the test tool - - node tools/test --run=cancel.js --browser - -This will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled. - -Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active. - -#### Supported options by the test tool - -The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`. - - - `--run=String`. Which tests to run (or compile when testing in browser). Default `"all"`. Can also be a glob string (relative to ./test/mocha folder) - - `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `"html"` (use `--cover` to use default reporter). - - `--browser` - Whether to compile tests for browsers. Default `false`. - - `--port=Number` - Whe port where local server is hosted when testing in browser. Default `9999` - - `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`. - - `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`. - - `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`. - - `--js-hint` - Whether to run JSHint on source files. Default `true`. - - `--saucelabs` Wheter to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser.Default `false`. - -## Benchmarks - -To run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too). - -Node 0.11.2+ is required to run the generator examples. - -### 1\. DoxBee sequential - -Currently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections. - -Command: `bench doxbee` - -### 2\. Made-up parallel - -This made-up scenario runs 15 shimmed queries in parallel. - -Command: `bench parallel` - -## Custom builds - -Custom builds for browsers are supported through a command-line utility. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
The following features can be disabled
Feature(s)Command line identifier
.any and Promise.anyany
.race and Promise.racerace
.call and .getcall_get
.filter and Promise.filterfilter
.map and Promise.mapmap
.reduce and Promise.reducereduce
.props and Promise.propsprops
.settle and Promise.settlesettle
.some and Promise.somesome
.nodeifynodeify
Promise.coroutine and Promise.spawngenerators
Progressionprogress
Promisificationpromisify
Cancellationcancel
Timerstimers
Resource managementusing
- - -Make sure you have cloned the repo somewhere and did `npm install` successfully. - -After that you can run: - - node tools/build --features="core" - - -The above builds the most minimal build you can get. You can add more features separated by spaces from the above list: - - node tools/build --features="core filter map reduce" - -The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features. - -Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build -a full version afterwards (after having taken a copy of the bluebird.js somewhere): - - node tools/build --debug --main --zalgo --browser --minify - -#### Supported options by the build tool - -The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`. - - - `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`. - - `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`. - - `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`. - - `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`. - - `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`. - - `--features=String` - See [custom builds](#custom-builds) - -
- -## For library authors - -Building a library that depends on bluebird? You should know about a few features. - -If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file -that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains: - -```js - //NOTE the function call right after -module.exports = require("bluebird/js/main/promise")(); -``` - -Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic. - -You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API. - -
- -## What is the sync build? - -You may now use sync build by: - - var Promise = require("bluebird/zalgo"); - -The sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards. - -The normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility -of stack overflow errors and non-deterministic behavior. - -The sync build skips the async call trampoline completely, e.g code like: - - async.invoke( this.fn, this, val ); - -Appears as this in the sync build: - - this.fn(val); - -This should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism. - -Note that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads. - - -```js -var cache = new Map(); //ES6 Map or DataStructures/Map or whatever... -function getResult(url) { - var resolver = Promise.pending(); - if (cache.has(url)) { - resolver.resolve(cache.get(url)); - } - else { - http.get(url, function(err, content) { - if (err) resolver.reject(err); - else { - cache.set(url, content); - resolver.resolve(content); - } - }); - } - return resolver.promise; -} - - - -//The result of console.log is truly random without async guarantees -function guessWhatItPrints( url ) { - var i = 3; - getResult(url).then(function(){ - i = 4; - }); - console.log(i); -} -``` - -# Optimization guide - -Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome. - -A single cohesive guide compiled from the articles will probably be done eventually. +The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. # License The MIT License (MIT) -Copyright (c) 2014 Petka Antonov +Copyright (c) 2013-2015 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 diff --git a/node_modules/bluebird/changelog.md b/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..73b2eb6 --- /dev/null +++ b/node_modules/bluebird/changelog.md @@ -0,0 +1 @@ +[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html) diff --git a/node_modules/bluebird/js/browser/bluebird.js b/node_modules/bluebird/js/browser/bluebird.js index c42fe29..8c742cd 100644 --- a/node_modules/bluebird/js/browser/bluebird.js +++ b/node_modules/bluebird/js/browser/bluebird.js @@ -1,14 +1,14 @@ /* @preserve * The MIT License (MIT) * - * Copyright (c) 2014 Petka Antonov + * Copyright (c) 2013-2015 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:

+ * 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. @@ -23,8 +23,8 @@ * */ /** - * bluebird build version 2.9.24 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers + * bluebird build version 3.0.6 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0; + +Async.prototype.fatalError = function(e, isNode) { + if (isNode) { + process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e)); + process.exit(2); + } else { + this.throwLater(e); + } }; Async.prototype.throwLater = function(fn, arg) { @@ -94,8 +100,6 @@ Async.prototype.throwLater = function(fn, arg) { arg = fn; fn = function () { throw arg; }; } - var domain = this._getDomain(); - if (domain !== undefined) fn = domain.bind(fn); if (typeof setTimeout !== "undefined") { setTimeout(function() { fn(arg); @@ -105,75 +109,22 @@ Async.prototype.throwLater = function(fn, arg) { fn(arg); }); } catch (e) { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } }; -Async.prototype._getDomain = function() {}; - -if (util.isNode) { - var EventsModule = _dereq_("events"); - - var domainGetter = function() { - var domain = process.domain; - if (domain === null) return undefined; - return domain; - }; - - if (EventsModule.usingDomains) { - Async.prototype._getDomain = domainGetter; - } else { - var descriptor = - Object.getOwnPropertyDescriptor(EventsModule, "usingDomains"); - - if (!descriptor.configurable) { - process.on("domainsActivated", function() { - Async.prototype._getDomain = domainGetter; - }); - } else { - var usingDomains = false; - Object.defineProperty(EventsModule, "usingDomains", { - configurable: false, - enumerable: true, - get: function() { - return usingDomains; - }, - set: function(value) { - if (usingDomains || !value) return; - usingDomains = true; - Async.prototype._getDomain = domainGetter; - util.toFastProperties(process); - process.emit("domainsActivated"); - } - }); - } - - - } -} - function AsyncInvokeLater(fn, receiver, arg) { - var domain = this._getDomain(); - if (domain !== undefined) fn = domain.bind(fn); this._lateQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncInvoke(fn, receiver, arg) { - var domain = this._getDomain(); - if (domain !== undefined) fn = domain.bind(fn); this._normalQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncSettlePromises(promise) { - var domain = this._getDomain(); - if (domain !== undefined) { - var fn = domain.bind(promise._settlePromises); - this._normalQueue.push(fn, promise, undefined); - } else { - this._normalQueue._pushOne(promise); - } + this._normalQueue._pushOne(promise); this._queueTick(); } @@ -182,13 +133,18 @@ if (!util.hasDevTools) { Async.prototype.invoke = AsyncInvoke; Async.prototype.settlePromises = AsyncSettlePromises; } else { + if (schedule.isStatic) { + schedule = function(fn) { setTimeout(fn, 0); }; + } Async.prototype.invokeLater = function (fn, receiver, arg) { if (this._trampolineEnabled) { AsyncInvokeLater.call(this, fn, receiver, arg); } else { - setTimeout(function() { - fn.call(receiver, arg); - }, 100); + this._schedule(function() { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + }); } }; @@ -196,9 +152,9 @@ if (!util.hasDevTools) { if (this._trampolineEnabled) { AsyncInvoke.call(this, fn, receiver, arg); } else { - setTimeout(function() { + this._schedule(function() { fn.call(receiver, arg); - }, 0); + }); } }; @@ -206,16 +162,14 @@ if (!util.hasDevTools) { if (this._trampolineEnabled) { AsyncSettlePromises.call(this, promise); } else { - setTimeout(function() { + this._schedule(function() { promise._settlePromises(); - }, 0); + }); } }; } Async.prototype.invokeFirst = function (fn, receiver, arg) { - var domain = this._getDomain(); - if (domain !== undefined) fn = domain.bind(fn); this._normalQueue.unshift(fn, receiver, arg); this._queueTick(); }; @@ -236,6 +190,7 @@ Async.prototype._drainQueue = function(queue) { Async.prototype._drainQueues = function () { this._drainQueue(this._normalQueue); this._reset(); + this._haveDrainedQueues = true; this._drainQueue(this._lateQueue); }; @@ -250,12 +205,13 @@ Async.prototype._reset = function () { this._isTickUsed = false; }; -module.exports = new Async(); +module.exports = Async; module.exports.firstLineError = firstLineError; -},{"./queue.js":28,"./schedule.js":31,"./util.js":38,"events":39}],3:[function(_dereq_,module,exports){ +},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ "use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { +var calledBind = false; var rejectThis = function(_, e) { this._reject(e); }; @@ -266,8 +222,7 @@ var targetRejected = function(e, context) { }; var bindingResolved = function(thisArg, context) { - this._setBoundTo(thisArg); - if (this._isPending()) { + if (((this._bitField & 50397184) === 0)) { this._resolveCallback(context.target); } }; @@ -277,10 +232,16 @@ var bindingRejected = function(e, context) { }; Promise.prototype.bind = function (thisArg) { + if (!calledBind) { + calledBind = true; + Promise.prototype._propagateFrom = debug.propagateFromFunction(); + Promise.prototype._boundValue = debug.boundValueFunction(); + } var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); + ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, @@ -288,11 +249,11 @@ Promise.prototype.bind = function (thisArg) { target: target, bindingPromise: maybePromise }; - target._then(INTERNAL, targetRejected, ret._progress, ret, context); + target._then(INTERNAL, targetRejected, undefined, ret, context); maybePromise._then( - bindingResolved, bindingRejected, ret._progress, ret, context); + bindingResolved, bindingRejected, undefined, ret, context); + ret._setOnCancel(maybePromise); } else { - ret._setBoundTo(thisArg); ret._resolveCallback(target); } return ret; @@ -300,31 +261,19 @@ Promise.prototype.bind = function (thisArg) { Promise.prototype._setBoundTo = function (obj) { if (obj !== undefined) { - this._bitField = this._bitField | 131072; + this._bitField = this._bitField | 2097152; this._boundTo = obj; } else { - this._bitField = this._bitField & (~131072); + this._bitField = this._bitField & (~2097152); } }; Promise.prototype._isBound = function () { - return (this._bitField & 131072) === 131072; + return (this._bitField & 2097152) === 2097152; }; Promise.bind = function (thisArg, value) { - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - - if (maybePromise instanceof Promise) { - maybePromise._then(function(thisArg) { - ret._setBoundTo(thisArg); - ret._resolveCallback(value); - }, ret._reject, ret._progress, ret, null); - } else { - ret._setBoundTo(thisArg); - ret._resolveCallback(value); - } - return ret; + return Promise.resolve(value).bind(thisArg); }; }; @@ -337,11 +286,11 @@ function noConflict() { catch (e) {} return bluebird; } -var bluebird = _dereq_("./promise.js")(); +var bluebird = _dereq_("./promise")(); bluebird.noConflict = noConflict; module.exports = bluebird; -},{"./promise.js":23}],5:[function(_dereq_,module,exports){ +},{"./promise":22}],5:[function(_dereq_,module,exports){ "use strict"; var cr = Object.create; if (cr) { @@ -351,7 +300,7 @@ if (cr) { } module.exports = function(Promise) { -var util = _dereq_("./util.js"); +var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; @@ -427,7 +376,7 @@ function caller(obj) { return fn.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];} + var args = [].slice.call(arguments, 1);; if (!true) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); @@ -466,149 +415,556 @@ Promise.prototype.get = function (propertyName) { }; }; -},{"./util.js":38}],6:[function(_dereq_,module,exports){ +},{"./util":36}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray, apiRejection, debug) { +var util = _dereq_("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +Promise.prototype["break"] = Promise.prototype.cancel = function() { + if (!debug.cancellation()) return this._warn("cancellation is disabled"); + + var promise = this; + var child = promise; + while (promise.isCancellable()) { + if (!promise._cancelBy(child)) { + if (child._isFollowing()) { + child._followee().cancel(); + } else { + child._cancelBranched(); + } + break; + } + + var parent = promise._cancellationParent; + if (parent == null || !parent.isCancellable()) { + if (promise._isFollowing()) { + promise._followee().cancel(); + } else { + promise._cancelBranched(); + } + break; + } else { + if (promise._isFollowing()) promise._followee().cancel(); + child = promise; + promise = parent; + } + } +}; + +Promise.prototype._branchHasCancelled = function() { + this._branchesRemainingToCancel--; +}; + +Promise.prototype._enoughBranchesHaveCancelled = function() { + return this._branchesRemainingToCancel === undefined || + this._branchesRemainingToCancel <= 0; +}; + +Promise.prototype._cancelBy = function(canceller) { + if (canceller === this) { + this._branchesRemainingToCancel = 0; + this._invokeOnCancel(); + return true; + } else { + this._branchHasCancelled(); + if (this._enoughBranchesHaveCancelled()) { + this._invokeOnCancel(); + return true; + } + } + return false; +}; + +Promise.prototype._cancelBranched = function() { + if (this._enoughBranchesHaveCancelled()) { + this._cancel(); + } +}; + +Promise.prototype._cancel = function() { + if (!this.isCancellable()) return; + + this._setCancelled(); + async.invoke(this._cancelPromises, this, undefined); +}; + +Promise.prototype._cancelPromises = function() { + if (this._length() > 0) this._settlePromises(); +}; + +Promise.prototype._unsetOnCancel = function() { + this._onCancelField = undefined; +}; + +Promise.prototype.isCancellable = function() { + return this.isPending() && !this.isCancelled(); +}; + +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { + if (util.isArray(onCancelCallback)) { + for (var i = 0; i < onCancelCallback.length; ++i) { + this._doInvokeOnCancel(onCancelCallback[i], internalOnly); + } + } else if (onCancelCallback !== undefined) { + if (typeof onCancelCallback === "function") { + if (!internalOnly) { + var e = tryCatch(onCancelCallback).call(this._boundValue()); + if (e === errorObj) { + this._attachExtraTrace(e.e); + async.throwLater(e.e); + } + } + } else { + onCancelCallback._resultCancelled(this); + } + } +}; + +Promise.prototype._invokeOnCancel = function() { + var onCancelCallback = this._onCancel(); + this._unsetOnCancel(); + async.invoke(this._doInvokeOnCancel, this, onCancelCallback); +}; + +Promise.prototype._invokeInternalOnCancel = function() { + if (this.isCancellable()) { + this._doInvokeOnCancel(this._onCancel(), true); + this._unsetOnCancel(); + } +}; + +Promise.prototype._resultCancelled = function() { + this.cancel(); +}; + +}; + +},{"./util":36}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util"); +var getKeys = _dereq_("./es5").keys; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function catchFilter(instances, cb, promise) { + return function(e) { + var boundTo = promise._boundValue(); + predicateLoop: for (var i = 0; i < instances.length; ++i) { + var item = instances[i]; + + if (item === Error || + (item != null && item.prototype instanceof Error)) { + if (e instanceof item) { + return tryCatch(cb).call(boundTo, e); + } + } else if (typeof item === "function") { + var matchesPredicate = tryCatch(item).call(boundTo, e); + if (matchesPredicate === errorObj) { + return matchesPredicate; + } else if (matchesPredicate) { + return tryCatch(cb).call(boundTo, e); + } + } else if (util.isObject(e)) { + var keys = getKeys(item); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + if (item[key] != e[key]) { + continue predicateLoop; + } + } + return tryCatch(cb).call(boundTo, e); + } + } + return NEXT_FILTER; + }; +} + +return catchFilter; +}; + +},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { -var errors = _dereq_("./errors.js"); -var async = _dereq_("./async.js"); -var CancellationError = errors.CancellationError; +var longStackTraces = false; +var contextStack = []; -Promise.prototype._cancel = function (reason) { - if (!this.isCancellable()) return this; - var parent; - var promiseToReject = this; - while ((parent = promiseToReject._cancellationParent) !== undefined && - parent.isCancellable()) { - promiseToReject = parent; +Promise.prototype._promiseCreated = function() {}; +Promise.prototype._pushContext = function() {}; +Promise.prototype._popContext = function() {return null;}; +Promise._peekContext = Promise.prototype._peekContext = function() {}; + +function Context() { + this._trace = new Context.CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (this._trace !== undefined) { + this._trace._promiseCreated = null; + contextStack.push(this._trace); } - this._unsetCancellable(); - promiseToReject._target()._rejectCallback(reason, false, true); }; -Promise.prototype.cancel = function (reason) { - if (!this.isCancellable()) return this; - if (reason === undefined) reason = new CancellationError(); - async.invokeLater(this._cancel, this, reason); - return this; +Context.prototype._popContext = function () { + if (this._trace !== undefined) { + var trace = contextStack.pop(); + var ret = trace._promiseCreated; + trace._promiseCreated = null; + return ret; + } + return null; }; -Promise.prototype.cancellable = function () { - if (this._cancellable()) return this; - async.enableTrampoline(); - this._setCancellable(); - this._cancellationParent = undefined; - return this; +function createContext() { + if (longStackTraces) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} +Context.CapturedTrace = null; +Context.create = createContext; +Context.deactivateLongStackTraces = function() {}; +Context.activateLongStackTraces = function() { + var Promise_pushContext = Promise.prototype._pushContext; + var Promise_popContext = Promise.prototype._popContext; + var Promise_PeekContext = Promise._peekContext; + var Promise_peekContext = Promise.prototype._peekContext; + var Promise_promiseCreated = Promise.prototype._promiseCreated; + Context.deactivateLongStackTraces = function() { + Promise.prototype._pushContext = Promise_pushContext; + Promise.prototype._popContext = Promise_popContext; + Promise._peekContext = Promise_PeekContext; + Promise.prototype._peekContext = Promise_peekContext; + Promise.prototype._promiseCreated = Promise_promiseCreated; + longStackTraces = false; + }; + longStackTraces = true; + Promise.prototype._pushContext = Context.prototype._pushContext; + Promise.prototype._popContext = Context.prototype._popContext; + Promise._peekContext = Promise.prototype._peekContext = peekContext; + Promise.prototype._promiseCreated = function() { + var ctx = this._peekContext(); + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; + }; +}; +return Context; }; -Promise.prototype.uncancellable = function () { - var ret = this.then(); - 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; -}; -}; - -},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){ +},{}],9:[function(_dereq_,module,exports){ "use strict"; -module.exports = function() { -var async = _dereq_("./async.js"); -var util = _dereq_("./util.js"); +module.exports = function(Promise, Context) { +var getDomain = Promise._getDomain; +var async = Promise._async; +var Warning = _dereq_("./errors").Warning; +var util = _dereq_("./util"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; var stackFramePattern = null; var formatStack = null; var indentStackFrames = false; -var warn; +var printWarning; +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && + (true || + util.env("BLUEBIRD_DEBUG") || + util.env("NODE_ENV") === "development")); +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && + (debugging || util.env("BLUEBIRD_WARNINGS"))); +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); -function CapturedTrace(parent) { - this._parent = parent; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); +Promise.prototype.suppressUnhandledRejections = function() { + var target = this._target(); + target._bitField = ((target._bitField & (~1048576)) | + 2097152); +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 2097152) !== 0) return; + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._settledValue(); + this._setUnhandledRejectionIsNotified(); + fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 262144; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~262144); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 262144) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 1048576; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~1048576); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { + return warn(message, shouldUseOwnTrace, promise || this); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; +}; + +var disableLongStackTraces = function() {}; +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (!config.longStackTraces && longStackTracesIsSupported()) { + var Promise_captureStackTrace = Promise.prototype._captureStackTrace; + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + config.longStackTraces = true; + disableLongStackTraces = function() { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + Promise.prototype._captureStackTrace = Promise_captureStackTrace; + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Context.deactivateLongStackTraces(); + async.enableTrampoline(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Context.activateLongStackTraces(); + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + +Promise.config = function(opts) { + opts = Object(opts); + if ("longStackTraces" in opts) { + if (opts.longStackTraces) { + Promise.longStackTraces(); + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { + disableLongStackTraces(); + } + } + if ("warnings" in opts) { + config.warnings = !!opts.warnings; + } + if ("cancellation" in opts && opts.cancellation && !config.cancellation) { + if (async.haveItemsQueued()) { + throw new Error( + "cannot enable cancellation after promises are in use"); + } + Promise.prototype._clearCancellationData = + cancellationClearCancellationData; + Promise.prototype._propagateFrom = cancellationPropagateFrom; + Promise.prototype._onCancel = cancellationOnCancel; + Promise.prototype._setOnCancel = cancellationSetOnCancel; + Promise.prototype._attachCancellationCallback = + cancellationAttachCancellationCallback; + Promise.prototype._execute = cancellationExecute; + propagateFromFunction = cancellationPropagateFrom; + config.cancellation = true; + } +}; + +Promise.prototype._execute = function(executor, resolve, reject) { + try { + executor(resolve, reject); + } catch (e) { + return e; + } +}; +Promise.prototype._onCancel = function () {}; +Promise.prototype._setOnCancel = function (handler) { ; }; +Promise.prototype._attachCancellationCallback = function(onCancel) { + ; +}; +Promise.prototype._captureStackTrace = function () {}; +Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._clearCancellationData = function() {}; +Promise.prototype._propagateFrom = function (parent, flags) { + ; + ; +}; + +function cancellationExecute(executor, resolve, reject) { + var promise = this; + try { + executor(resolve, reject, function(onCancel) { + if (typeof onCancel !== "function") { + throw new TypeError("onCancel must be a function, got: " + + util.toString(onCancel)); + } + promise._attachCancellationCallback(onCancel); + }); + } catch (e) { + return e; + } } -util.inherits(CapturedTrace, Error); -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; +function cancellationAttachCancellationCallback(onCancel) { + if (!this.isCancellable()) return this; - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; + var previousOnCancel = this._onCancel(); + if (previousOnCancel !== undefined) { + if (util.isArray(previousOnCancel)) { + previousOnCancel.push(onCancel); + } else { + this._setOnCancel([previousOnCancel, onCancel]); } + } else { + this._setOnCancel(onCancel); } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; +} - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; +function cancellationOnCancel() { + return this._onCancelField; +} + +function cancellationSetOnCancel(onCancel) { + this._onCancelField = onCancel; +} + +function cancellationClearCancellationData() { + this._cancellationParent = undefined; + this._onCancelField = undefined; +} + +function cancellationPropagateFrom(parent, flags) { + if ((flags & 1) !== 0) { + this._cancellationParent = parent; + var branchesRemainingToCancel = parent._branchesRemainingToCancel; + if (branchesRemainingToCancel === undefined) { + branchesRemainingToCancel = 0; + } + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; + } + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} + +function bindingPropagateFrom(parent, flags) { + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +var propagateFromFunction = bindingPropagateFrom; + +function boundValueFunction() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; + return undefined; } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; } } -}; + return ret; +} -CapturedTrace.prototype.parent = function() { - return this._parent; -}; +function longStackTracesCaptureStackTrace() { + this._trace = new CapturedTrace(this._peekContext()); +} -CapturedTrace.prototype.hasParent = function() { - return this._parent !== undefined; -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = CapturedTrace.parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - stacks.push(cleanStack(trace.stack.split("\n"))); - trace = trace._parent; +function longStackTracesAttachExtraTrace(error, ignoreSelf) { + if (canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } } - removeCommonRoots(stacks); - removeDuplicateOrEmptyJumps(stacks); - util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); - util.notEnumerableProp(error, "__stackCleaned__", true); -}; +} + +function checkForgottenReturns(returnValue, promiseCreated, name, promise) { + if (returnValue === undefined && + promiseCreated !== null && + config.longStackTraces && + config.warnings) { + var msg = "a promise was created in a " + name + + " handler but was not returned from it"; + promise._warn(msg, true, promiseCreated); + } +} + +function deprecated(name, replacement) { + var message = name + + " is deprecated and will be removed in a future version."; + if (replacement) message += " Use " + replacement + " instead."; + return warn(message); +} + +function warn(message, shouldUseOwnTrace, promise) { + if (!config.warnings) return; + var warning = new Warning(message); + var ctx; + if (shouldUseOwnTrace) { + promise._attachExtraTrace(warning); + } else if (config.longStackTraces && (ctx = Promise._peekContext())) { + ctx.attachExtraTrace(warning); + } else { + var parsed = parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + formatAndLogError(warning, "", true); +} function reconstructStack(message, stacks) { for (var i = 0; i < stacks.length - 1; ++i) { @@ -663,8 +1019,8 @@ function cleanStack(stack) { var ret = []; for (var i = 0; i < stack.length; ++i) { var line = stack[i]; - var isTraceLine = stackFramePattern.test(line) || - " (No stack trace)" === line; + var isTraceLine = " (No stack trace)" === line || + stackFramePattern.test(line); var isInternalFrame = isTraceLine && shouldIgnore(line); if (isTraceLine && !isInternalFrame) { if (indentStackFrames && line.charAt(0) !== " ") { @@ -690,7 +1046,7 @@ function stackFramesAsArray(error) { return stack; } -CapturedTrace.parseStackAndMessage = function(error) { +function parseStackAndMessage(error) { var stack = error.stack; var message = error.toString(); stack = typeof stack === "string" && stack.length > 0 @@ -699,36 +1055,27 @@ CapturedTrace.parseStackAndMessage = function(error) { message: message, stack: cleanStack(stack) }; -}; +} -CapturedTrace.formatAndLogError = function(error, title) { +function formatAndLogError(error, title, isSoft) { if (typeof console !== "undefined") { var message; - if (typeof error === "object" || typeof error === "function") { + if (util.isObject(error)) { var stack = error.stack; message = title + formatStack(stack, error); } else { message = title + String(error); } - if (typeof warn === "function") { - warn(message); + if (typeof printWarning === "function") { + printWarning(message, isSoft); } 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.isSupported = function () { - return typeof captureStackTrace === "function"; -}; - -CapturedTrace.fireRejectionEvent = -function(name, localHandler, reason, promise) { +function fireRejectionEvent(name, localHandler, reason, promise) { var localEventFired = false; try { if (typeof localHandler === "function") { @@ -766,9 +1113,9 @@ function(name, localHandler, reason, promise) { if (!globalEventFired && !localEventFired && !domEventFired && name === "unhandledRejection") { - CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + formatAndLogError(reason, "Unhandled rejection "); } -}; +} function formatNonError(obj) { var str; @@ -777,7 +1124,8 @@ function formatNonError(obj) { (obj.name || "anonymous") + "]"; } else { - str = obj.toString(); + str = obj && typeof obj.toString === "function" + ? obj.toString() : util.toString(obj); var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; if (ruselessToString.test(str)) { try { @@ -803,6 +1151,10 @@ function snip(str) { return str.substr(0, maxChars - 3) + "..."; } +function longStackTracesIsSupported() { + return typeof captureStackTrace === "function"; +} + var shouldIgnore = function() { return false; }; var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; function parseLineInfo(line) { @@ -814,8 +1166,9 @@ function parseLineInfo(line) { }; } } -CapturedTrace.setBounds = function(firstLineError, lastLineError) { - if (!CapturedTrace.isSupported()) return; + +function setBounds(firstLineError, lastLineError) { + if (!longStackTracesIsSupported()) return; var firstStackLines = firstLineError.stack.split("\n"); var lastStackLines = lastLineError.stack.split("\n"); var firstIndex = -1; @@ -854,6 +1207,82 @@ CapturedTrace.setBounds = function(firstLineError, lastLineError) { } return false; }; +} + +function CapturedTrace(parent) { + this._parent = parent; + this._promisesCreated = 0; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); +Context.CapturedTrace = CapturedTrace; + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); }; var captureStackTrace = (function stackDetection() { @@ -870,7 +1299,7 @@ var captureStackTrace = (function stackDetection() { if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit = Error.stackTraceLimit + 6; + Error.stackTraceLimit += 6; stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; var captureStackTrace = Error.captureStackTrace; @@ -879,9 +1308,9 @@ var captureStackTrace = (function stackDetection() { return bluebirdFramePattern.test(line); }; return function(receiver, ignoreUntil) { - Error.stackTraceLimit = Error.stackTraceLimit + 6; + Error.stackTraceLimit += 6; captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit = Error.stackTraceLimit - 6; + Error.stackTraceLimit -= 6; }; } var err = new Error(); @@ -901,14 +1330,15 @@ var captureStackTrace = (function stackDetection() { catch(e) { hasStackAfterThrow = ("stack" in e); } - if (!("stack" in err) && hasStackAfterThrow) { + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { - Error.stackTraceLimit = Error.stackTraceLimit + 6; + Error.stackTraceLimit += 6; try { throw new Error(); } catch(e) { o.stack = e.stack; } - Error.stackTraceLimit = Error.stackTraceLimit - 6; + Error.stackTraceLimit -= 6; }; } @@ -993,355 +1423,138 @@ var fireGlobalEvent = (function() { })(); if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - warn = function (message) { + printWarning = function (message) { console.warn(message); }; if (util.isNode && process.stderr.isTTY) { - warn = function(message) { - process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + printWarning = function(message, isSoft) { + var color = isSoft ? "\u001b[33m" : "\u001b[31m"; + console.warn(color + message + "\u001b[0m\n"); }; } else if (!util.isNode && typeof (new Error().stack) === "string") { - warn = function(message) { - console.warn("%c" + message, "color: red"); + printWarning = function(message, isSoft) { + console.warn("%c" + message, + isSoft ? "color: darkorange" : "color: red"); }; } } -return CapturedTrace; +var config = { + warnings: warnings, + longStackTraces: false, + cancellation: false }; -},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){ +if (longStackTraces) Promise.longStackTraces(); + +return { + longStackTraces: function() { + return config.longStackTraces; + }, + warnings: function() { + return config.warnings; + }, + cancellation: function() { + return config.cancellation; + }, + propagateFromFunction: function() { + return propagateFromFunction; + }, + boundValueFunction: function() { + return boundValueFunction; + }, + checkForgottenReturns: checkForgottenReturns, + setBounds: setBounds, + warn: warn, + deprecated: deprecated, + CapturedTrace: CapturedTrace +}; +}; + +},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ "use strict"; -module.exports = function(NEXT_FILTER) { -var util = _dereq_("./util.js"); -var errors = _dereq_("./errors.js"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var keys = _dereq_("./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 = tryCatch(predicate).call(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 = tryCatch(cb).call(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) { - e = errorObj.e; - break; - } else if (shouldHandle) { - var ret = tryCatch(cb).call(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":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, CapturedTrace, isDebugging) { -var contextStack = []; -function Context() { - this._trace = new CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (!isDebugging()) return; - if (this._trace !== undefined) { - contextStack.push(this._trace); - } -}; - -Context.prototype._popContext = function () { - if (!isDebugging()) return; - if (this._trace !== undefined) { - contextStack.pop(); - } -}; - -function createContext() { - if (isDebugging()) return new Context(); -} - -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; -} - -Promise.prototype._peekContext = peekContext; -Promise.prototype._pushContext = Context.prototype._pushContext; -Promise.prototype._popContext = Context.prototype._popContext; - -return createContext; -}; - -},{}],10:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, CapturedTrace) { -var async = _dereq_("./async.js"); -var Warning = _dereq_("./errors.js").Warning; -var util = _dereq_("./util.js"); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var debugging = false || (util.isNode && - (!!process.env["BLUEBIRD_DEBUG"] || - process.env["NODE_ENV"] === "development")); - -if (debugging) { - async.disableTrampolineIfNecessary(); -} - -Promise.prototype._ensurePossibleRejectionHandled = function () { - this._setRejectionIsUnhandled(); - async.invokeLater(this._notifyUnhandledRejection, this, undefined); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - CapturedTrace.fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._getCarriedStackTrace() || this._settledValue; - this._setUnhandledRejectionIsNotified(); - CapturedTrace.fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; - -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._setRejectionIsUnhandled = function () { - 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._setCarriedStackTrace = function (capturedTrace) { - this._bitField = this._bitField | 1048576; - this._fulfillmentHandler0 = capturedTrace; -}; - -Promise.prototype._isCarryingStackTrace = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._getCarriedStackTrace = function () { - return this._isCarryingStackTrace() - ? this._fulfillmentHandler0 - : undefined; -}; - -Promise.prototype._captureStackTrace = function () { - if (debugging) { - this._trace = new CapturedTrace(this._peekContext()); - } - return this; -}; - -Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { - if (debugging && canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - trace.attachExtraTrace(error); - } else if (!error.__stackCleaned__) { - var parsed = CapturedTrace.parseStackAndMessage(error); - util.notEnumerableProp(error, "stack", - parsed.message + "\n" + parsed.stack.join("\n")); - util.notEnumerableProp(error, "__stackCleaned__", true); - } - } -}; - -Promise.prototype._warn = function(message) { - var warning = new Warning(message); - var ctx = this._peekContext(); - if (ctx) { - ctx.attachExtraTrace(warning); - } else { - var parsed = CapturedTrace.parseStackAndMessage(warning); - warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); - } - CapturedTrace.formatAndLogError(warning, ""); -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - 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(); - if (debugging) { - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return debugging && CapturedTrace.isSupported(); -}; - -if (!CapturedTrace.isSupported()) { - Promise.longStackTraces = function(){}; - debugging = false; -} - -return function() { - return debugging; -}; -}; - -},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util.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; - }; - } -}; - +function returner() { + return this.value; +} +function thrower() { + throw this.reason; +} 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); + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + returner, undefined, undefined, {value: value}, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { - if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + return this._then( + thrower, undefined, undefined, {reason: reason}, undefined); +}; + +Promise.prototype.catchThrow = function (reason) { + if (arguments.length <= 1) { return this._then( - wrapper(reason, 1), - undefined, - undefined, - undefined, - undefined - ); + undefined, thrower, undefined, {reason: reason}, undefined); + } else { + var _reason = arguments[1]; + var handler = function() {throw _reason;}; + return this.caught(reason, handler); + } +}; + +Promise.prototype.catchReturn = function (value) { + if (arguments.length <= 1) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + undefined, returner, undefined, {value: value}, undefined); + } else { + var _value = arguments[1]; + if (_value instanceof Promise) _value.suppressUnhandledRejections(); + var handler = function() {return _value;}; + return this.caught(value, handler); } - return this._then(thrower, undefined, undefined, reason, undefined); }; }; -},{"./util.js":38}],12:[function(_dereq_,module,exports){ +},{}],11:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; +var PromiseAll = Promise.all; + +function promiseAllThis() { + return PromiseAll(this); +} + +function PromiseMapSeries(promises, fn) { + return PromiseReduce(promises, fn, INTERNAL, INTERNAL); +} Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, null, INTERNAL); + return this.mapSeries(fn) + ._then(promiseAllThis, undefined, undefined, this, undefined); +}; + +Promise.prototype.mapSeries = function (fn) { + return PromiseReduce(this, fn, INTERNAL, INTERNAL); }; Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, null, INTERNAL); -}; + return PromiseMapSeries(promises, fn) + ._then(promiseAllThis, undefined, undefined, promises, undefined); }; -},{}],13:[function(_dereq_,module,exports){ +Promise.mapSeries = PromiseMapSeries; +}; + +},{}],12:[function(_dereq_,module,exports){ "use strict"; -var es5 = _dereq_("./es5.js"); +var es5 = _dereq_("./es5"); var Objectfreeze = es5.freeze; -var util = _dereq_("./util.js"); +var util = _dereq_("./util"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; @@ -1450,7 +1663,7 @@ module.exports = { Warning: Warning }; -},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){ +},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; return this === undefined; @@ -1532,7 +1745,7 @@ if (isES5) { }; } -},{}],15:[function(_dereq_,module,exports){ +},{}],14:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseMap = Promise.map; @@ -1546,116 +1759,119 @@ Promise.filter = function (promises, fn, options) { }; }; -},{}],16:[function(_dereq_,module,exports){ +},{}],15:[function(_dereq_,module,exports){ "use strict"; -module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { -var util = _dereq_("./util.js"); -var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; -var isPrimitive = util.isPrimitive; -var thrower = util.thrower; +module.exports = function(Promise, tryConvertToPromise) { +var util = _dereq_("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; -function returnThis() { - return this; +function FinallyHandlerCancelReaction(finallyHandler) { + this.finallyHandler = finallyHandler; } -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; + +FinallyHandlerCancelReaction.prototype._resultCancelled = function() { + checkCancel(this.finallyHandler); +}; + +function checkCancel(ctx, reason) { + if (ctx.cancelPromise != null) { + if (arguments.length > 1) { + ctx.cancelPromise._reject(reason); + } else { + ctx.cancelPromise._cancel(); + } + ctx.cancelPromise = null; + return true; } - return ret._then(then, thrower, undefined, reasonOrValue, undefined); + return false; } +function succeed() { + return finallyHandler.call(this, this.promise._target()._settledValue()); +} +function fail(reason) { + if (checkCancel(this, reason)) return; + errorObj.e = reason; + return errorObj; +} 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, promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - return promisedFinally(maybePromise, reasonOrValue, - promise.isFulfilled()); + if (!this.called) { + this.called = true; + var ret = this.type === 0 + ? handler.call(promise._boundValue()) + : handler.call(promise._boundValue(), reasonOrValue); + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + if (this.cancelPromise != null) { + if (maybePromise.isCancelled()) { + var reason = + new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + errorObj.e = reason; + return errorObj; + } else if (maybePromise.isPending()) { + maybePromise._attachCancellationCallback( + new FinallyHandlerCancelReaction(this)); + } + } + return maybePromise._then( + succeed, fail, undefined, this, undefined); + } } } if (promise.isRejected()) { - NEXT_FILTER.e = reasonOrValue; - return NEXT_FILTER; + checkCancel(this); + errorObj.e = reasonOrValue; + return errorObj; } else { + checkCancel(this); 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, promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - return promisedFinally(maybePromise, value, true); - } - } - return value; -} - -Promise.prototype._passThroughHandler = function (handler, isFinally) { +Promise.prototype._passThrough = function(handler, type, success, fail) { if (typeof handler !== "function") return this.then(); - - var promiseAndHandler = { + return this._then(success, fail, undefined, { promise: this, - handler: handler - }; - - return this._then( - isFinally ? finallyHandler : tapHandler, - isFinally ? finallyHandler : undefined, undefined, - promiseAndHandler, undefined); + handler: handler, + called: false, + cancelPromise: null, + type: type + }, undefined); }; Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { - return this._passThroughHandler(handler, true); + return this._passThrough(handler, + 0, + finallyHandler, + finallyHandler); }; Promise.prototype.tap = function (handler) { - return this._passThroughHandler(handler, false); -}; + return this._passThrough(handler, 1, finallyHandler); }; -},{"./util.js":38}],17:[function(_dereq_,module,exports){ +return finallyHandler; +}; + +},{"./util":36}],16:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, apiRejection, INTERNAL, - tryConvertToPromise) { -var errors = _dereq_("./errors.js"); + tryConvertToPromise, + Proxyable, + debug) { +var errors = _dereq_("./errors"); var TypeError = errors.TypeError; -var util = _dereq_("./util.js"); +var util = _dereq_("./util"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var yieldHandlers = []; @@ -1680,6 +1896,7 @@ function promiseFromYieldHandler(value, yieldHandlers, traceParent) { function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { var promise = this._promise = new Promise(INTERNAL); promise._captureStackTrace(); + promise._setOnCancel(this); this._stack = stack; this._generatorFunction = generatorFunction; this._receiver = receiver; @@ -1687,7 +1904,75 @@ function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; + this._yieldedPromise = null; } +util.inherits(PromiseSpawn, Proxyable); + +PromiseSpawn.prototype._isResolved = function() { + return this.promise === null; +}; + +PromiseSpawn.prototype._cleanup = function() { + this._promise = this._generator = null; +}; + +PromiseSpawn.prototype._promiseCancelled = function() { + if (this._isResolved()) return; + var implementsReturn = typeof this._generator["return"] !== "undefined"; + + var result; + if (!implementsReturn) { + var reason = new Promise.CancellationError( + "generator .return() sentinel"); + Promise.coroutine.returnSentinel = reason; + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + result = tryCatch(this._generator["throw"]).call(this._generator, + reason); + this._promise._popContext(); + if (result === errorObj && result.e === reason) { + result = null; + } + } else { + this._promise._pushContext(); + result = tryCatch(this._generator["return"]).call(this._generator, + undefined); + this._promise._popContext(); + } + var promise = this._promise; + this._cleanup(); + if (result === errorObj) { + promise._rejectCallback(result.e, false); + } else { + promise.cancel(); + } +}; + +PromiseSpawn.prototype._promiseFulfilled = function(value) { + this._yieldedPromise = null; + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._promiseRejected = function(reason) { + this._yieldedPromise = null; + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._resultCancelled = function() { + if (this._yieldedPromise instanceof Promise) { + var promise = this._yieldedPromise; + this._yieldedPromise = null; + promise.cancel(); + } +}; PromiseSpawn.prototype.promise = function () { return this._promise; @@ -1697,17 +1982,20 @@ PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; - this._next(undefined); + this._promiseFulfilled(undefined); }; PromiseSpawn.prototype._continue = function (result) { + var promise = this._promise; if (result === errorObj) { - return this._promise._rejectCallback(result.e, false, true); + this._cleanup(); + return promise._rejectCallback(result.e, false); } var value = result.value; if (result.done === true) { - this._promise._resolveCallback(value); + this._cleanup(); + return promise._resolveCallback(value); } else { var maybePromise = tryConvertToPromise(value, this._promise); if (!(maybePromise instanceof Promise)) { @@ -1716,9 +2004,9 @@ PromiseSpawn.prototype._continue = function (result) { this._yieldHandlers, this._promise); if (maybePromise === null) { - this._throw( + this._promiseRejected( new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) @@ -1726,35 +2014,25 @@ PromiseSpawn.prototype._continue = function (result) { return; } } - maybePromise._then( - this._next, - this._throw, - undefined, - this, - null - ); + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + this._yieldedPromise = maybePromise; + maybePromise._proxy(this, null); + } else if (((bitField & 33554432) !== 0)) { + this._promiseFulfilled(maybePromise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._promiseRejected(maybePromise._reason()); + } else { + this._promiseCancelled(); + } } }; -PromiseSpawn.prototype._throw = function (reason) { - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._next = function (value) { - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); -}; - 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"); + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var yieldHandler = Object(options).yieldHandler; var PromiseSpawn$ = PromiseSpawn; @@ -1763,20 +2041,24 @@ Promise.coroutine = function (generatorFunction, options) { var generator = generatorFunction.apply(this, arguments); var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); + var ret = spawn.promise(); spawn._generator = generator; - spawn._next(undefined); - return spawn.promise(); + spawn._promiseFulfilled(undefined); + return ret; }; }; 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"); + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { + debug.deprecated("Promise.spawn()", "Promise.coroutine()"); if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); @@ -1785,11 +2067,11 @@ Promise.spawn = function (generatorFunction) { }; }; -},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){ +},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { -var util = _dereq_("./util.js"); +var util = _dereq_("./util"); var canEvaluate = util.canEvaluate; var tryCatch = util.tryCatch; var errorObj = util.errorObj; @@ -1805,54 +2087,85 @@ if (canEvaluate) { ".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\ + var promiseSetter = function(i) { + return new Function("promise", "holder", " \n\ 'use strict'; \n\ - var callback = holder.fn; \n\ - return callback(values); \n\ - ".replace(/values/g, values.join(", "))); + holder.pIndex = promise; \n\ + ".replace(/Index/g, i)); }; + + var generateHolderClass = function(total) { + var props = new Array(total); + for (var i = 0; i < props.length; ++i) { + props[i] = "this.p" + (i+1); + } + var assignment = props.join(" = ") + " = null;"; + var cancellationCode= "var promise;\n" + props.map(function(prop) { + return " \n\ + promise = " + prop + "; \n\ + if (promise instanceof Promise) { \n\ + promise.cancel(); \n\ + } \n\ + "; + }).join("\n"); + var passedArguments = props.join(", "); + var name = "Holder$" + total; + + + var code = "return function(tryCatch, errorObj, Promise) { \n\ + 'use strict'; \n\ + function [TheName](fn) { \n\ + [TheProperties] \n\ + this.fn = fn; \n\ + this.now = 0; \n\ + } \n\ + [TheName].prototype.checkFulfillment = function(promise) { \n\ + var now = ++this.now; \n\ + if (now === [TheTotal]) { \n\ + promise._pushContext(); \n\ + var callback = this.fn; \n\ + var ret = tryCatch(callback)([ThePassedArguments]); \n\ + promise._popContext(); \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(ret.e, false); \n\ + } else { \n\ + promise._resolveCallback(ret); \n\ + } \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype._resultCancelled = function() { \n\ + [CancellationCode] \n\ + }; \n\ + \n\ + return [TheName]; \n\ + }(tryCatch, errorObj, Promise); \n\ + "; + + code = code.replace(/\[TheName\]/g, name) + .replace(/\[TheTotal\]/g, total) + .replace(/\[ThePassedArguments\]/g, passedArguments) + .replace(/\[TheProperties\]/g, assignment) + .replace(/\[CancellationCode\]/g, cancellationCode); + + return new Function("tryCatch", "errorObj", "Promise", code) + (tryCatch, errorObj, Promise); + }; + + var holderClasses = []; var thenCallbacks = []; - var callers = [undefined]; - for (var i = 1; i <= 5; ++i) { - thenCallbacks.push(thenCallback(i)); - callers.push(caller(i)); + var promiseSetters = []; + + for (var i = 0; i < 8; ++i) { + holderClasses.push(generateHolderClass(i + 1)); + thenCallbacks.push(thenCallback(i + 1)); + promiseSetters.push(promiseSetter(i + 1)); } - 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]; - promise._pushContext(); - var ret = tryCatch(handler)(this); - promise._popContext(); - if (ret === errorObj) { - promise._rejectCallback(ret.e, false, true); - } else { - promise._resolveCallback(ret); - } - } else { - this.now = now; - } - }; - - var reject = function (reason) { + reject = function (reason) { this._reject(reason); }; -} -} +}} Promise.join = function () { var last = arguments.length - 1; @@ -1860,33 +2173,44 @@ Promise.join = function () { if (last > 0 && typeof arguments[last] === "function") { fn = arguments[last]; if (!true) { - if (last < 6 && canEvaluate) { + if (last <= 8 && canEvaluate) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); - var holder = new Holder(last, fn); + var HolderClass = holderClasses[last - 1]; + var holder = new HolderClass(fn); var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); - if (maybePromise._isPending()) { + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { maybePromise._then(callbacks[i], reject, undefined, ret, holder); - } else if (maybePromise._isFulfilled()) { + promiseSetters[i](maybePromise, holder); + } else if (((bitField & 33554432) !== 0)) { callbacks[i].call(ret, maybePromise._value(), holder); - } else { + } else if (((bitField & 16777216) !== 0)) { ret._reject(maybePromise._reason()); + } else { + ret._cancel(); } } else { callbacks[i].call(ret, maybePromise, holder); } } + if (!ret._isFateSealed()) { + ret._setAsyncGuaranteed(); + ret._setOnCancel(holder); + } return ret; } } } - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + var args = [].slice.call(arguments);; if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; @@ -1894,34 +2218,34 @@ Promise.join = function () { }; -},{"./util.js":38}],19:[function(_dereq_,module,exports){ +},{"./util":36}],18:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, - INTERNAL) { -var async = _dereq_("./async.js"); -var util = _dereq_("./util.js"); + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; -var PENDING = {}; var EMPTY_ARRAY = []; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); - this._callback = fn; + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = limit >= 1 ? [] : EMPTY_ARRAY; - async.invoke(init, this, undefined); + this._init$(undefined, -2); } util.inherits(MappingPromiseArray, PromiseArray); -function init() {this._init$(undefined, -2);} MappingPromiseArray.prototype._init = function () {}; @@ -1930,39 +2254,58 @@ MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; - if (values[index] === PENDING) { + + if (index < 0) { + index = (index * -1) - 1; values[index] = value; if (limit >= 1) { this._inFlight--; this._drainQueue(); - if (this._isResolved()) return; + if (this._isResolved()) return true; } } else { if (limit >= 1 && this._inFlight >= limit) { values[index] = value; this._queue.push(index); - return; + return false; } if (preservedValues !== null) preservedValues[index] = value; + var promise = this._promise; var callback = this._callback; - var receiver = this._promise._boundTo; - this._promise._pushContext(); + var receiver = promise._boundValue(); + promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); - this._promise._popContext(); - if (ret === errorObj) return this._reject(ret.e); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promiseCreated, + preservedValues !== null ? "Promise.filter" : "Promise.map", + promise + ); + if (ret === errorObj) { + this._reject(ret.e); + return true; + } var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); - if (maybePromise._isPending()) { + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { if (limit >= 1) this._inFlight++; - values[index] = PENDING; - return maybePromise._proxyPromiseArray(this, index); - } else if (maybePromise._isFulfilled()) { + values[index] = maybePromise; + maybePromise._proxy(this, (index + 1) * -1); + return false; + } else if (((bitField & 33554432) !== 0)) { ret = maybePromise._value(); + } else if (((bitField & 16777216) !== 0)) { + this._reject(maybePromise._reason()); + return true; } else { - return this._reject(maybePromise._reason()); + this._cancel(); + return true; } } values[index] = ret; @@ -1974,8 +2317,9 @@ MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { } else { this._resolve(values); } - + return true; } + return false; }; MappingPromiseArray.prototype._drainQueue = function () { @@ -2005,1067 +2349,92 @@ MappingPromiseArray.prototype.preservedValues = function () { }; function map(promises, fn, options, _filter) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } 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); + return new MappingPromiseArray(promises, fn, limit, _filter).promise(); } 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(); + return map(this, fn, options, null); }; 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(); + return map(promises, fn, options, _filter); }; }; -},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){ +},{"./util":36}],19:[function(_dereq_,module,exports){ "use strict"; module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util.js"); +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { +var util = _dereq_("./util"); var tryCatch = util.tryCatch; Promise.method = function (fn) { if (typeof fn !== "function") { - throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); } return function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); - ret._popContext(); + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.method", ret); ret._resolveFromSyncValue(value); return ret; }; }; -Promise.attempt = Promise["try"] = function (fn, args, ctx) { +Promise.attempt = Promise["try"] = function (fn) { if (typeof fn !== "function") { - return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + return apiRejection("expecting a function but got " + util.classString(fn)); } var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); - var value = util.isArray(args) - ? tryCatch(fn).apply(ctx, args) - : tryCatch(fn).call(ctx, args); - ret._popContext(); + var value; + if (arguments.length > 1) { + debug.deprecated("calling Promise.try with more than 1 argument"); + var arg = arguments[1]; + var ctx = arguments[2]; + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) + : tryCatch(fn).call(ctx, arg); + } else { + value = tryCatch(fn)(); + } + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.try", ret); ret._resolveFromSyncValue(value); return ret; }; Promise.prototype._resolveFromSyncValue = function (value) { if (value === util.errorObj) { - this._rejectCallback(value.e, false, true); + this._rejectCallback(value.e, false); } else { this._resolveCallback(value, true); } }; }; -},{"./util.js":38}],21:[function(_dereq_,module,exports){ +},{"./util":36}],20:[function(_dereq_,module,exports){ "use strict"; -module.exports = function(Promise) { -var util = _dereq_("./util.js"); -var async = _dereq_("./async.js"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundTo; - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} -function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var target = promise._target(); - var newReason = target._getCarriedStackTrace(); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundTo, reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -Promise.prototype.asCallback = -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, - this, - nodeback - ); - } - return this; -}; -}; - -},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, PromiseArray) { -var util = _dereq_("./util.js"); -var async = _dereq_("./async.js"); -var tryCatch = util.tryCatch; -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._target()._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; - - var ret = tryCatch(handler).call(receiver, progressValue); - if (ret === errorObj) { - if (ret.e != null && - ret.e.name !== "StopProgressPropagation") { - var trace = util.canAttachTrace(ret.e) - ? ret.e : new Error(util.toString(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) { - 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 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); - } - } -}; -}; - -},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){ -"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._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -var util = _dereq_("./util.js"); -var async = _dereq_("./async.js"); -var errors = _dereq_("./errors.js"); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {e: null}; -var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL); -var PromiseArray = - _dereq_("./promise_array.js")(Promise, INTERNAL, - tryConvertToPromise, apiRejection); -var CapturedTrace = _dereq_("./captured_trace.js")(); -var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace); - /*jshint unused:false*/ -var createContext = - _dereq_("./context.js")(Promise, CapturedTrace, isDebugging); -var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER); -var PromiseResolver = _dereq_("./promise_resolver.js"); -var nodebackForPromise = PromiseResolver._nodebackForPromise; -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -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; - if (resolver !== INTERNAL) this._resolveFromResolver(resolver); -} - -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 { - return Promise.reject( - new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); - } - } - catchInstances.length = j; - fn = arguments[i]; - 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) { - if (isDebugging() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - 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.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - return new PromiseArray(this).promise(); -}; - -Promise.prototype.error = function (fn) { - return this.caught(util.originatesFromRejection, fn); -}; - -Promise.is = function (val) { - return val instanceof Promise; -}; - -Promise.fromNode = function(fn) { - var ret = new Promise(INTERNAL); - var result = tryCatch(fn)(nodebackForPromise(ret)); - if (result === errorObj) { - ret._rejectCallback(result.e, true, true); - } - return ret; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.defer = Promise.pending = function () { - var promise = new Promise(INTERNAL); - return new PromiseResolver(promise); -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - var val = ret; - ret = new Promise(INTERNAL); - ret._fulfillUnchecked(val); - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - var prev = async._schedule; - async._schedule = fn; - return prev; -}; - -Promise.prototype._then = function ( - didFulfill, - didReject, - didProgress, - receiver, - internalData -) { - var haveInternalData = internalData !== undefined; - var ret = haveInternalData ? internalData : new Promise(INTERNAL); - - if (!haveInternalData) { - ret._propagateFrom(this, 4 | 1); - ret._captureStackTrace(); - } - - var target = this._target(); - if (target !== this) { - if (receiver === undefined) receiver = this._boundTo; - if (!haveInternalData) ret._setIsMigrated(); - } - - var callbackIndex = - target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); - - if (target._isResolved() && !target._isSettlePromisesQueued()) { - async.invoke( - target._settlePromiseAtPostResolution, target, callbackIndex); - } - - return ret; -}; - -Promise.prototype._settlePromiseAtPostResolution = function (index) { - if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); - this._settlePromiseAt(index); -}; - -Promise.prototype._length = function () { - return this._bitField & 131071; -}; - -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 & -131072) | - (len & 131071); -}; - -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._setIsMigrated = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._unsetIsMigrated = function () { - this._bitField = this._bitField & (~4194304); -}; - -Promise.prototype._isMigrated = function () { - return (this._bitField & 4194304) > 0; -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 - ? this._receiver0 - : this[ - index * 5 - 5 + 4]; - if (ret === undefined && this._isBound()) { - return this._boundTo; - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return index === 0 - ? this._promise0 - : this[index * 5 - 5 + 3]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - return index === 0 - ? this._fulfillmentHandler0 - : this[index * 5 - 5 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return index === 0 - ? this._rejectionHandler0 - : this[index * 5 - 5 + 1]; -}; - -Promise.prototype._migrateCallbacks = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var progress = follower._progressHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (promise instanceof Promise) promise._setIsMigrated(); - this._addCallbacks(fulfill, reject, progress, promise, receiver); -}; - -Promise.prototype._addCallbacks = function ( - fulfill, - reject, - progress, - promise, - receiver -) { - var index = this._length(); - - if (index >= 131071 - 5) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - 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 { - 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 >= 131071 - 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) { - this._setProxyHandlers(promiseArray, index); -}; - -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (this._isFollowingOrFulfilledOrRejected()) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false, true); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - var propagationFlags = 1 | (shouldBind ? 4 : 0); - this._propagateFrom(maybePromise, propagationFlags); - var promise = maybePromise._target(); - if (promise._isPending()) { - var len = this._length(); - for (var i = 0; i < len; ++i) { - promise._migrateCallbacks(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if (promise._isFulfilled()) { - this._fulfillUnchecked(promise._value()); - } else { - this._rejectUnchecked(promise._reason(), - promise._getCarriedStackTrace()); - } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { - if (!shouldNotMarkOriginatingFromRejection) { - util.markAsOriginatingFromRejection(reason); - } - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason, hasStack ? undefined : trace); -}; - -Promise.prototype._resolveFromResolver = function (resolver) { - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = tryCatch(resolver)(function(value) { - if (promise === null) return; - promise._resolveCallback(value); - promise = null; - }, function (reason) { - if (promise === null) return; - promise._rejectCallback(reason, synchronous); - promise = null; - }); - synchronous = false; - this._popContext(); - - if (r !== undefined && r === errorObj && promise !== null) { - promise._rejectCallback(r.e, true, true); - promise = null; - } -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - if (promise._isRejected()) return; - promise._pushContext(); - var x; - if (receiver === APPLY && !this._isRejected()) { - x = tryCatch(handler).apply(this._boundTo, value); - } else { - x = tryCatch(handler).call(receiver, value); - } - promise._popContext(); - - if (x === errorObj || x === promise || x === NEXT_FILTER) { - var err = x === promise ? makeSelfResolutionError() : x.e; - promise._rejectCallback(err, false, true); - } else { - promise._resolveCallback(x); - } -}; - -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; - -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; - -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; - -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 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -}; - -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 promise = this._promiseAt(index); - var isPromise = promise instanceof Promise; - - if (isPromise && promise._isMigrated()) { - promise._unsetIsMigrated(); - return async.invoke(this._settlePromiseAt, this, index); - } - var handler = this._isFulfilled() - ? this._fulfillmentHandlerAt(index) - : this._rejectionHandlerAt(index); - - var carriedStackTrace = - this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; - var value = this._settledValue; - var receiver = this._receiverAt(index); - - - this._clearCallbackDataAtIndex(index); - - if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof PromiseArray) { - if (!receiver._isResolved()) { - if (this._isFulfilled()) { - receiver._promiseFulfilled(value, promise); - } - else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (this._isFulfilled()) { - promise._fulfill(value); - } else { - promise._reject(value, carriedStackTrace); - } - } - - if (index >= 4 && (index & 31) === 4) - async.invokeLater(this._setLength, this, 0); -}; - -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._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() { - async.settlePromises(this); - this._setSettlePromisesQueued(); -}; - -Promise.prototype._fulfillUnchecked = function (value) { - 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 = util.ensureErrorObject(reason); - this._rejectUnchecked(reason, trace === reason ? undefined : trace); -}; - -Promise.prototype._rejectUnchecked = function (reason, trace) { - if (reason === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._rejectUnchecked(err); - } - this._setRejected(); - this._settledValue = reason; - this._cleanValues(); - - if (this._isFinal()) { - async.throwLater(function(e) { - if ("stack" in e) { - async.invokeFirst( - CapturedTrace.unhandledRejection, undefined, e); - } - throw e; - }, trace === undefined ? reason : trace); - return; - } - - if (trace !== undefined && trace !== reason) { - this._setCarriedStackTrace(trace); - } - - if (this._length() > 0) { - this._queueSettlePromises(); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._settlePromises = function () { - this._unsetSettlePromisesQueued(); - var len = this._length(); - for (var i = 0; i < len; i++) { - this._settlePromiseAt(i); - } -}; - -Promise._makeSelfResolutionError = makeSelfResolutionError; -_dereq_("./progress.js")(Promise, PromiseArray); -_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); -_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise); -_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); -_dereq_("./direct_resolve.js")(Promise); -_dereq_("./synchronous_inspection.js")(Promise); -_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); -Promise.Promise = Promise; -_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); -_dereq_('./cancel.js')(Promise); -_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); -_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); -_dereq_('./nodeify.js')(Promise); -_dereq_('./call_get.js')(Promise); -_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); -_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); -_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); -_dereq_('./settle.js')(Promise, PromiseArray); -_dereq_('./some.js')(Promise, PromiseArray, apiRejection); -_dereq_('./promisify.js')(Promise, INTERNAL); -_dereq_('./any.js')(Promise); -_dereq_('./each.js')(Promise, INTERNAL); -_dereq_('./timers.js')(Promise, INTERNAL); -_dereq_('./filter.js')(Promise, INTERNAL); - - util.toFastProperties(Promise); - util.toFastProperties(Promise.prototype); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._progressHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - p._settledValue = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - CapturedTrace.setBounds(async.firstLineError, util.lastLineError); - return Promise; - -}; - -},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection) { -var util = _dereq_("./util.js"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - var parent; - if (values instanceof Promise) { - parent = values; - promise._propagateFrom(parent, 1 | 4); - } - 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, this._promise); - if (values instanceof Promise) { - values = values._target(); - this._values = values; - if (values._isFulfilled()) { - values = values._value(); - 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()) { - values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - return; - } else { - this._reject(values._reason()); - return; - } - } else if (!isArray(values)) { - this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); - 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) { - var isResolved = this._isResolved(); - var maybePromise = tryConvertToPromise(values[i], promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - if (isResolved) { - maybePromise._unsetRejectionIsUnhandled(); - } else if (maybePromise._isPending()) { - maybePromise._proxyPromiseArray(this, i); - } else if (maybePromise._isFulfilled()) { - this._promiseFulfilled(maybePromise._value(), i); - } else { - this._promiseRejected(maybePromise._reason(), i); - } - } else if (!isResolved) { - this._promiseFulfilled(maybePromise, i); - } - } -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype.__hardReject__ = -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false, true); -}; - -PromiseArray.prototype._promiseProgressed = function (progressValue, index) { - this._promise._progress({ - index: index, - value: progressValue - }); -}; - - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - } -}; - -PromiseArray.prototype._promiseRejected = function (reason, index) { - this._totalResolved++; - this._reject(reason); -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; - -},{"./util.js":38}],25:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util.js"); +var util = _dereq_("./util"); var maybeWrapAsError = util.maybeWrapAsError; -var errors = _dereq_("./errors.js"); -var TimeoutError = errors.TimeoutError; +var errors = _dereq_("./errors"); var OperationalError = errors.OperationalError; -var haveGetters = util.haveGetters; -var es5 = _dereq_("./es5.js"); +var es5 = _dereq_("./es5"); function isUntypedError(obj) { return obj instanceof Error && @@ -3093,114 +2462,1055 @@ function wrapAsOperationalError(obj) { return obj; } -function nodebackForPromise(promise) { +function nodebackForPromise(promise, multiArgs) { 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 { + } else if (!multiArgs) { promise._fulfill(value); + } else { + var args = [].slice.call(arguments, 1);; + promise._fulfill(args); } - promise = null; }; } +module.exports = nodebackForPromise; -var PromiseResolver; -if (!haveGetters) { - PromiseResolver = function (promise) { - this.promise = promise; - this.asCallback = nodebackForPromise(promise); - this.callback = this.asCallback; - }; +},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var util = _dereq_("./util"); +var async = Promise._async; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = + tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } } -else { - PromiseResolver = function (promise) { - this.promise = promise; - }; + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundValue(); + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } } -if (haveGetters) { - var prop = { - get: function() { - return nodebackForPromise(this.promise); +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var newReason = new Error(reason + ""); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundValue(), reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = 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, + this, + nodeback + ); + } + return this; +}; +}; + +},{"./util":36}],22:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var reflectHandler = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +function Proxyable() {} +var UNDEFINED_BINDING = {}; +var util = _dereq_("./util"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; }; - es5.defineProperty(PromiseResolver.prototype, "asCallback", prop); - es5.defineProperty(PromiseResolver.prototype, "callback", prop); +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var es5 = _dereq_("./es5"); +var Async = _dereq_("./async"); +var async = new Async(); +es5.defineProperty(Promise, "_async", {value: async}); +var errors = _dereq_("./errors"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +var CancellationError = Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {}; +var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array")(Promise, INTERNAL, + tryConvertToPromise, apiRejection, Proxyable); +var Context = _dereq_("./context")(Promise); + /*jshint unused:false*/ +var createContext = Context.create; +var debug = _dereq_("./debuggability")(Promise, Context); +var CapturedTrace = debug.CapturedTrace; +var finallyHandler = _dereq_("./finally")(Promise, tryConvertToPromise); +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = _dereq_("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + if (self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } } -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"); +function Promise(executor) { + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + if (executor !== INTERNAL) { + check(this, executor); + this._resolveFromExecutor(executor); } - this.promise._resolveCallback(value); + this._promiseCreated(); +} + +Promise.prototype.toString = function () { + return "[object Promise]"; }; -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"); +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 (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return apiRejection("expecting an object but got " + util.classString(item)); + } + } + catchInstances.length = j; + fn = arguments[i]; + return this.then(undefined, catchFilter(catchInstances, fn, this)); } - this.promise._rejectCallback(reason); + return this.then(undefined, fn); }; -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"); +Promise.prototype.reflect = function () { + return this._then(reflectHandler, + reflectHandler, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject) { + if (debug.warnings() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); } - this.promise._progress(value); + return this._then(didFulfill, didReject, undefined, undefined, undefined); }; -PromiseResolver.prototype.cancel = function (err) { - this.promise.cancel(err); +Promise.prototype.done = function (didFulfill, didReject) { + var promise = + this._then(didFulfill, didReject, undefined, undefined, undefined); + promise._setIsFinal(); }; -PromiseResolver.prototype.timeout = function () { - this.reject(new TimeoutError("timeout")); +Promise.prototype.spread = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; -PromiseResolver.prototype.isResolved = function () { - return this.promise.isResolved(); +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; }; -PromiseResolver.prototype.toJSON = function () { - return this.promise.toJSON(); +Promise.prototype.all = function () { + if (arguments.length > 0) { + this._warn(".all() was passed arguments but it does not take any"); + } + return new PromiseArray(this).promise(); }; -module.exports = PromiseResolver; +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; -},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){ +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = Promise.fromCallback = function(fn) { + var ret = new Promise(INTERNAL); + var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs + : false; + var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); + if (result === errorObj) { + ret._rejectCallback(result.e, true); + } + if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._setFulfilled(); + ret._rejectionHandler0 = obj; + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + _, receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var promise = haveInternalData ? internalData : new Promise(INTERNAL); + var target = this._target(); + var bitField = target._bitField; + + if (!haveInternalData) { + promise._propagateFrom(this, 3); + promise._captureStackTrace(); + if (receiver === undefined && + ((this._bitField & 2097152) !== 0)) { + if (!((bitField & 50397184) === 0)) { + receiver = this._boundValue(); + } else { + receiver = target === this ? undefined : this._boundTo; + } + } + } + + var domain = getDomain(); + if (!((bitField & 50397184) === 0)) { + var handler, value, settler = target._settlePromiseCtx; + if (((bitField & 33554432) !== 0)) { + value = target._rejectionHandler0; + handler = didFulfill; + } else if (((bitField & 16777216) !== 0)) { + value = target._fulfillmentHandler0; + handler = didReject; + target._unsetRejectionIsUnhandled(); + } else { + settler = target._settlePromiseLateCancellationObserver; + value = new CancellationError("late cancellation observer"); + target._attachExtraTrace(value); + handler = didReject; + } + + async.invoke(settler, target, { + handler: domain === null ? handler + : (typeof handler === "function" && domain.bind(handler)), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + } + + return promise; +}; + +Promise.prototype._length = function () { + return this._bitField & 65535; +}; + +Promise.prototype._isFateSealed = function () { + return (this._bitField & 117506048) !== 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 67108864) === 67108864; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -65536) | + (len & 65535); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 16777216; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._unsetCancelled = function() { + this._bitField = this._bitField & (~65536); +}; + +Promise.prototype._setCancelled = function() { + this._bitField = this._bitField | 65536; +}; + +Promise.prototype._setAsyncGuaranteed = function() { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 ? this._receiver0 : this[ + index * 4 - 4 + 3]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return this[ + index * 4 - 4 + 2]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return this[ + index * 4 - 4 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return this[ + index * 4 - 4 + 1]; +}; + +Promise.prototype._boundValue = function() {}; + +Promise.prototype._migrateCallback0 = function (follower) { + var bitField = follower._bitField; + var fulfill = follower._fulfillmentHandler0; + var reject = follower._rejectionHandler0; + var promise = follower._promise0; + var receiver = follower._receiverAt(0); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._migrateCallbackAt = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + promise, + receiver, + domain +) { + var index = this._length(); + + if (index >= 65535 - 4) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + this._receiver0 = receiver; + if (typeof fulfill === "function") { + this._fulfillmentHandler0 = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : domain.bind(reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : domain.bind(reject); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._proxy = function (proxyable, arg) { + this._addCallbacks(undefined, undefined, arg, proxyable, null); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (((this._bitField & 117506048) !== 0)) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + if (shouldBind) this._propagateFrom(maybePromise, 2); + + var promise = maybePromise._target(); + var bitField = promise._bitField; + if (((bitField & 50397184) === 0)) { + var len = this._length(); + if (len > 0) promise._migrateCallback0(this); + for (var i = 1; i < len; ++i) { + promise._migrateCallbackAt(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (((bitField & 33554432) !== 0)) { + this._fulfill(promise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._reject(promise._reason()); + } else { + var reason = new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + this._reject(reason); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, ignoreNonErrorWarnings) { + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { + var message = "a promise was rejected with a non-error: " + + util.classString(reason); + this._warn(message, true); + } + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason); +}; + +Promise.prototype._resolveFromExecutor = function (executor) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = this._execute(executor, function(value) { + promise._resolveCallback(value); + }, function (reason) { + promise._rejectCallback(reason, synchronous); + }); + synchronous = false; + this._popContext(); + + if (r !== undefined) { + promise._rejectCallback(r, true); + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + var bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + promise._pushContext(); + var x; + if (receiver === APPLY) { + if (!value || typeof value.length !== "number") { + x = errorObj; + x.e = new TypeError("cannot .spread() a non-array: " + + util.classString(value)); + } else { + x = tryCatch(handler).apply(this._boundValue(), value); + } + } else { + x = tryCatch(handler).call(receiver, value); + } + var promiseCreated = promise._popContext(); + bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + + if (x === NEXT_FILTER) { + promise._reject(value); + } else if (x === errorObj || x === promise) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false); + } else { + debug.checkForgottenReturns(x, promiseCreated, "", promise); + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._settlePromise = function(promise, handler, receiver, value) { + var isPromise = promise instanceof Promise; + var bitField = this._bitField; + var asyncGuaranteed = ((bitField & 134217728) !== 0); + if (((bitField & 65536) !== 0)) { + if (isPromise) promise._invokeInternalOnCancel(); + + if (handler === finallyHandler) { + receiver.cancelPromise = promise; + if (tryCatch(handler).call(receiver, value) === errorObj) { + promise._reject(errorObj.e); + } + } else if (handler === reflectHandler) { + promise._fulfill(reflectHandler.call(receiver)); + } else if (receiver instanceof Proxyable) { + receiver._promiseCancelled(promise); + } else if (isPromise || promise instanceof PromiseArray) { + promise._cancel(); + } else { + receiver.cancel(); + } + } else if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof Proxyable) { + if (!receiver._isResolved()) { + if (((bitField & 33554432) !== 0)) { + receiver._promiseFulfilled(value, promise); + } else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + if (((bitField & 33554432) !== 0)) { + promise._fulfill(value); + } else { + promise._reject(value); + } + } +}; + +Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { + var handler = ctx.handler; + var promise = ctx.promise; + var receiver = ctx.receiver; + var value = ctx.value; + if (typeof handler === "function") { + if (!(promise instanceof Promise)) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (promise instanceof Promise) { + promise._reject(value); + } +}; + +Promise.prototype._settlePromiseCtx = function(ctx) { + this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); +}; + +Promise.prototype._settlePromise0 = function(handler, value, bitField) { + var promise = this._promise0; + var receiver = this._receiverAt(0); + this._promise0 = undefined; + this._receiver0 = undefined; + this._settlePromise(promise, handler, receiver, value); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + var base = index * 4 - 4; + this[base + 2] = + this[base + 3] = + this[base + 0] = + this[base + 1] = undefined; +}; + +Promise.prototype._fulfill = function (value) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._reject(err); + } + this._setFulfilled(); + this._rejectionHandler0 = value; + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + } +}; + +Promise.prototype._reject = function (reason) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + this._setRejected(); + this._fulfillmentHandler0 = reason; + + if (this._isFinal()) { + return async.fatalError(reason, util.isNode); + } + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._fulfillPromises = function (len, value) { + for (var i = 1; i < len; i++) { + var handler = this._fulfillmentHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, value); + } +}; + +Promise.prototype._rejectPromises = function (len, reason) { + for (var i = 1; i < len; i++) { + var handler = this._rejectionHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, reason); + } +}; + +Promise.prototype._settlePromises = function () { + var bitField = this._bitField; + var len = (bitField & 65535); + + if (len > 0) { + if (((bitField & 16842752) !== 0)) { + var reason = this._fulfillmentHandler0; + this._settlePromise0(this._rejectionHandler0, reason, bitField); + this._rejectPromises(len, reason); + } else { + var value = this._rejectionHandler0; + this._settlePromise0(this._fulfillmentHandler0, value, bitField); + this._fulfillPromises(len, value); + } + this._setLength(0); + } + this._clearCancellationData(); +}; + +Promise.prototype._settledValue = function() { + var bitField = this._bitField; + if (((bitField & 33554432) !== 0)) { + return this._rejectionHandler0; + } else if (((bitField & 16777216) !== 0)) { + return this._fulfillmentHandler0; + } +}; + +function deferResolve(v) {this.promise._resolveCallback(v);} +function deferReject(v) {this.promise._rejectCallback(v, false);} + +Promise.defer = Promise.pending = function() { + debug.deprecated("Promise.defer", "new Promise"); + var promise = new Promise(INTERNAL); + return { + promise: promise, + resolve: deferResolve, + reject: deferReject + }; +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, + debug); +_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); +_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); +_dereq_("./direct_resolve")(Promise); +_dereq_("./synchronous_inspection")(Promise); +_dereq_("./join")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug); +Promise.Promise = Promise; +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); +_dereq_('./timers.js')(Promise, INTERNAL); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); +_dereq_('./nodeify.js')(Promise); +_dereq_('./call_get.js')(Promise); +_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +_dereq_('./settle.js')(Promise, PromiseArray, debug); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./promisify.js')(Promise, INTERNAL); +_dereq_('./any.js')(Promise); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + debug.setBounds(Async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = _dereq_("./util"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + if (values instanceof Promise) { + promise._propagateFrom(values, 3); + } + promise._setOnCancel(this); + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +util.inherits(PromiseArray, Proxyable); + +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, this._promise); + if (values instanceof Promise) { + values = values._target(); + var bitField = values._bitField; + ; + this._values = values; + + if (((bitField & 50397184) === 0)) { + this._promise._setAsyncGuaranteed(); + return values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + } else if (((bitField & 33554432) !== 0)) { + values = values._value(); + } else if (((bitField & 16777216) !== 0)) { + return this._reject(values._reason()); + } else { + return this._cancel(); + } + } + values = util.asArray(values); + if (values === null) { + var err = apiRejection( + "expecting an array or an iterable object but got " + util.classString(values)).reason(); + this._promise._rejectCallback(err, false); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + this._iterate(values); +}; + +PromiseArray.prototype._iterate = function(values) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var result = this._promise; + var isResolved = false; + var bitField = null; + for (var i = 0; i < len; ++i) { + var maybePromise = tryConvertToPromise(values[i], result); + + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + bitField = maybePromise._bitField; + } else { + bitField = null; + } + + if (isResolved) { + if (bitField !== null) { + maybePromise.suppressUnhandledRejections(); + } + } else if (bitField !== null) { + if (((bitField & 50397184) === 0)) { + maybePromise._proxy(this, i); + this._values[i] = maybePromise; + } else if (((bitField & 33554432) !== 0)) { + isResolved = this._promiseFulfilled(maybePromise._value(), i); + } else if (((bitField & 16777216) !== 0)) { + isResolved = this._promiseRejected(maybePromise._reason(), i); + } else { + isResolved = this._promiseCancelled(i); + } + } else { + isResolved = this._promiseFulfilled(maybePromise, i); + } + } + if (!isResolved) result._setAsyncGuaranteed(); +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype._cancel = function() { + if (this._isResolved() || !this._promise.isCancellable()) return; + this._values = null; + this._promise._cancel(); +}; + +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false); +}; + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +PromiseArray.prototype._promiseCancelled = function() { + this._cancel(); + return true; +}; + +PromiseArray.prototype._promiseRejected = function (reason) { + this._totalResolved++; + this._reject(reason); + return true; +}; + +PromiseArray.prototype._resultCancelled = function() { + if (this._isResolved()) return; + var values = this._values; + this._cancel(); + if (values instanceof Promise) { + values.cancel(); + } else { + for (var i = 0; i < values.length; ++i) { + if (values[i] instanceof Promise) { + values[i].cancel(); + } + } + } +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util":36}],24:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; -var util = _dereq_("./util.js"); -var nodebackForPromise = _dereq_("./promise_resolver.js") - ._nodebackForPromise; +var util = _dereq_("./util"); +var nodebackForPromise = _dereq_("./nodeback"); var withAppended = util.withAppended; var maybeWrapAsError = util.maybeWrapAsError; var canEvaluate = util.canEvaluate; var TypeError = _dereq_("./errors").TypeError; var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; -var noCopyPropsPattern = - /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/; -var defaultFilter = function(name, func) { +var noCopyProps = [ + "arity", "length", + "name", + "arguments", + "caller", + "callee", + "prototype", + "__isPromisified__" +]; +var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); + +var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && - !util.isClass(func); + name !== "constructor"; }; function propsFilter(key) { @@ -3228,7 +3538,7 @@ function checkValid(ret, suffix, suffixRegexp) { 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" + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" .replace("%s", suffix)); } } @@ -3290,7 +3600,7 @@ var parameterCount = function(fn) { }; makeNodePromisifiedEval = -function(callback, receiver, originalName, fn) { +function(callback, receiver, originalName, fn, _, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver === THIS; @@ -3335,22 +3645,13 @@ function(callback, receiver, originalName, fn) { var getFunctionCode = typeof callback === "string" ? ("this != null ? this['"+callback+"'] : fn") : "fn"; - - return new Function("Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "INTERNAL","'use strict'; \n\ + var body = "'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise); \n\ + var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ var ret; \n\ var callback = tryCatch([GetFunctionCode]); \n\ switch(len) { \n\ @@ -3359,28 +3660,39 @@ function(callback, receiver, originalName, fn) { if (ret === errorObj) { \n\ promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ } \n\ + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ return promise; \n\ }; \n\ - ret.__isPromisified__ = true; \n\ + notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ - " - .replace("Parameters", parameterDeclaration(newParameterCount)) - .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode))( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - INTERNAL - ); + ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode); + body = body.replace("Parameters", parameterDeclaration(newParameterCount)); + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "notEnumerableProp", + "INTERNAL", + body)( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + util.notEnumerableProp, + INTERNAL); }; } -function makeNodePromisifiedClosure(callback, receiver, _, fn) { +function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { var defaultThis = (function() {return this;})(); var method = callback; if (typeof method === "string") { @@ -3393,15 +3705,16 @@ function makeNodePromisifiedClosure(callback, receiver, _, fn) { promise._captureStackTrace(); var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; - var fn = nodebackForPromise(promise); + var fn = nodebackForPromise(promise, multiArgs); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true, true); } + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); return promise; } - promisified.__isPromisified__ = true; + util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } @@ -3409,7 +3722,7 @@ var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; -function promisifyAll(obj, suffix, filter, promisifier) { +function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); @@ -3418,37 +3731,48 @@ function promisifyAll(obj, suffix, filter, promisifier) { 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, function() { - return makeNodePromisified(key, THIS, key, fn, suffix); - }); + if (promisifier === makeNodePromisified) { + obj[promisifiedKey] = + makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); + } else { + var promisified = promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, + fn, suffix, multiArgs); + }); + util.notEnumerableProp(promisified, "__isPromisified__", true); + obj[promisifiedKey] = promisified; + } } util.toFastProperties(obj); return obj; } -function promisify(callback, receiver) { - return makeNodePromisified(callback, receiver, undefined, callback); +function promisify(callback, receiver, multiArgs) { + return makeNodePromisified(callback, receiver, undefined, + callback, null, multiArgs); } -Promise.promisify = function (fn, receiver) { +Promise.promisify = function (fn, options) { if (typeof fn !== "function") { - throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + throw new TypeError("expecting a function but got " + util.classString(fn)); } if (isPromisified(fn)) { return fn; } - var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + options = Object(options); + var receiver = options.context === undefined ? THIS : options.context; + var multiArgs = !!options.multiArgs; + var ret = promisify(fn, receiver, multiArgs); util.copyDescriptors(fn, ret, propsFilter); return ret; }; 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"); + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } options = Object(options); + var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; var filter = options.filter; @@ -3457,7 +3781,7 @@ Promise.promisifyAll = function (target, options) { 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"); + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var keys = util.inheritedDataKeys(target); @@ -3465,59 +3789,99 @@ Promise.promisifyAll = function (target, options) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier); - promisifyAll(value, suffix, filter, promisifier); + promisifyAll(value.prototype, suffix, filter, promisifier, + multiArgs); + promisifyAll(value, suffix, filter, promisifier, multiArgs); } } - return promisifyAll(target, suffix, filter, promisifier); + return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; -},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){ +},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util.js"); +var util = _dereq_("./util"); var isObject = util.isObject; -var es5 = _dereq_("./es5.js"); +var es5 = _dereq_("./es5"); +var Es6Map; +if (typeof Map === "function") Es6Map = Map; + +var mapToEntries = (function() { + var index = 0; + var size = 0; + + function extractEntry(value, key) { + this[index] = value; + this[index + size] = key; + index++; + } + + return function mapToEntries(map) { + size = map.size; + index = 0; + var ret = new Array(map.size * 2); + map.forEach(extractEntry, ret); + return ret; + }; +})(); + +var entriesToMap = function(entries) { + var ret = new Es6Map(); + var length = entries.length / 2 | 0; + for (var i = 0; i < length; ++i) { + var key = entries[length + i]; + var value = entries[i]; + ret.set(key, value); + } + return ret; +}; 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; + var isMap = false; + var entries; + if (Es6Map !== undefined && obj instanceof Es6Map) { + entries = mapToEntries(obj); + isMap = true; + } else { + var keys = es5.keys(obj); + var len = keys.length; + entries = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + entries[i] = obj[key]; + entries[i + len] = key; + } } - this.constructor$(values); + this.constructor$(entries); + this._isMap = isMap; + this._init$(undefined, -3); } util.inherits(PropertiesPromiseArray, PromiseArray); -PropertiesPromiseArray.prototype._init = function () { - this._init$(undefined, -3) ; -}; +PropertiesPromiseArray.prototype._init = function () {}; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { 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]; + var val; + if (this._isMap) { + val = entriesToMap(this._values); + } else { + 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); + return true; } -}; - -PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { - this._promise._progress({ - key: this._values[index + this.length()], - value: value - }); + return false; }; PropertiesPromiseArray.prototype.shouldCopyValues = function () { @@ -3533,7 +3897,7 @@ function props(promises) { var castValue = tryConvertToPromise(promises); if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } else if (castValue instanceof Promise) { ret = castValue._then( Promise.props, undefined, undefined, undefined, undefined); @@ -3542,7 +3906,7 @@ function props(promises) { } if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 4); + ret._propagateFrom(castValue, 2); } return ret; } @@ -3556,7 +3920,7 @@ Promise.props = function (promises) { }; }; -},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){ +},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { @@ -3648,11 +4012,11 @@ Queue.prototype._resizeTo = function (capacity) { module.exports = Queue; -},{}],29:[function(_dereq_,module,exports){ +},{}],27:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var isArray = _dereq_("./util.js").isArray; +var util = _dereq_("./util"); var raceLater = function (promise) { return promise.then(function(array) { @@ -3665,13 +4029,15 @@ function race(promises, parent) { 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"); + } else { + promises = util.asArray(promises); + if (promises === null) + return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); } var ret = new Promise(INTERNAL); if (parent !== undefined) { - ret._propagateFrom(parent, 4 | 1); + ret._propagateFrom(parent, 3); } var fulfill = ret._fulfill; var reject = ret._reject; @@ -3697,145 +4063,108 @@ Promise.prototype.race = function () { }; -},{"./util.js":38}],30:[function(_dereq_,module,exports){ +},{"./util":36}],28:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, - INTERNAL) { -var async = _dereq_("./async.js"); -var util = _dereq_("./util.js"); + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +var util = _dereq_("./util"); var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -function ReductionPromiseArray(promises, fn, accum, _each) { + +function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); - this._promise._captureStackTrace(); - 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, this._promise); - var rejected = false; - var isPromise = maybePromise instanceof Promise; - if (isPromise) { - maybePromise = maybePromise._target(); - if (maybePromise._isPending()) { - maybePromise._proxyPromiseArray(this, -1); - } else if (maybePromise._isFulfilled()) { - accum = maybePromise._value(); - this._gotAccum = true; - } else { - this._reject(maybePromise._reason()); - rejected = true; - } + var domain = getDomain(); + this._fn = domain === null ? fn : domain.bind(fn); + if (initialValue !== undefined) { + initialValue = Promise.resolve(initialValue); + initialValue._attachCancellationCallback(this); } - if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; - this._callback = fn; - this._accum = accum; - if (!rejected) async.invoke(init, this, undefined); -} -function init() { + this._initialValue = initialValue; + this._currentCancellable = null; + this._eachValues = _each === INTERNAL ? [] : undefined; + this._promise._captureStackTrace(); 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._gotAccum = function(accum) { + if (this._eachValues !== undefined && accum !== INTERNAL) { + this._eachValues.push(accum); } }; -ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { - 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 = new Array(length); - for (valuesPhaseIndex=0; valuesPhaseIndex 10) || (version[0] > 0) - ? global.setImmediate : process.nextTick; - - if (!schedule) { - if (typeof setImmediate !== "undefined") { - schedule = setImmediate; - } else if (typeof setTimeout !== "undefined") { - schedule = setTimeout; - } else { - schedule = noAsyncScheduler; - } - } -} else if (typeof MutationObserver !== "undefined") { +if (util.isNode && typeof MutationObserver === "undefined") { + var GlobalSetImmediate = global.setImmediate; + var ProcessNextTick = process.nextTick; + schedule = util.isRecentNode + ? function(fn) { GlobalSetImmediate.call(global, fn); } + : function(fn) { ProcessNextTick.call(process, fn); }; +} else if ((typeof MutationObserver !== "undefined") && + !(typeof window !== "undefined" && + window.navigator && + window.navigator.standalone)) { schedule = function(fn) { var div = document.createElement("div"); var observer = new MutationObserver(fn); @@ -3886,12 +4264,12 @@ if (_dereq_("./util.js").isNode) { } module.exports = schedule; -},{"./util.js":38}],32:[function(_dereq_,module,exports){ +},{"./util":36}],30:[function(_dereq_,module,exports){ "use strict"; module.exports = - function(Promise, PromiseArray) { + function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; -var util = _dereq_("./util.js"); +var util = _dereq_("./util"); function SettledPromiseArray(values) { this.constructor$(values); @@ -3903,39 +4281,43 @@ SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); + return true; } + return false; }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); - ret._bitField = 268435456; - ret._settledValue = value; - this._promiseResolved(index, ret); + ret._bitField = 33554432; + ret._settledValueField = value; + return this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); - ret._bitField = 134217728; - ret._settledValue = reason; - this._promiseResolved(index, ret); + ret._bitField = 16777216; + ret._settledValueField = reason; + return this._promiseResolved(index, ret); }; Promise.settle = function (promises) { + debug.deprecated(".settle()", ".reflect()"); return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { - return new SettledPromiseArray(this).promise(); + return Promise.settle(this); }; }; -},{"./util.js":38}],33:[function(_dereq_,module,exports){ +},{"./util":36}],31:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection) { -var util = _dereq_("./util.js"); -var RangeError = _dereq_("./errors.js").RangeError; -var AggregateError = _dereq_("./errors.js").AggregateError; +var util = _dereq_("./util"); +var RangeError = _dereq_("./errors").RangeError; +var AggregateError = _dereq_("./errors").AggregateError; var isArray = util.isArray; +var CANCELLATION = {}; function SomePromiseArray(values) { @@ -3989,18 +4371,40 @@ SomePromiseArray.prototype._promiseFulfilled = function (value) { } else { this._resolve(this._values); } + return true; } + return false; }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._promiseCancelled = function () { + if (this._values instanceof Promise || this._values == null) { + return this._cancel(); + } + this._addRejected(CANCELLATION); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._checkOutcome = function() { if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { - e.push(this._values[i]); + if (this._values[i] !== CANCELLATION) { + e.push(this._values[i]); + } } - this._reject(e); + if (e.length > 0) { + this._reject(e); + } else { + this._cancel(); + } + return true; } + return false; }; SomePromiseArray.prototype._fulfilled = function () { @@ -4035,7 +4439,7 @@ SomePromiseArray.prototype._resolveEmptyArray = function () { function some(promises, howMany) { if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var ret = new SomePromiseArray(promises); var promise = ret.promise(); @@ -4055,142 +4459,151 @@ Promise.prototype.some = function (howMany) { Promise._SomePromiseArray = SomePromiseArray; }; -},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){ +},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function PromiseInspection(promise) { if (promise !== undefined) { promise = promise._target(); this._bitField = promise._bitField; - this._settledValue = promise._settledValue; + this._settledValueField = promise._isFateSealed() + ? promise._settledValue() : undefined; } else { this._bitField = 0; - this._settledValue = undefined; + this._settledValueField = undefined; } } -PromiseInspection.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._settledValue = function() { + return this._settledValueField; }; -PromiseInspection.prototype.error = +var value = PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var reason = PromiseInspection.prototype.error = PromiseInspection.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"); + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } - return this._settledValue; + return this._settledValue(); }; -PromiseInspection.prototype.isFulfilled = -Promise.prototype._isFulfilled = function () { - return (this._bitField & 268435456) > 0; +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { + return (this._bitField & 33554432) !== 0; }; -PromiseInspection.prototype.isRejected = -Promise.prototype._isRejected = function () { - return (this._bitField & 134217728) > 0; +var isRejected = PromiseInspection.prototype.isRejected = function () { + return (this._bitField & 16777216) !== 0; }; -PromiseInspection.prototype.isPending = -Promise.prototype._isPending = function () { - return (this._bitField & 402653184) === 0; +var isPending = PromiseInspection.prototype.isPending = function () { + return (this._bitField & 50397184) === 0; }; -PromiseInspection.prototype.isResolved = -Promise.prototype._isResolved = function () { - return (this._bitField & 402653184) > 0; +var isResolved = PromiseInspection.prototype.isResolved = function () { + return (this._bitField & 50331648) !== 0; +}; + +PromiseInspection.prototype.isCancelled = +Promise.prototype._isCancelled = function() { + return (this._bitField & 65536) === 65536; +}; + +Promise.prototype.isCancelled = function() { + return this._target()._isCancelled(); }; Promise.prototype.isPending = function() { - return this._target()._isPending(); + return isPending.call(this._target()); }; Promise.prototype.isRejected = function() { - return this._target()._isRejected(); + return isRejected.call(this._target()); }; Promise.prototype.isFulfilled = function() { - return this._target()._isFulfilled(); + return isFulfilled.call(this._target()); }; Promise.prototype.isResolved = function() { - return this._target()._isResolved(); -}; - -Promise.prototype._value = function() { - return this._settledValue; -}; - -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue; + return isResolved.call(this._target()); }; Promise.prototype.value = function() { - var target = this._target(); - if (!target.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); - } - return target._settledValue; + return value.call(this._target()); }; Promise.prototype.reason = function() { var target = this._target(); - if (!target.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); - } target._unsetRejectionIsUnhandled(); - return target._settledValue; + return reason.call(target); }; +Promise.prototype._value = function() { + return this._settledValue(); +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue(); +}; Promise.PromiseInspection = PromiseInspection; }; -},{}],35:[function(_dereq_,module,exports){ +},{}],33:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { -var util = _dereq_("./util.js"); +var util = _dereq_("./util"); var errorObj = util.errorObj; var isObject = util.isObject; function tryConvertToPromise(obj, context) { if (isObject(obj)) { - if (obj instanceof Promise) { - return obj; - } - else if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfillUnchecked, - ret._rejectUncheckedCheckError, - ret._progressUnchecked, - ret, - null - ); - return ret; - } - var then = util.tryCatch(getThen)(obj); + if (obj instanceof Promise) return obj; + var then = getThen(obj); if (then === errorObj) { if (context) context._pushContext(); var ret = Promise.reject(then.e); if (context) context._popContext(); return ret; } else if (typeof then === "function") { + if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfill, + ret._reject, + undefined, + ret, + null + ); + return ret; + } return doThenable(obj, then, context); } } return obj; } -function getThen(obj) { +function doGetThen(obj) { return obj.then; } +function getThen(obj) { + try { + return doGetThen(obj); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} + var hasProp = {}.hasOwnProperty; function isAnyBluebirdPromise(obj) { return hasProp.call(obj, "_promise0"); @@ -4203,77 +4616,71 @@ function doThenable(x, then, context) { promise._captureStackTrace(); if (context) context._popContext(); var synchronous = true; - var result = util.tryCatch(then).call(x, - resolveFromThenable, - rejectFromThenable, - progressFromThenable); + var result = util.tryCatch(then).call(x, resolve, reject); synchronous = false; + if (promise && result === errorObj) { promise._rejectCallback(result.e, true, true); promise = null; } - function resolveFromThenable(value) { + function resolve(value) { if (!promise) return; - if (x === value) { - promise._rejectCallback( - Promise._makeSelfResolutionError(), false, true); - } else { - promise._resolveCallback(value); - } + promise._resolveCallback(value); promise = null; } - function rejectFromThenable(reason) { + function reject(reason) { if (!promise) return; promise._rejectCallback(reason, synchronous, true); promise = null; } - - function progressFromThenable(value) { - if (!promise) return; - if (typeof promise._progress === "function") { - promise._progress(value); - } - } return ret; } return tryConvertToPromise; }; -},{"./util.js":38}],36:[function(_dereq_,module,exports){ +},{"./util":36}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { -var util = _dereq_("./util.js"); +var util = _dereq_("./util"); var TimeoutError = Promise.TimeoutError; -var afterTimeout = function (promise, message) { +var afterTimeout = function (promise, message, parent) { if (!promise.isPending()) return; + var err; if (typeof message !== "string") { - message = "operation timed out"; + if (message instanceof Error) { + err = message; + } else { + err = new TimeoutError("operation timed out"); + } + } else { + err = new TimeoutError(message); } - var err = new TimeoutError(message); util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); - promise._cancel(err); + promise._reject(err); + parent.cancel(); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; -var delay = Promise.delay = function (value, ms) { - if (ms === undefined) { - ms = value; - value = undefined; - var ret = new Promise(INTERNAL); - setTimeout(function() { ret._fulfill(); }, ms); - return ret; +var delay = Promise.delay = function (ms, value) { + var ret; + if (value !== undefined) { + ret = Promise.resolve(value) + ._then(afterValue, null, null, ms, undefined); + } else { + ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, +ms); } - ms = +ms; - return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); + ret._setAsyncGuaranteed(); + return ret; }; Promise.prototype.delay = function (ms) { - return delay(this, ms); + return delay(ms, this); }; function successClear(value) { @@ -4292,35 +4699,25 @@ function failureClear(reason) { Promise.prototype.timeout = function (ms, message) { ms = +ms; - var ret = this.then().cancellable(); - ret._cancellationParent = this; + var parent = this.then(); + var ret = parent.then(); var handle = setTimeout(function timeoutTimeout() { - afterTimeout(ret, message); + afterTimeout(ret, message, parent); }, ms); return ret._then(successClear, failureClear, undefined, handle, undefined); }; }; -},{"./util.js":38}],37:[function(_dereq_,module,exports){ +},{"./util":36}],35:[function(_dereq_,module,exports){ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext) { - var TypeError = _dereq_("./errors.js").TypeError; - var inherits = _dereq_("./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; - } + createContext, INTERNAL, debug) { + var util = _dereq_("./util"); + var TypeError = _dereq_("./errors").TypeError; + var inherits = _dereq_("./util").inherits; + var errorObj = util.errorObj; + var tryCatch = util.tryCatch; function thrower(e) { setTimeout(function(){throw e;}, 0); @@ -4339,9 +4736,9 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, function dispose(resources, inspection) { var i = 0; var len = resources.length; - var ret = Promise.defer(); + var ret = new Promise(INTERNAL); function iterator() { - if (i >= len) return ret.resolve(); + if (i >= len) return ret._fulfill(); var maybePromise = castPreservingDisposable(resources[i++]); if (maybePromise instanceof Promise && maybePromise._isDisposable()) { @@ -4360,21 +4757,7 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, 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); + return ret; } function Disposer(data, promise, context) { @@ -4434,16 +4817,43 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, return value; } + function ResourceList(length) { + this.length = length; + this.promise = null; + this[length-1] = null; + } + + ResourceList.prototype._resultCancelled = function() { + var len = this.length; + for (var i = 0; i < len; ++i) { + var item = this[i]; + if (item instanceof Promise) { + item.cancel(); + } + } + }; + 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); + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var input; + var spreadArgs = true; + if (len === 2 && Array.isArray(arguments[0])) { + input = arguments[0]; + len = input.length; + spreadArgs = false; + } else { + input = arguments; + len--; + } + var resources = new ResourceList(len); for (var i = 0; i < len; ++i) { - var resource = arguments[i]; + var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); @@ -4461,31 +4871,51 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, resources[i] = resource; } - var promise = Promise.settle(resources) - .then(inspectionMapper) - .then(function(vals) { - promise._pushContext(); - var ret; - try { - ret = fn.apply(undefined, vals); - } finally { - promise._popContext(); + var reflectedResources = new Array(resources.length); + for (var i = 0; i < reflectedResources.length; ++i) { + reflectedResources[i] = Promise.resolve(resources[i]).reflect(); + } + + var resultPromise = Promise.all(reflectedResources) + .then(function(inspections) { + for (var i = 0; i < inspections.length; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + errorObj.e = inspection.error(); + return errorObj; + } else if (!inspection.isFulfilled()) { + resultPromise.cancel(); + return; + } + inspections[i] = inspection.value(); } + promise._pushContext(); + + fn = tryCatch(fn); + var ret = spreadArgs + ? fn.apply(undefined, inspections) : fn(inspections); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, promiseCreated, "Promise.using", promise); return ret; - }) - ._then( - disposerSuccess, disposerFail, undefined, resources, undefined); + }); + + var promise = resultPromise.lastly(function() { + var inspection = new Promise.PromiseInspection(resultPromise); + return dispose(resources, inspection); + }); resources.promise = promise; + promise._setOnCancel(resources); return promise; }; Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 262144; + this._bitField = this._bitField | 131072; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { - return (this._bitField & 262144) > 0; + return (this._bitField & 131072) > 0; }; Promise.prototype._getDisposer = function () { @@ -4493,7 +4923,7 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, }; Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~262144); + this._bitField = this._bitField & (~131072); this._disposer = undefined; }; @@ -4506,31 +4936,18 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, }; -},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){ +},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ "use strict"; -var es5 = _dereq_("./es5.js"); +var es5 = _dereq_("./es5"); var canEvaluate = typeof navigator == "undefined"; -var haveGetters = (function(){ - try { - var o = {}; - es5.defineProperty(o, "f", { - get: function () { - return 3; - } - }); - return o.f === 3; - } - catch (e) { - return false; - } - -})(); var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { - return tryCatchTarget.apply(this, arguments); + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; @@ -4568,7 +4985,8 @@ function isPrimitive(val) { } function isObject(value) { - return !isPrimitive(value); + return typeof value === "function" || + typeof value === "object" && value !== null; } function maybeWrapAsError(maybeError) { @@ -4591,6 +5009,7 @@ function withAppended(target, appendee) { 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 @@ -4613,23 +5032,32 @@ function notEnumerableProp(obj, name, value) { return obj; } - -var wrapsPrimitiveReceiver = (function() { - return this !== "string"; -}).call("string"); - function thrower(r) { throw r; } var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; + + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; + if (es5.isES5) { - var oProto = Object.prototype; var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); - while (obj != null && obj !== oProto) { + while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); @@ -4650,11 +5078,23 @@ var inheritedDataKeys = (function() { return ret; }; } else { + var hasProp = {}.hasOwnProperty; return function(obj) { + if (isExcludedProto(obj)) return []; var ret = []; + /*jshint forin:false */ - for (var key in obj) { - ret.push(key); + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } } return ret; }; @@ -4662,13 +5102,22 @@ var inheritedDataKeys = (function() { })(); +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); - if (es5.isES5) return keys.length > 1; - return keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); + + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } } return false; } catch (e) { @@ -4678,10 +5127,10 @@ function isClass(fn) { function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ - function f() {} - f.prototype = obj; + function FakeConstructor() {} + FakeConstructor.prototype = obj; var l = 8; - while (l--) new f(); + while (l--) new FakeConstructor(); return obj; eval(obj); } @@ -4748,11 +5197,50 @@ function copyDescriptors(from, to, filter) { for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} } } } +var asArray = function(v) { + if (es5.isArray(v)) { + return v; + } + return null; +}; + +if (typeof Symbol !== "undefined" && Symbol.iterator) { + var ArrayFrom = typeof Array.from === "function" ? function(v) { + return Array.from(v); + } : function(v) { + var ret = []; + var it = v[Symbol.iterator](); + var itResult; + while (!((itResult = it.next()).done)) { + ret.push(itResult.value); + } + return ret; + }; + + asArray = function(v) { + if (es5.isArray(v)) { + return v; + } else if (v != null && typeof v[Symbol.iterator] === "function") { + return ArrayFrom(v); + } + return null; + }; +} + +var isNode = typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]"; + +function env(key, def) { + return isNode ? process.env[key] : def; +} + var ret = { isClass: isClass, isIdentifier: isIdentifier, @@ -4760,7 +5248,7 @@ var ret = { getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, - haveGetters: haveGetters, + asArray: asArray, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, @@ -4770,7 +5258,6 @@ var ret = { inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, - wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, @@ -4782,314 +5269,18 @@ var ret = { copyDescriptors: copyDescriptors, hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function", - isNode: typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]" + isNode: isNode, + env: env }; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; -},{"./es5.js":14}],39:[function(_dereq_,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -EventEmitter.defaultMaxListeners = 10; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } - throw TypeError('Uncaught, unspecified "error" event.'); - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - handler.apply(this, args); - } - } else if (isObject(handler)) { - len = arguments.length; - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - var m; - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.listenerCount = function(emitter, type) { - var ret; - if (!emitter._events || !emitter._events[type]) - ret = 0; - else if (isFunction(emitter._events[type])) - ret = 1; - else - ret = emitter._events[type].length; - return ret; -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - -},{}]},{},[4])(4) +},{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } \ No newline at end of file diff --git a/node_modules/bluebird/js/browser/bluebird.min.js b/node_modules/bluebird/js/browser/bluebird.min.js index bee550c..7f99a65 100644 --- a/node_modules/bluebird/js/browser/bluebird.min.js +++ b/node_modules/bluebird/js/browser/bluebird.min.js @@ -1,14 +1,14 @@ /* @preserve * The MIT License (MIT) * - * Copyright (c) 2014 Petka Antonov + * Copyright (c) 2013-2015 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:

+ * 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. @@ -23,9 +23,9 @@ * */ /** - * bluebird build version 2.9.24 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers + * bluebird build version 3.0.6 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,r;return function n(t,e,r){function i(s,a){if(!e[s]){if(!t[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=e[s]={exports:{}};t[s][0].call(l.exports,function(e){var r=t[s][1][e];return i(r?r:e)},l,l.exports,n,t,e,r)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0},r.prototype.throwLater=function(t,e){1===arguments.length&&(e=t,t=function(){throw e});var r=this._getDomain();if(void 0!==r&&(t=r.bind(t)),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(n){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}},r.prototype._getDomain=function(){},l.isNode){var h=t("events"),p=function(){var t=process.domain;return null===t?void 0:t};if(h.usingDomains)r.prototype._getDomain=p;else{var f=Object.getOwnPropertyDescriptor(h,"usingDomains");if(f.configurable){var _=!1;Object.defineProperty(h,"usingDomains",{configurable:!1,enumerable:!0,get:function(){return _},set:function(t){!_&&t&&(_=!0,r.prototype._getDomain=p,l.toFastProperties(process),process.emit("domainsActivated"))}})}else process.on("domainsActivated",function(){r.prototype._getDomain=p})}}l.hasDevTools?(r.prototype.invokeLater=function(t,e,r){this._trampolineEnabled?n.call(this,t,e,r):setTimeout(function(){t.call(e,r)},100)},r.prototype.invoke=function(t,e,r){this._trampolineEnabled?i.call(this,t,e,r):setTimeout(function(){t.call(e,r)},0)},r.prototype.settlePromises=function(t){this._trampolineEnabled?o.call(this,t):setTimeout(function(){t._settlePromises()},0)}):(r.prototype.invokeLater=n,r.prototype.invoke=i,r.prototype.settlePromises=o),r.prototype.invokeFirst=function(t,e,r){var n=this._getDomain();void 0!==n&&(t=n.bind(t)),this._normalQueue.unshift(t,e,r),this._queueTick()},r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=new r,e.exports.firstLineError=s},{"./queue.js":28,"./schedule.js":31,"./util.js":38,events:39}],3:[function(t,e){"use strict";e.exports=function(t,e,r){var n=function(t,e){this._reject(e)},i=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(n,n,null,this,t)},o=function(t,e){this._setBoundTo(t),this._isPending()&&this._resolveCallback(e.target)},s=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(n){var a=r(n),u=new t(e);u._propagateFrom(this,1);var c=this._target();if(a instanceof t){var l={promiseRejectionQueued:!1,promise:u,target:c,bindingPromise:a};c._then(e,i,u._progress,u,l),a._then(o,s,u._progress,u,l)}else u._setBoundTo(n),u._resolveCallback(c);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=131072|this._bitField,this._boundTo=t):this._bitField=-131073&this._bitField},t.prototype._isBound=function(){return 131072===(131072&this._bitField)},t.bind=function(n,i){var o=r(n),s=new t(e);return o instanceof t?o._then(function(t){s._setBoundTo(t),s._resolveCallback(i)},s._reject,s._progress,s,null):(s._setBoundTo(n),s._resolveCallback(i)),s}}},{}],4:[function(t,e){"use strict";function r(){try{Promise===i&&(Promise=n)}catch(t){}return i}var n;"undefined"!=typeof Promise&&(n=Promise);var i=t("./promise.js")();i.noConflict=r,e.exports=i},{"./promise.js":23}],5:[function(t,e){"use strict";var r=Object.create;if(r){var n=r(null),i=r(null);n[" size"]=i[" size"]=0}e.exports=function(e){function r(t,r){var n;if(null!=t&&(n=t[r]),"function"!=typeof n){var i="Object "+a.classString(t)+" has no method '"+a.toString(r)+"'";throw new e.TypeError(i)}return n}function n(t){var e=this.pop(),n=r(t,e);return n.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}{var s,a=t("./util.js"),u=a.canEvaluate;a.isIdentifier}e.prototype.call=function(t){for(var e=arguments.length,r=new Array(e-1),i=1;e>i;++i)r[i-1]=arguments[i];return r.push(t),this._then(n,void 0,void 0,r,void 0)},e.prototype.get=function(t){var e,r="number"==typeof t;if(r)e=o;else if(u){var n=s(t);e=null!==n?n:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util.js":38}],6:[function(t,e){"use strict";e.exports=function(e){var r=t("./errors.js"),n=t("./async.js"),i=r.CancellationError;e.prototype._cancel=function(t){if(!this.isCancellable())return this;for(var e,r=this;void 0!==(e=r._cancellationParent)&&e.isCancellable();)r=e;this._unsetCancellable(),r._target()._rejectCallback(t,!1,!0)},e.prototype.cancel=function(t){return this.isCancellable()?(void 0===t&&(t=new i),n.invokeLater(this._cancel,this,t),this):this},e.prototype.cancellable=function(){return this._cancellable()?this:(n.enableTrampoline(),this._setCancellable(),this._cancellationParent=void 0,this)},e.prototype.uncancellable=function(){var t=this.then();return t._unsetCancellable(),t},e.prototype.fork=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);return n._setCancellable(),n._cancellationParent=void 0,n}}},{"./async.js":2,"./errors.js":13}],7:[function(t,e){"use strict";e.exports=function(){function e(t){this._parent=t;var r=this._length=1+(void 0===t?0:t._length);j(this,e),r>32&&this.uncycle()}function r(t,e){for(var r=0;r=0;--a)if(n[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}function o(t){for(var e=[],r=0;r0&&(e=e.slice(r)),e}function a(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t.toString();var r=/\[object [a-zA-Z0-9$_]+\]/;if(r.test(e))try{var n=JSON.stringify(t);e=n}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+u(e)+">, no stack trace)"}function u(t){var e=41;return t.lengtht)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;t=this._length=n;for(var n=t-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(var n=0;t>n;++n){var s=e[n].stack,a=r[s];if(void 0!==a&&a!==n){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var u=n>0?e[n-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,l=n-2;l>=0;--l)e[l]._length=c,c++;return}}}},e.prototype.parent=function(){return this._parent},e.prototype.hasParent=function(){return void 0!==this._parent},e.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var s=e.parseStackAndMessage(t),a=s.message,u=[s.stack],c=this;void 0!==c;)u.push(o(c.stack.split("\n"))),c=c._parent;i(u),n(u),p.notEnumerableProp(t,"stack",r(a,u)),p.notEnumerableProp(t,"__stackCleaned__",!0)}},e.parseStackAndMessage=function(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?s(t):[" (No stack trace)"],{message:r,stack:o(e)}},e.formatAndLogError=function(t,e){if("undefined"!=typeof console){var r;if("object"==typeof t||"function"==typeof t){var n=t.stack;r=e+d(n,t)}else r=e+String(t);"function"==typeof l?l(r):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}},e.unhandledRejection=function(t){e.formatAndLogError(t,"^--- With additional stack trace: ")},e.isSupported=function(){return"function"==typeof j},e.fireRejectionEvent=function(t,r,n,i){var o=!1;try{"function"==typeof r&&(o=!0,"rejectionHandled"===t?r(i):r(n,i))}catch(s){h.throwLater(s)}var a=!1;try{a=b(t,n,i)}catch(s){a=!0,h.throwLater(s)}var u=!1;if(m)try{u=m(t.toLowerCase(),{reason:n,promise:i})}catch(s){u=!0,h.throwLater(s)}a||o||u||"unhandledRejection"!==t||e.formatAndLogError(n,"Unhandled rejection ")};var y=function(){return!1},g=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;e.setBounds=function(t,r){if(e.isSupported()){for(var n,i,o=t.stack.split("\n"),s=r.stack.split("\n"),a=-1,u=-1,l=0;la||0>u||!n||!i||n!==i||a>=u||(y=function(t){if(f.test(t))return!0;var e=c(t);return e&&e.fileName===n&&a<=e.line&&e.line<=u?!0:!1})}};var m,j=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():a(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit=Error.stackTraceLimit+6,_=t,d=e;var r=Error.captureStackTrace;return y=function(t){return f.test(t)},function(t,e){Error.stackTraceLimit=Error.stackTraceLimit+6,r(t,e),Error.stackTraceLimit=Error.stackTraceLimit-6}}var n=new Error;if("string"==typeof n.stack&&n.stack.split("\n")[0].indexOf("stackDetection@")>=0)return _=/@/,d=e,v=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in n||!i?(d=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?a(e):e.toString()},null):(_=t,d=e,function(t){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6})}([]),b=function(){if(p.isNode)return function(t,e,r){return"rejectionHandled"===t?process.emit(t,r):process.emit(t,e,r)};var t=!1,e=!0;try{var r=new self.CustomEvent("test");t=r instanceof CustomEvent}catch(n){}if(!t)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(n){e=!1}e&&(m=function(e,r){var n;return t?n=new self.CustomEvent(e,{detail:r,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(n=document.createEvent("CustomEvent"),n.initCustomEvent(e,!1,!0,r)),n?!self.dispatchEvent(n):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,r){var n=o[t],i=self[n];return i?("rejectionHandled"===t?i.call(self,r):i.call(self,e,r),!0):!1}}();return"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(l=function(t){console.warn(t)},p.isNode&&process.stderr.isTTY?l=function(t){process.stderr.write(""+t+"\n")}:p.isNode||"string"!=typeof(new Error).stack||(l=function(t){console.warn("%c"+t,"color: red")})),e}},{"./async.js":2,"./util.js":38}],8:[function(t,e){"use strict";e.exports=function(e){function r(t,e,r){this._instances=t,this._callback=e,this._promise=r}function n(t,e){var r={},n=s(t).call(r,e);if(n===a)return n;var i=u(r);return i.length?(a.e=new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"),a):n}var i=t("./util.js"),o=t("./errors.js"),s=i.tryCatch,a=i.errorObj,u=t("./es5.js").keys,c=o.TypeError;return r.prototype.doFilter=function(t){for(var r=this._callback,i=this._promise,o=i._boundTo,u=0,c=this._instances.length;c>u;++u){var l=this._instances[u],h=l===Error||null!=l&&l.prototype instanceof Error;if(h&&t instanceof l){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}if("function"==typeof l&&!h){var f=n(l,t);if(f===a){t=a.e;break}if(f){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}}}return e.e=t,e},r}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(t,e){"use strict";e.exports=function(t,e,r){function n(){this._trace=new e(o())}function i(){return r()?new n:void 0}function o(){var t=s.length-1;return t>=0?s[t]:void 0}var s=[];return n.prototype._pushContext=function(){r()&&void 0!==this._trace&&s.push(this._trace)},n.prototype._popContext=function(){r()&&void 0!==this._trace&&s.pop()},t.prototype._peekContext=o,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,i}},{}],10:[function(t,e){"use strict";e.exports=function(e,r){var n,i,o=t("./async.js"),s=t("./errors.js").Warning,a=t("./util.js"),u=a.canAttachTrace,c=!1||a.isNode&&(!!process.env.BLUEBIRD_DEBUG||"development"===process.env.NODE_ENV);return c&&o.disableTrampolineIfNecessary(),e.prototype._ensurePossibleRejectionHandled=function(){this._setRejectionIsUnhandled(),o.invokeLater(this._notifyUnhandledRejection,this,void 0)},e.prototype._notifyUnhandledRejectionIsHandled=function(){r.fireRejectionEvent("rejectionHandled",n,void 0,this)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified(),r.fireRejectionEvent("unhandledRejection",i,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},e.prototype._setCarriedStackTrace=function(t){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=t},e.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},e.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},e.prototype._captureStackTrace=function(){return c&&(this._trace=new r(this._peekContext())),this},e.prototype._attachExtraTrace=function(t,e){if(c&&u(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var i=r.parseStackAndMessage(t);a.notEnumerableProp(t,"stack",i.message+"\n"+i.stack.join("\n")),a.notEnumerableProp(t,"__stackCleaned__",!0)}}},e.prototype._warn=function(t){var e=new s(t),n=this._peekContext();if(n)n.attachExtraTrace(e);else{var i=r.parseStackAndMessage(e);e.stack=i.message+"\n"+i.stack.join("\n")}r.formatAndLogError(e,"")},e.onPossiblyUnhandledRejection=function(t){i="function"==typeof t?t:void 0},e.onUnhandledRejectionHandled=function(t){n="function"==typeof t?t:void 0},e.longStackTraces=function(){if(o.haveItemsQueued()&&c===!1)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n");c=r.isSupported(),c&&o.disableTrampolineIfNecessary()},e.hasLongStackTraces=function(){return c&&r.isSupported()},r.isSupported()||(e.longStackTraces=function(){},c=!1),function(){return c}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(t,e){"use strict";var r=t("./util.js"),n=r.isPrimitive,i=r.wrapsPrimitiveReceiver;e.exports=function(t){var e=function(){return this},r=function(){throw this},o=function(t,e){return 1===e?function(){throw t}:2===e?function(){return t}:void 0};t.prototype["return"]=t.prototype.thenReturn=function(t){return i&&n(t)?this._then(o(t,2),void 0,void 0,void 0,void 0):this._then(e,void 0,void 0,t,void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return i&&n(t)?this._then(o(t,1),void 0,void 0,void 0,void 0):this._then(r,void 0,void 0,t,void 0)}}},{"./util.js":38}],12:[function(t,e){"use strict";e.exports=function(t,e){var r=t.reduce;t.prototype.each=function(t){return r(this,t,null,e)},t.each=function(t,n){return r(t,n,null,e)}}},{}],13:[function(t,e){"use strict";function r(t,e){function r(n){return this instanceof r?(l(this,"message","string"==typeof n?n:e),l(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new r(n)}return c(r,Error),r}function n(t){return this instanceof n?(l(this,"name","OperationalError"),l(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(l(this,"message",t.message),l(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new n(t)}var i,o,s=t("./es5.js"),a=s.freeze,u=t("./util.js"),c=u.inherits,l=u.notEnumerableProp,h=r("Warning","warning"),p=r("CancellationError","cancellation error"),f=r("TimeoutError","timeout error"),_=r("AggregateError","aggregate error");try{i=TypeError,o=RangeError}catch(d){i=r("TypeError","type error"),o=r("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y0&&"function"==typeof arguments[e]){t=arguments[e];var n}for(var i=arguments.length,o=new Array(i),s=0;i>s;++s)o[s]=arguments[s];t&&o.pop();var n=new r(o).promise();return void 0!==t?n.spread(t):n}}},{"./util.js":38}],19:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace(),this._callback=e,this._preservedValues=n===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=r>=1?[]:_,c.invoke(a,this,void 0)}function a(){this._init$(void 0,-2)}function u(t,e,r,n){var i="object"==typeof r&&null!==r?r.concurrency:0;return i="number"==typeof i&&isFinite(i)&&i>=1?i:0,new s(t,e,i,n)}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj,f={},_=[];l.inherits(s,r),s.prototype._init=function(){},s.prototype._promiseFulfilled=function(t,r){var n=this._values,o=this.length(),s=this._preservedValues,a=this._limit;if(n[r]===f){if(n[r]=t,a>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return}else{if(a>=1&&this._inFlight>=a)return n[r]=t,void this._queue.push(r);null!==s&&(s[r]=t);var u=this._callback,c=this._promise._boundTo;this._promise._pushContext();var l=h(u).call(c,t,r,o);if(this._promise._popContext(),l===p)return this._reject(l.e);var _=i(l,this._promise);if(_ instanceof e){if(_=_._target(),_._isPending())return a>=1&&this._inFlight++,n[r]=f,_._proxyPromiseArray(this,r);if(!_._isFulfilled())return this._reject(_._reason());l=_._value()}n[r]=l}var d=++this._totalResolved;d>=o&&(null!==s?this._filter(n,s):this._resolve(n))},s.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},s.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return"function"!=typeof t?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(this,t,e,null).promise()},e.map=function(t,e,r,i){return"function"!=typeof e?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(t,e,r,i).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(t,e){"use strict";e.exports=function(e,r,n,i){var o=t("./util.js"),s=o.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");return function(){var n=new e(r);n._captureStackTrace(),n._pushContext();var i=s(t).apply(this,arguments);return n._popContext(),n._resolveFromSyncValue(i),n}},e.attempt=e["try"]=function(t,n,a){if("function"!=typeof t)return i("fn must be a function\n\n See http://goo.gl/916lJJ\n");var u=new e(r);u._captureStackTrace(),u._pushContext();var c=o.isArray(n)?s(t).apply(a,n):s(t).call(a,n);return u._popContext(),u._resolveFromSyncValue(c),u},e.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1,!0):this._resolveCallback(t,!0)}}},{"./util.js":38}],21:[function(t,e){"use strict";e.exports=function(e){function r(t,e){var r=this;if(!o.isArray(t))return n.call(r,t,e);var i=a(e).apply(r._boundTo,[null].concat(t));i===u&&s.throwLater(i.e)}function n(t,e){var r=this,n=r._boundTo,i=void 0===t?a(e).call(n,null):a(e).call(n,null,t);i===u&&s.throwLater(i.e)}function i(t,e){var r=this;if(!t){var n=r._target(),i=n._getCarriedStackTrace();i.cause=t,t=i}var o=a(e).call(r._boundTo,t);o===u&&s.throwLater(o.e)}var o=t("./util.js"),s=t("./async.js"),a=o.tryCatch,u=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=n;void 0!==e&&Object(e).spread&&(o=r),this._then(o,i,void 0,this,t)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(t,e){"use strict";e.exports=function(e,r){var n=t("./util.js"),i=t("./async.js"),o=n.tryCatch,s=n.errorObj;e.prototype.progressed=function(t){return this._then(void 0,void 0,t,void 0,void 0)},e.prototype._progress=function(t){this._isFollowingOrFulfilledOrRejected()||this._target()._progressUnchecked(t)},e.prototype._progressHandlerAt=function(t){return 0===t?this._progressHandler0:this[(t<<2)+t-5+2]},e.prototype._doProgressWith=function(t){var r=t.value,i=t.handler,a=t.promise,u=t.receiver,c=o(i).call(u,r);if(c===s){if(null!=c.e&&"StopProgressPropagation"!==c.e.name){var l=n.canAttachTrace(c.e)?c.e:new Error(n.toString(c.e));a._attachExtraTrace(l),a._progress(c.e)}}else c instanceof e?c._then(a._progress,null,null,a,void 0):a._progress(c)},e.prototype._progressUnchecked=function(t){for(var n=this._length(),o=this._progress,s=0;n>s;s++){var a=this._progressHandlerAt(s),u=this._promiseAt(s);if(u instanceof e)"function"==typeof a?i.invoke(this._doProgressWith,this,{handler:a,promise:u,receiver:this._receiverAt(s),value:t}):i.invoke(o,u,t);else{var c=this._receiverAt(s);"function"==typeof a?a.call(c,t,u):c instanceof r&&!c._isResolved()&&c._promiseProgressed(t,u)}}}}},{"./async.js":2,"./util.js":38}],23:[function(t,e){"use strict";e.exports=function(){function e(t){if("function"!=typeof t)throw new c("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n");if(this.constructor!==e)throw new c("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._progressHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,t!==l&&this._resolveFromResolver(t)}function r(t){var r=new e(l);r._fulfillmentHandler0=t,r._rejectionHandler0=t,r._progressHandler0=t,r._promise0=t,r._receiver0=t,r._settledValue=t}var n=function(){return new c("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")},i=function(){return new e.PromiseInspection(this._target())},o=function(t){return e.reject(new c(t))},s=t("./util.js"),a=t("./async.js"),u=t("./errors.js"),c=e.TypeError=u.TypeError;e.RangeError=u.RangeError,e.CancellationError=u.CancellationError,e.TimeoutError=u.TimeoutError,e.OperationalError=u.OperationalError,e.RejectionError=u.OperationalError,e.AggregateError=u.AggregateError;var l=function(){},h={},p={e:null},f=t("./thenables.js")(e,l),_=t("./promise_array.js")(e,l,f,o),d=t("./captured_trace.js")(),v=t("./debuggability.js")(e,d),y=t("./context.js")(e,d,v),g=t("./catch_filter.js")(p),m=t("./promise_resolver.js"),j=m._nodebackForPromise,b=s.errorObj,w=s.tryCatch;return e.prototype.toString=function(){return"[object Promise]"},e.prototype.caught=e.prototype["catch"]=function(t){var r=arguments.length;if(r>1){var n,i=new Array(r-1),o=0;for(n=0;r-1>n;++n){var s=arguments[n];if("function"!=typeof s)return e.reject(new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"));i[o++]=s}i.length=o,t=arguments[n];var a=new g(i,t,this);return this._then(void 0,a.doFilter,void 0,a,void 0)}return this._then(void 0,t,void 0,void 0,void 0)},e.prototype.reflect=function(){return this._then(i,i,void 0,this,void 0)},e.prototype.then=function(t,e,r){if(v()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+s.classString(t); -arguments.length>1&&(n+=", "+s.classString(e)),this._warn(n)}return this._then(t,e,r,void 0,void 0)},e.prototype.done=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);n._setIsFinal()},e.prototype.spread=function(t,e){return this.all()._then(t,e,void 0,h,void 0)},e.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable()},e.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},e.prototype.all=function(){return new _(this).promise()},e.prototype.error=function(t){return this.caught(s.originatesFromRejection,t)},e.is=function(t){return t instanceof e},e.fromNode=function(t){var r=new e(l),n=w(t)(j(r));return n===b&&r._rejectCallback(n.e,!0,!0),r},e.all=function(t){return new _(t).promise()},e.defer=e.pending=function(){var t=new e(l);return new m(t)},e.cast=function(t){var r=f(t);if(!(r instanceof e)){var n=r;r=new e(l),r._fulfillUnchecked(n)}return r},e.resolve=e.fulfilled=e.cast,e.reject=e.rejected=function(t){var r=new e(l);return r._captureStackTrace(),r._rejectCallback(t,!0),r},e.setScheduler=function(t){if("function"!=typeof t)throw new c("fn must be a function\n\n See http://goo.gl/916lJJ\n");var e=a._schedule;return a._schedule=t,e},e.prototype._then=function(t,r,n,i,o){var s=void 0!==o,u=s?o:new e(l);s||(u._propagateFrom(this,5),u._captureStackTrace());var c=this._target();c!==this&&(void 0===i&&(i=this._boundTo),s||u._setIsMigrated());var h=c._addCallbacks(t,r,n,u,i);return c._isResolved()&&!c._isSettlePromisesQueued()&&a.invoke(c._settlePromiseAtPostResolution,c,h),u},e.prototype._settlePromiseAtPostResolution=function(t){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),this._settlePromiseAt(t)},e.prototype._length=function(){return 131071&this._bitField},e.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},e.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},e.prototype._setLength=function(t){this._bitField=-131072&this._bitField|131071&t},e.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},e.prototype._setRejected=function(){this._bitField=134217728|this._bitField},e.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},e.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},e.prototype._isFinal=function(){return(33554432&this._bitField)>0},e.prototype._cancellable=function(){return(67108864&this._bitField)>0},e.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},e.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},e.prototype._setIsMigrated=function(){this._bitField=4194304|this._bitField},e.prototype._unsetIsMigrated=function(){this._bitField=-4194305&this._bitField},e.prototype._isMigrated=function(){return(4194304&this._bitField)>0},e.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[5*t-5+4];return void 0===e&&this._isBound()?this._boundTo:e},e.prototype._promiseAt=function(t){return 0===t?this._promise0:this[5*t-5+3]},e.prototype._fulfillmentHandlerAt=function(t){return 0===t?this._fulfillmentHandler0:this[5*t-5+0]},e.prototype._rejectionHandlerAt=function(t){return 0===t?this._rejectionHandler0:this[5*t-5+1]},e.prototype._migrateCallbacks=function(t,r){var n=t._fulfillmentHandlerAt(r),i=t._rejectionHandlerAt(r),o=t._progressHandlerAt(r),s=t._promiseAt(r),a=t._receiverAt(r);s instanceof e&&s._setIsMigrated(),this._addCallbacks(n,i,o,s,a)},e.prototype._addCallbacks=function(t,e,r,n,i){var o=this._length();if(o>=131066&&(o=0,this._setLength(0)),0===o)this._promise0=n,void 0!==i&&(this._receiver0=i),"function"!=typeof t||this._isCarryingStackTrace()||(this._fulfillmentHandler0=t),"function"==typeof e&&(this._rejectionHandler0=e),"function"==typeof r&&(this._progressHandler0=r);else{var s=5*o-5;this[s+3]=n,this[s+4]=i,"function"==typeof t&&(this[s+0]=t),"function"==typeof e&&(this[s+1]=e),"function"==typeof r&&(this[s+2]=r)}return this._setLength(o+1),o},e.prototype._setProxyHandlers=function(t,e){var r=this._length();if(r>=131066&&(r=0,this._setLength(0)),0===r)this._promise0=e,this._receiver0=t;else{var n=5*r-5;this[n+3]=e,this[n+4]=t}this._setLength(r+1)},e.prototype._proxyPromiseArray=function(t,e){this._setProxyHandlers(t,e)},e.prototype._resolveCallback=function(t,r){if(!this._isFollowingOrFulfilledOrRejected()){if(t===this)return this._rejectCallback(n(),!1,!0);var i=f(t,this);if(!(i instanceof e))return this._fulfill(t);var o=1|(r?4:0);this._propagateFrom(i,o);var s=i._target();if(s._isPending()){for(var a=this._length(),u=0;a>u;++u)s._migrateCallbacks(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(s)}else s._isFulfilled()?this._fulfillUnchecked(s._value()):this._rejectUnchecked(s._reason(),s._getCarriedStackTrace())}},e.prototype._rejectCallback=function(t,e,r){r||s.markAsOriginatingFromRejection(t);var n=s.ensureErrorObject(t),i=n===t;this._attachExtraTrace(n,e?i:!1),this._reject(t,i?void 0:n)},e.prototype._resolveFromResolver=function(t){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=w(t)(function(t){null!==e&&(e._resolveCallback(t),e=null)},function(t){null!==e&&(e._rejectCallback(t,r),e=null)});r=!1,this._popContext(),void 0!==n&&n===b&&null!==e&&(e._rejectCallback(n.e,!0,!0),e=null)},e.prototype._settlePromiseFromHandler=function(t,e,r,i){if(!i._isRejected()){i._pushContext();var o;if(o=e!==h||this._isRejected()?w(t).call(e,r):w(t).apply(this._boundTo,r),i._popContext(),o===b||o===i||o===p){var s=o===i?n():o.e;i._rejectCallback(s,!1,!0)}else i._resolveCallback(o)}},e.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},e.prototype._followee=function(){return this._rejectionHandler0},e.prototype._setFollowee=function(t){this._rejectionHandler0=t},e.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},e.prototype._propagateFrom=function(t,e){(1&e)>0&&t._cancellable()&&(this._setCancellable(),this._cancellationParent=t),(4&e)>0&&t._isBound()&&this._setBoundTo(t._boundTo)},e.prototype._fulfill=function(t){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(t)},e.prototype._reject=function(t,e){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(t,e)},e.prototype._settlePromiseAt=function(t){var r=this._promiseAt(t),n=r instanceof e;if(n&&r._isMigrated())return r._unsetIsMigrated(),a.invoke(this._settlePromiseAt,this,t);var i=this._isFulfilled()?this._fulfillmentHandlerAt(t):this._rejectionHandlerAt(t),o=this._isCarryingStackTrace()?this._getCarriedStackTrace():void 0,s=this._settledValue,u=this._receiverAt(t);this._clearCallbackDataAtIndex(t),"function"==typeof i?n?this._settlePromiseFromHandler(i,u,s,r):i.call(u,s,r):u instanceof _?u._isResolved()||(this._isFulfilled()?u._promiseFulfilled(s,r):u._promiseRejected(s,r)):n&&(this._isFulfilled()?r._fulfill(s):r._reject(s,o)),t>=4&&4===(31&t)&&a.invokeLater(this._setLength,this,0)},e.prototype._clearCallbackDataAtIndex=function(t){if(0===t)this._isCarryingStackTrace()||(this._fulfillmentHandler0=void 0),this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=void 0;else{var e=5*t-5;this[e+3]=this[e+4]=this[e+0]=this[e+1]=this[e+2]=void 0}},e.prototype._isSettlePromisesQueued=function(){return-1073741824===(-1073741824&this._bitField)},e.prototype._setSettlePromisesQueued=function(){this._bitField=-1073741824|this._bitField},e.prototype._unsetSettlePromisesQueued=function(){this._bitField=1073741823&this._bitField},e.prototype._queueSettlePromises=function(){a.settlePromises(this),this._setSettlePromisesQueued()},e.prototype._fulfillUnchecked=function(t){if(t===this){var e=n();return this._attachExtraTrace(e),this._rejectUnchecked(e,void 0)}this._setFulfilled(),this._settledValue=t,this._cleanValues(),this._length()>0&&this._queueSettlePromises()},e.prototype._rejectUncheckedCheckError=function(t){var e=s.ensureErrorObject(t);this._rejectUnchecked(t,e===t?void 0:e)},e.prototype._rejectUnchecked=function(t,e){if(t===this){var r=n();return this._attachExtraTrace(r),this._rejectUnchecked(r)}return this._setRejected(),this._settledValue=t,this._cleanValues(),this._isFinal()?void a.throwLater(function(t){throw"stack"in t&&a.invokeFirst(d.unhandledRejection,void 0,t),t},void 0===e?t:e):(void 0!==e&&e!==t&&this._setCarriedStackTrace(e),void(this._length()>0?this._queueSettlePromises():this._ensurePossibleRejectionHandled()))},e.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();for(var t=this._length(),e=0;t>e;e++)this._settlePromiseAt(e)},e._makeSelfResolutionError=n,t("./progress.js")(e,_),t("./method.js")(e,l,f,o),t("./bind.js")(e,l,f),t("./finally.js")(e,p,f),t("./direct_resolve.js")(e),t("./synchronous_inspection.js")(e),t("./join.js")(e,_,f,l),e.Promise=e,t("./map.js")(e,_,o,f,l),t("./cancel.js")(e),t("./using.js")(e,o,f,y),t("./generators.js")(e,o,l,f),t("./nodeify.js")(e),t("./call_get.js")(e),t("./props.js")(e,_,f,o),t("./race.js")(e,l,f,o),t("./reduce.js")(e,_,o,f,l),t("./settle.js")(e,_),t("./some.js")(e,_,o),t("./promisify.js")(e,l),t("./any.js")(e),t("./each.js")(e,l),t("./timers.js")(e,l),t("./filter.js")(e,l),s.toFastProperties(e),s.toFastProperties(e.prototype),r({a:1}),r({b:2}),r({c:3}),r(1),r(function(){}),r(void 0),r(!1),r(new e(l)),d.setBounds(a.firstLineError,s.lastLineError),e}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){switch(t){case-2:return[];case-3:return{}}}function s(t){var n,i=this._promise=new e(r);t instanceof e&&(n=t,i._propagateFrom(n,5)),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var a=t("./util.js"),u=a.isArray;return s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function c(t,r){var s=n(this._values,this._promise);if(s instanceof e){if(s=s._target(),this._values=s,!s._isFulfilled())return s._isPending()?void s._then(c,this._reject,void 0,this,r):void this._reject(s._reason());if(s=s._value(),!u(s)){var a=new e.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");return void this.__hardReject__(a)}}else if(!u(s))return void this._promise._reject(i("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());if(0===s.length)return void(-5===r?this._resolveEmptyArray():this._resolve(o(r)));var l=this.getActualLength(s.length);this._length=l,this._values=this.shouldCopyValues()?new Array(l):this._values;for(var h=this._promise,p=0;l>p;++p){var f=this._isResolved(),_=n(s[p],h);_ instanceof e?(_=_._target(),f?_._unsetRejectionIsUnhandled():_._isPending()?_._proxyPromiseArray(this,p):_._isFulfilled()?this._promiseFulfilled(_._value(),p):this._promiseRejected(_._reason(),p)):f||this._promiseFulfilled(_,p)}},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype.__hardReject__=s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1,!0)},s.prototype._promiseProgressed=function(t,e){this._promise._progress({index:e,value:t})},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},s.prototype._promiseRejected=function(t){this._totalResolved++,this._reject(t)},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util.js":38}],25:[function(t,e){"use strict";function r(t){return t instanceof Error&&p.getPrototypeOf(t)===Error.prototype}function n(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=p.keys(t),i=0;i2){for(var o=arguments.length,s=new Array(o-1),u=1;o>u;++u)s[u-1]=arguments[u];t._fulfill(s)}else t._fulfill(r);t=null}}}var o,s=t("./util.js"),a=s.maybeWrapAsError,u=t("./errors.js"),c=u.TimeoutError,l=u.OperationalError,h=s.haveGetters,p=t("./es5.js"),f=/^(?:name|message|stack|cause)$/;if(o=h?function(t){this.promise=t}:function(t){this.promise=t,this.asCallback=i(t),this.callback=this.asCallback},h){var _={get:function(){return i(this.promise)}};p.defineProperty(o.prototype,"asCallback",_),p.defineProperty(o.prototype,"callback",_)}o._nodebackForPromise=i,o.prototype.toString=function(){return"[object PromiseResolver]"},o.prototype.resolve=o.prototype.fulfill=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._resolveCallback(t)},o.prototype.reject=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._rejectCallback(t)},o.prototype.progress=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._progress(t)},o.prototype.cancel=function(t){this.promise.cancel(t)},o.prototype.timeout=function(){this.reject(new c("timeout"))},o.prototype.isResolved=function(){return this.promise.isResolved()},o.prototype.toJSON=function(){return this.promise.toJSON()},e.exports=o},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(t,e){"use strict";e.exports=function(e,r){function n(t){return!b.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,r){var n=f.getDataPropertyOrDefault(t,e+r,j);return n?i(n):!1}function s(t,e,r){for(var n=0;ns;s+=2){var c=o[s],l=o[s+1],h=c+e;t[h]=n===E?E(c,p,c,l,e):n(l,function(){return E(c,p,c,l,e)})}return f.toFastProperties(t),t}function l(t,e){return E(t,e,void 0,t)}var h,p={},f=t("./util.js"),_=t("./promise_resolver.js")._nodebackForPromise,d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,g=t("./errors").TypeError,m="Async",j={__isPromisified__:!0},b=/^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/,w=function(t,e){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&!f.isClass(e)},k=function(t){return t.replace(/([$])/,"\\$")},E=y?h:u;e.promisify=function(t,e){if("function"!=typeof t)throw new g("fn must be a function\n\n See http://goo.gl/916lJJ\n");if(i(t))return t;var r=l(t,arguments.length<2?p:e);return f.copyDescriptors(t,r,n),r},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new g("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n");e=Object(e);var r=e.suffix;"string"!=typeof r&&(r=m);var n=e.filter;"function"!=typeof n&&(n=w);var i=e.promisifier;if("function"!=typeof i&&(i=E),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n");for(var o=f.inheritedDataKeys(t),s=0;si;++i){var o=e[i];n[i]=t[o],n[i+r]=o}this.constructor$(n)}function s(t){var r,s=n(t);return u(s)?(r=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&r._propagateFrom(s,4),r):i("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}var a=t("./util.js"),u=a.isObject,c=t("./es5.js");a.inherits(o,r),o.prototype._init=function(){this._init$(void 0,-3)},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;if(r>=this._length){for(var n={},i=this.length(),o=0,s=this.length();s>o;++o)n[this._values[o+i]]=this._values[o];this._resolve(n)}},o.prototype._promiseProgressed=function(t,e){this._promise._progress({key:this._values[e+this.length()],value:t})},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5.js":14,"./util.js":38}],28:[function(t,e){"use strict";function r(t,e,r,n,i){for(var o=0;i>o;++o)r[o+n]=t[o+e],t[o+e]=void 0}function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacityp;++p){var _=t[p];(void 0!==_||p in t)&&e.cast(_)._then(l,h,void 0,c,null)}return c}var s=t("./util.js").isArray,a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util.js":38}],30:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,r,n,s){this.constructor$(t),this._promise._captureStackTrace(),this._preservedValues=s===o?[]:null,this._zerothIsAccum=void 0===n,this._gotAccum=!1,this._reducingIndex=this._zerothIsAccum?1:0,this._valuesPhase=void 0;var u=i(n,this._promise),l=!1,h=u instanceof e;h&&(u=u._target(),u._isPending()?u._proxyPromiseArray(this,-1):u._isFulfilled()?(n=u._value(),this._gotAccum=!0):(this._reject(u._reason()),l=!0)),h||this._zerothIsAccum||(this._gotAccum=!0),this._callback=r,this._accum=n,l||c.invoke(a,this,void 0)}function a(){this._init$(void 0,-5)}function u(t,e,r,i){if("function"!=typeof e)return n("fn must be a function\n\n See http://goo.gl/916lJJ\n");var o=new s(t,e,r,i);return o.promise()}var c=t("./async.js"),l=t("./util.js"),h=l.tryCatch,p=l.errorObj;l.inherits(s,r),s.prototype._init=function(){},s.prototype._resolveEmptyArray=function(){(this._gotAccum||this._zerothIsAccum)&&this._resolve(null!==this._preservedValues?[]:this._accum)},s.prototype._promiseFulfilled=function(t,r){var n=this._values;n[r]=t;var o,s=this.length(),a=this._preservedValues,u=null!==a,c=this._gotAccum,l=this._valuesPhase;if(!l)for(l=this._valuesPhase=new Array(s),o=0;s>o;++o)l[o]=0;if(o=l[r],0===r&&this._zerothIsAccum?(this._accum=t,this._gotAccum=c=!0,l[r]=0===o?1:2):-1===r?(this._accum=t,this._gotAccum=c=!0):0===o?l[r]=1:(l[r]=2,this._accum=t),c){for(var f,_=this._callback,d=this._promise._boundTo,v=this._reducingIndex;s>v;++v)if(o=l[v],2!==o){if(1!==o)return;if(t=n[v],this._promise._pushContext(),u?(a.push(t),f=h(_).call(d,t,v,s)):f=h(_).call(d,this._accum,t,v,s),this._promise._popContext(),f===p)return this._reject(f.e);var y=i(f,this._promise);if(y instanceof e){if(y=y._target(),y._isPending())return l[v]=4,y._proxyPromiseArray(this,v);if(!y._isFulfilled())return this._reject(y._reason());f=y._value()}this._reducingIndex=v+1,this._accum=f}else this._reducingIndex=v+1;this._resolve(u?a:this._accum)}},e.prototype.reduce=function(t,e){return u(this,t,e,null)},e.reduce=function(t,e,r,n){return u(t,e,r,n)}}},{"./async.js":2,"./util.js":38}],31:[function(t,e){"use strict";var r,n=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(t("./util.js").isNode){var i=process.versions.node.split(".").map(Number);r=0===i[0]&&i[1]>10||i[0]>0?global.setImmediate:process.nextTick,r||(r="undefined"!=typeof setImmediate?setImmediate:"undefined"!=typeof setTimeout?setTimeout:n)}else"undefined"!=typeof MutationObserver?(r=function(t){var e=document.createElement("div"),r=new MutationObserver(t);return r.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},r.isStatic=!0):r="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:n;e.exports=r},{"./util.js":38}],32:[function(t,e){"use strict";e.exports=function(e,r){function n(t){this.constructor$(t)}var i=e.PromiseInspection,o=t("./util.js");o.inherits(n,r),n.prototype._promiseResolved=function(t,e){this._values[t]=e;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},n.prototype._promiseFulfilled=function(t,e){var r=new i;r._bitField=268435456,r._settledValue=t,this._promiseResolved(e,r)},n.prototype._promiseRejected=function(t,e){var r=new i;r._bitField=134217728,r._settledValue=t,this._promiseResolved(e,r)},e.settle=function(t){return new n(t).promise()},e.prototype.settle=function(){return new n(this).promise()}}},{"./util.js":38}],33:[function(t,e){"use strict";e.exports=function(e,r,n){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return n("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n");var r=new i(t),o=r.promise();return r.setHowMany(e),r.init(),o}var s=t("./util.js"),a=t("./errors.js").RangeError,u=t("./errors.js").AggregateError,c=s.isArray;s.inherits(i,r),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),this._resolve(1===this.howMany()&&this._unwrap?this._values[0]:this._values))},i.prototype._promiseRejected=function(t){if(this._addRejected(t),this.howMany()>this._canPossiblyFulfill()){for(var e=new u,r=this.length();r0},e.prototype.isRejected=t.prototype._isRejected=function(){return(134217728&this._bitField)>0},e.prototype.isPending=t.prototype._isPending=function(){return 0===(402653184&this._bitField)},e.prototype.isResolved=t.prototype._isResolved=function(){return(402653184&this._bitField)>0},t.prototype.isPending=function(){return this._target()._isPending()},t.prototype.isRejected=function(){return this._target()._isRejected()},t.prototype.isFulfilled=function(){return this._target()._isFulfilled()},t.prototype.isResolved=function(){return this._target()._isResolved()},t.prototype._value=function(){return this._settledValue},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue},t.prototype.value=function(){var t=this._target();if(!t.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return t._settledValue},t.prototype.reason=function(){var t=this._target();if(!t.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return t._unsetRejectionIsUnhandled(),t._settledValue},t.PromiseInspection=e}},{}],35:[function(t,e){"use strict";e.exports=function(e,r){function n(t,n){if(c(t)){if(t instanceof e)return t;if(o(t)){var l=new e(r);return t._then(l._fulfillUnchecked,l._rejectUncheckedCheckError,l._progressUnchecked,l,null),l}var h=a.tryCatch(i)(t);if(h===u){n&&n._pushContext();var l=e.reject(h.e);return n&&n._popContext(),l}if("function"==typeof h)return s(t,h,n)}return t}function i(t){return t.then}function o(t){return l.call(t,"_promise0")}function s(t,n,i){function o(r){l&&(t===r?l._rejectCallback(e._makeSelfResolutionError(),!1,!0):l._resolveCallback(r),l=null)}function s(t){l&&(l._rejectCallback(t,p,!0),l=null)}function c(t){l&&"function"==typeof l._progress&&l._progress(t)}var l=new e(r),h=l;i&&i._pushContext(),l._captureStackTrace(),i&&i._popContext();var p=!0,f=a.tryCatch(n).call(t,o,s,c);return p=!1,l&&f===u&&(l._rejectCallback(f.e,!0,!0),l=null),h}var a=t("./util.js"),u=a.errorObj,c=a.isObject,l={}.hasOwnProperty;return n}},{"./util.js":38}],36:[function(t,e){"use strict";e.exports=function(e,r){function n(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util.js"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){"string"!=typeof e&&(e="operation timed out");var r=new s(e);o.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._cancel(r)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,n){if(void 0===n){n=t,t=void 0;var i=new e(r);return setTimeout(function(){i._fulfill()},n),i}return n=+n,e.resolve(t)._then(u,null,null,n,void 0)};e.prototype.delay=function(t){return c(this,t)},e.prototype.timeout=function(t,e){t=+t;var r=this.then().cancellable();r._cancellationParent=this;var o=setTimeout(function(){a(r,e)},t);return r._then(n,i,void 0,o,void 0)}}},{"./util.js":38}],37:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){for(var r=t.length,n=0;r>n;++n){var i=t[n];if(i.isRejected())return e.reject(i.error());t[n]=i._settledValue}return t}function s(t){setTimeout(function(){throw t},0)}function a(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function u(t,r){function i(){if(o>=u)return c.resolve();var l=a(t[o++]);if(l instanceof e&&l._isDisposable()){try{l=n(l._getDisposer().tryDispose(r),t.promise)}catch(h){return s(h)}if(l instanceof e)return l._then(i,s,null,null,null)}i()}var o=0,u=t.length,c=e.defer();return i(),c.promise}function c(t){var e=new v;return e._settledValue=t,e._bitField=268435456,u(this,e).thenReturn(t)}function l(t){var e=new v;return e._settledValue=t,e._bitField=134217728,u(this,e).thenThrow(t)}function h(t,e,r){this._data=t,this._promise=e,this._context=r}function p(t,e,r){this.constructor$(t,e,r)}function f(t){return h.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}var _=t("./errors.js").TypeError,d=t("./util.js").inherits,v=e.PromiseInspection;h.prototype.data=function(){return this._data},h.prototype.promise=function(){return this._promise},h.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},h.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=null!==e?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},h.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},d(p,h),p.prototype.doDispose=function(t,e){var r=this.data();return r.call(t,t,e)},e.using=function(){var t=arguments.length;if(2>t)return r("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return r("fn must be a function\n\n See http://goo.gl/916lJJ\n");t--;for(var s=new Array(t),a=0;t>a;++a){var u=arguments[a];if(h.isDisposer(u)){var p=u;u=u.promise(),u._setDisposable(p)}else{var _=n(u);_ instanceof e&&(u=_._then(f,null,null,{resources:s,index:a},void 0))}s[a]=u}var d=e.settle(s).then(o).then(function(t){d._pushContext();var e;try{e=i.apply(void 0,t)}finally{d._popContext()}return e})._then(c,l,void 0,s,void 0);return s.promise=d,d},e.prototype._setDisposable=function(t){this._bitField=262144|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(262144&this._bitField)>0 -},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-262145&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new _}}},{"./errors.js":13,"./util.js":38}],38:[function(t,e,r){"use strict";function n(){try{return T.apply(this,arguments)}catch(t){return F.e=t,F}}function i(t){return T=t,n}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return!o(t)}function a(t){return o(t)?new Error(v(t)):t}function u(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;n>r;++r)i[r]=t[r];return i[r]=e,i}function c(t,e,r){if(!w.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var n=Object.getOwnPropertyDescriptor(t,e);return null!=n?null==n.get&&null==n.set?n.value:r:void 0}function l(t,e,r){if(o(t))return t;var n={value:r,configurable:!0,enumerable:!1,writable:!0};return w.defineProperty(t,e,n),t}function h(t){throw t}function p(t){try{if("function"==typeof t){var e=w.names(t.prototype);return w.isES5?e.length>1:e.length>0&&!(1===e.length&&"constructor"===e[0])}return!1}catch(r){return!1}}function f(t){function e(){}e.prototype=t;for(var r=8;r--;)new e;return t}function _(t){return R.test(t)}function d(t,e,r){for(var n=new Array(t),i=0;t>i;++i)n[i]=e+i+r;return n}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){try{l(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function m(t){return t instanceof Error&&w.propertyIsWritable(t,"stack")}function j(t){return{}.toString.call(t)}function b(t,e,r){for(var n=w.names(t),i=0;it||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},r.prototype.emit=function(t){var e,r,i,a,u,c;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(n(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];r.apply(this,a)}else if(o(r)){for(i=arguments.length,a=new Array(i-1),u=1;i>u;u++)a[u-1]=arguments[u];for(c=r.slice(),i=c.length,u=0;i>u;u++)c[u].apply(this,a)}return!0},r.prototype.addListener=function(t,e){var i;if(!n(e))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,n(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned){var i;i=s(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,i&&i>0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())}return this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(t,e){function r(){this.removeListener(t,r),i||(i=!0,e.apply(this,arguments))}if(!n(e))throw TypeError("listener must be a function");var i=!1;return r.listener=e,this.on(t,r),this},r.prototype.removeListener=function(t,e){var r,i,s,a;if(!n(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],s=r.length,i=-1,r===e||n(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(a=s;a-->0;)if(r[a]===e||r[a].listener&&r[a].listener===e){i=a;break}if(0>i)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(i,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},r.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],n(r))this.removeListener(t,r);else for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},r.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?n(this._events[t])?[this._events[t]]:this._events[t].slice():[]},r.listenerCount=function(t,e){var r;return r=t._events&&t._events[e]?n(t._events[e])?1:t._events[e].length:0}},{}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(s,a){if(!e[s]){if(!t[s]){var c="function"==typeof _dereq_&&_dereq_;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},n.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},n.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},n.prototype._reset=function(){this._isTickUsed=!1},e.exports=n,e.exports.firstLineError=s},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,s,void 0,u,h),l._then(a,c,void 0,u,h),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e){"use strict";function n(){try{Promise===i&&(Promise=r)}catch(t){}return i}var r;"undefined"!=typeof Promise&&(r=Promise);var i=t("./promise")();i.noConflict=n,e.exports=i},{"./promise":22}],5:[function(t,e){"use strict";var n=Object.create;if(n){var r=n(null),i=n(null);r[" size"]=i[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}{var s,a=t("./util"),c=a.canEvaluate;a.isIdentifier}e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(c){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t.isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n.isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this.isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],9:[function(t,e){"use strict";e.exports=function(e,n){function r(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function i(t){if(!this.isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function o(){return this._onCancelField}function s(t){this._onCancelField=t}function a(){this._cancellationParent=void 0,this._onCancelField=void 0}function c(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function l(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function u(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function p(){this._trace=new P(this._peekContext())}function h(t,e){if(I(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=w(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function f(t,e,n,r){if(void 0===t&&null!==e&&Y.longStackTraces&&Y.warnings){var i="a promise was created in a "+n+" handler but was not returned from it";r._warn(i,!0,e)}}function _(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),d(n)}function d(t,n,r){if(Y.warnings){var i,o=new V(t);if(n)r._attachExtraTrace(o);else if(Y.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=w(o);o.stack=s.message+"\n"+s.stack.join("\n")}C(o,"",!0)}}function v(t,e){for(var n=0;n=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var c=r[a];if(e[i]!==c)break;e.pop(),i--}e=r}}function m(t){for(var e=[],n=0;n0&&(e=e.slice(n)),e}function w(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?b(t):[" (No stack trace)"],{message:n,stack:m(e)}}function C(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+U(i,t)}else r=e+String(t);"function"==typeof O?O(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function j(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){D.throwLater(o)}var s=!1;try{s=J(t,n,r)}catch(o){s=!0,D.throwLater(o)}var a=!1;if(W)try{a=W(t.toLowerCase(),{reason:n,promise:r})}catch(o){a=!0,D.throwLater(o)}s||i||a||"unhandledRejection"!==t||C(n,"Unhandled rejection ")}function k(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+F(e)+">, no stack trace)"}function F(t){var e=41;return t.lengths||0>a||!n||!r||n!==r||s>=a||(X=function(t){if(L.test(t))return!0;var e=x(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function P(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);K(this,P),e>32&&this.uncycle()}var R,S,O,A=e._getDomain,D=e._async,V=t("./errors").Warning,H=t("./util"),I=H.canAttachTrace,L=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,N=null,U=null,M=!1,B=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),q=!(0==H.env("BLUEBIRD_WARNINGS")||!B&&!H.env("BLUEBIRD_WARNINGS")),Q=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!B&&!H.env("BLUEBIRD_LONG_STACK_TRACES"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|2097152},e.prototype._ensurePossibleRejectionHandled=function(){0===(2097152&this._bitField)&&(this._setRejectionIsUnhandled(),D.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){j("rejectionHandled",R,void 0,this)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),j("unhandledRejection",S,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return d(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=A();S="function"==typeof t?null===e?t:e.bind(t):void 0},e.onUnhandledRejectionHandled=function(t){var e=A();R="function"==typeof t?null===e?t:e.bind(t):void 0};var $=function(){};e.longStackTraces=function(){if(D.haveItemsQueued()&&!Y.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!Y.longStackTraces&&E()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;Y.longStackTraces=!0,$=function(){if(D.haveItemsQueued()&&!Y.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),D.enableTrampoline(),Y.longStackTraces=!1},e.prototype._captureStackTrace=p,e.prototype._attachExtraTrace=h,n.activateLongStackTraces(),D.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return Y.longStackTraces&&E()},e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&$()),"warnings"in t&&(Y.warnings=!!t.warnings),"cancellation"in t&&t.cancellation&&!Y.cancellation){if(D.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=a,e.prototype._propagateFrom=c,e.prototype._onCancel=o,e.prototype._setOnCancel=s,e.prototype._attachCancellationCallback=i,e.prototype._execute=r,z=c,Y.cancellation=!0}},e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(){},e.prototype._attachCancellationCallback=function(){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(){};var z=l,X=function(){return!1},G=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(P,Error),n.CapturedTrace=P,P.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>a?(c._parent=e[a+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},P.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=w(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(m(i.stack.split("\n"))),i=i._parent;g(r),y(r),H.notEnumerableProp(t,"stack",v(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var W,K=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():k(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,N=t,U=e;var n=Error.captureStackTrace;return X=function(t){return L.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return N=/@/,U=e,M=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(U=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?k(e):e.toString()},null):(N=t,U=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]),J=function(){if(H.isNode)return function(t,e,n){return"rejectionHandled"===t?process.emit(t,n):process.emit(t,e,n)};var t=!1,e=!0;try{var n=new self.CustomEvent("test");t=n instanceof CustomEvent}catch(r){}if(!t)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(r){e=!1}e&&(W=function(e,n){var r;return t?r=new self.CustomEvent(e,{detail:n,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(r=document.createEvent("CustomEvent"),r.initCustomEvent(e,!1,!0,n)),r?!self.dispatchEvent(r):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,n){var r=o[t],i=self[r];return i?("rejectionHandled"===t?i.call(self,n):i.call(self,e,n),!0):!1}}();"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(O=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?O=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:H.isNode||"string"!=typeof(new Error).stack||(O=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var Y={warnings:q,longStackTraces:!1,cancellation:!1};return Q&&e.longStackTraces(),{longStackTraces:function(){return Y.longStackTraces},warnings:function(){return Y.warnings},cancellation:function(){return Y.cancellation},propagateFromFunction:function(){return z},boundValueFunction:function(){return u},checkForgottenReturns:f,setBounds:T,warn:d,deprecated:_,CapturedTrace:P}}},{"./errors":12,"./util":36}],10:[function(t,e){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return this.mapSeries(t)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,e){return r(t,e)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e){"use strict";function n(t,e){function n(r){return this instanceof n?(u(this,"message","string"==typeof r?r:e),u(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return l(n,Error),n}function r(t){return this instanceof r?(u(this,"name","OperationalError"),u(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(u(this,"message",t.message),u(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new r(t)}var i,o,s=t("./es5"),a=s.freeze,c=t("./util"),l=c.inherits,u=c.notEnumerableProp,p=n("Warning","warning"),h=n("CancellationError","cancellation error"),f=n("TimeoutError","timeout error"),_=n("AggregateError","aggregate error");try{i=TypeError,o=RangeError}catch(d){i=n("TypeError","type error"),o=n("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function o(){return a.call(this,this.promise._target()._settledValue())}function s(t){return i(this,t)?void 0:(u.e=t,u)}function a(t){var a=this.promise,c=this.handler;if(!this.called){this.called=!0;var p=0===this.type?c.call(a._boundValue()):c.call(a._boundValue(),t);if(void 0!==p){var h=n(p,a);if(h instanceof e){if(null!=this.cancelPromise){if(h.isCancelled()){var f=new l("late cancellation observer");return a._attachExtraTrace(f),u.e=f,u}h.isPending()&&h._attachCancellationCallback(new r(this))}return h._then(o,s,void 0,this,void 0)}}}return a.isRejected()?(i(this),u.e=t,u):(i(this),t)}var c=t("./util"),l=e.CancellationError,u=c.errorObj;return r.prototype._resultCancelled=function(){i(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,{promise:this,handler:t,called:!1,cancelPromise:null,type:e},void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,a,a)},e.prototype.tap=function(t){return this._passThrough(t,1,a)},a}},{"./util":36}],16:[function(t,e){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=l();this._callback=null===i?e:i.bind(e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=n>=1?[]:f,this._init$(void 0,-2)}function c(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+u.classString(e));var o="object"==typeof n&&null!==n?n.concurrency:0;return o="number"==typeof o&&isFinite(o)&&o>=1?o:0,new a(t,e,o,i).promise()}var l=e._getDomain,u=t("./util"),p=u.tryCatch,h=u.errorObj,f=[];u.inherits(a,n),a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){var r=this._values,o=this.length(),a=this._preservedValues,c=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,c>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(c>=1&&this._inFlight>=c)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var l=this._promise,u=this._callback,f=l._boundValue();l._pushContext();var _=p(u).call(f,t,n,o),d=l._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",l),_===h)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return c>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var g=++this._totalResolved;return g>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return c(this,t,e,null)},e.map=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],19:[function(t,e){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments),s=r._popContext();return o.checkForgottenReturns(i,s,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=s.isArray(l)?a(t).apply(u,l):a(t).call(u,l)}else c=a(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e){"use strict";function n(t){return t instanceof Error&&l.getPrototypeOf(t)===Error.prototype}function r(t){var e;if(n(t)){e=new c(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var r=l.keys(t),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!h.isObject(o))return u("expecting an object but got "+h.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,T(r,t,this))}return this.then(void 0,t)},r.prototype.reflect=function(){return this._then(l,l,void 0,this,void 0)},r.prototype.then=function(t,e){if(E.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+h.classString(t);arguments.length>1&&(n+=", "+h.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},r.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},r.prototype.spread=function(t){return"function"!=typeof t?u("expecting a function but got "+h.classString(t)):this.all()._then(t,void 0,void 0,b,void 0)},r.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},r.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new j(this).promise()},r.prototype.error=function(t){return this.caught(h.originatesFromRejection,t)},r.is=function(t){return t instanceof r},r.fromNode=r.fromCallback=function(t){var e=new r(m),n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,i=S(t)(P(e,n));return i===R&&e._rejectCallback(i.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},r.all=function(t){return new j(t).promise()},r.cast=function(t){var e=C(t);return e instanceof r||(e=new r(m),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},r.resolve=r.fulfilled=r.cast,r.reject=r.rejected=function(t){var e=new r(m);return e._captureStackTrace(),e._rejectCallback(t,!0),e},r.setScheduler=function(t){if("function"!=typeof t)throw new y("expecting a function but got "+h.classString(t));var e=d._schedule;return d._schedule=t,e},r.prototype._then=function(t,e,n,i,o){var s=void 0!==o,c=s?o:new r(m),l=this._target(),u=l._bitField;s||(c._propagateFrom(this,3),c._captureStackTrace(),void 0===i&&0!==(2097152&this._bitField)&&(i=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo));var p=a();if(0!==(50397184&u)){var h,f,_=l._settlePromiseCtx;0!==(33554432&u)?(f=l._rejectionHandler0,h=t):0!==(16777216&u)?(f=l._fulfillmentHandler0,h=e,l._unsetRejectionIsUnhandled()):(_=l._settlePromiseLateCancellationObserver,f=new g("late cancellation observer"),l._attachExtraTrace(f),h=e),d.invoke(_,l,{handler:null===p?h:"function"==typeof h&&p.bind(h),promise:c,receiver:i,value:f})}else l._addCallbacks(t,e,c,i,p);return c},r.prototype._length=function(){return 65535&this._bitField},r.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},r.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},r.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},r.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField},r.prototype._setRejected=function(){this._bitField=16777216|this._bitField},r.prototype._setFollowing=function(){this._bitField=67108864|this._bitField},r.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},r.prototype._isFinal=function(){return(4194304&this._bitField)>0},r.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},r.prototype._setCancelled=function(){this._bitField=65536|this._bitField},r.prototype._setAsyncGuaranteed=function(){this._bitField=134217728|this._bitField},r.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===p?void 0:void 0===e&&this._isBound()?this._boundValue():e},r.prototype._promiseAt=function(t){return this[4*t-4+2]},r.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},r.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},r.prototype._boundValue=function(){},r.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=p),this._addCallbacks(e,n,r,i,null)},r.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=p),this._addCallbacks(n,r,i,o,null)},r.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:i.bind(t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:i.bind(e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:i.bind(t)),"function"==typeof e&&(this[s+1]=null===i?e:i.bind(e))}return this._setLength(o+1),o},r.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},r.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(c(),!1);var n=C(t,this);if(!(n instanceof r))return this._fulfill(t);e&&this._propagateFrom(n,2);var i=n._target(),o=i._bitField;if(0===(50397184&o)){var s=this._length();s>0&&i._migrateCallback0(this);for(var a=1;s>a;++a)i._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(i)}else if(0!==(33554432&o))this._fulfill(i._value());else if(0!==(16777216&o))this._reject(i._reason());else{var l=new g("late cancellation observer");i._attachExtraTrace(l),this._reject(l)}}},r.prototype._rejectCallback=function(t,e,n){var r=h.ensureErrorObject(t),i=r===t;if(!i&&!n&&E.warnings()){var o="a promise was rejected with a non-error: "+h.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},r.prototype._resolveFromExecutor=function(t){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)},r.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===b?n&&"number"==typeof n.length?o=S(t).apply(this._boundValue(),n):(o=R,o.e=new y("cannot .spread() a non-array: "+h.classString(n))):o=S(t).call(e,n);var s=r._popContext();if(i=r._bitField,0===(65536&i))if(o===w)r._reject(n);else if(o===R||o===r){var a=o===r?c():o.e;r._rejectCallback(a,!1)}else E.checkForgottenReturns(o,s,"",r),r._resolveCallback(o)}},r.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},r.prototype._followee=function(){return this._rejectionHandler0},r.prototype._setFollowee=function(t){this._rejectionHandler0=t},r.prototype._settlePromise=function(t,n,i,o){var s=t instanceof r,a=this._bitField,c=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),n===x?(i.cancelPromise=t,S(n).call(i,o)===R&&t._reject(R.e)):n===l?t._fulfill(l.call(i)):i instanceof e?i._promiseCancelled(t):s||t instanceof j?t._cancel():i.cancel()):"function"==typeof n?s?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(n,i,o,t)):n.call(i,o,t):i instanceof e?i._isResolved()||(0!==(33554432&a)?i._promiseFulfilled(o,t):i._promiseRejected(o,t)):s&&(c&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},r.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,i=t.receiver,o=t.value;"function"==typeof e?n instanceof r?this._settlePromiseFromHandler(e,i,o,n):e.call(i,o,n):n instanceof r&&n._reject(o)},r.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},r.prototype._settlePromise0=function(t,e){var n=this._promise0,r=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(n,t,r,e)},r.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},r.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=c();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():d.settlePromises(this))}},r.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?d.fatalError(t,h.isNode):void((65535&e)>0?0!==(134217728&e)?this._settlePromises():d.settlePromises(this):this._ensurePossibleRejectionHandled())},r.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},r.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},r.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},r.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},r.defer=r.pending=function(){E.deprecated("Promise.defer","new Promise");var t=new r(m);return{promise:t,resolve:i,reject:o}},h.notEnumerableProp(r,"_makeSelfResolutionError",c),t("./method")(r,m,C,u,E),t("./bind")(r,m,C,E),t("./cancel")(r,j,u,E),t("./direct_resolve")(r),t("./synchronous_inspection")(r),t("./join")(r,j,C,m,E),r.Promise=r,t("./map.js")(r,j,u,C,m,E),t("./using.js")(r,u,C,F,m,E),t("./timers.js")(r,m),t("./generators.js")(r,u,m,C,e,E),t("./nodeify.js")(r),t("./call_get.js")(r),t("./props.js")(r,j,C,u),t("./race.js")(r,m,C,u),t("./reduce.js")(r,j,u,C,m,E),t("./settle.js")(r,j,E),t("./some.js")(r,j,u),t("./promisify.js")(r,m),t("./any.js")(r),t("./each.js")(r,m),t("./filter.js")(r,m),h.toFastProperties(r),h.toFastProperties(r.prototype),s({a:1}),s({b:2}),s({c:3}),s(1),s(function(){}),s(void 0),s(!1),s(new r(m)),E.setBounds(_.firstLineError,h.lastLineError),r}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(t,e){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{}}}function a(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}{var c=t("./util");c.isArray}return c.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var a=o._bitField;if(this._values=o,0===(50397184&a))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&a))return 0!==(16777216&a)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(s(n))):void this._iterate(o)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var c=r(t[a],i);c instanceof e?(c=c._target(),s=c._bitField):s=null,o?null!==s&&c.suppressUnhandledRejections():null!==s?0===(50397184&s)?(c._proxy(this,a),this._values[a]=c):o=0!==(33554432&s)?this._promiseFulfilled(c._value(),a):0!==(16777216&s)?this._promiseRejected(c._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(c,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise.isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;nc;c+=2){var u=s[c],p=s[c+1],_=u+e;if(r===F)t[_]=F(u,h,u,p,e,i);else{var d=r(p,function(){return F(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return F(t,e,void 0,t,null,n)}var p,h={},f=t("./util"),_=t("./nodeback"),d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,g=t("./errors").TypeError,m="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},k=function(t){return t.replace(/([$])/,"\\$")},F=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new g("expecting a function but got "+f.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?h:e.context,o=!!e.multiArgs,s=u(t,n,o);return f.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new g("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=m);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=F),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=f.inheritedDataKeys(t),a=0;ao;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,-3)}function s(t){var n,s=r(t);return l(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}var a,c=t("./util"),l=c.isObject,u=t("./es5");"function"==typeof Map&&(a=Map);var p=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),h=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};c.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=h(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5":13,"./util":36}],26:[function(t,e){"use strict";function n(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function r(t){this._capacity=t,this._length=0,this._front=0}r.prototype._willBeOverCapacity=function(t){return this._capacityh;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,p,void 0,l,null)}return l}var s=t("./util"),a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util":36}],28:[function(t,e){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=h();this._fn=null===s?n:s.bind(n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,this._eachValues=i===o?[]:void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function l(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+f.classString(e));var o=new a(t,e,n,i);return o.promise()}function u(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(p,void 0,void 0,this,void 0)):p.call(this,n)}function p(t){var n=this.array,r=n._promise,i=_(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var h=e._getDomain,f=t("./util"),_=f.tryCatch;f.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(u,void 0,void 0,o,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(c,c,void 0,n,this)},e.prototype.reduce=function(t,e){return l(this,t,e,null)},e.reduce=function(t,e,n,r){return l(t,e,n,r)}}},{"./util":36}],29:[function(t,e){"use strict";var n,r=t("./util"),i=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")};if(r.isNode&&"undefined"==typeof MutationObserver){var o=global.setImmediate,s=process.nextTick;n=r.isRecentNode?function(t){o.call(global,t)}:function(t){s.call(process,t)}}else"undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&window.navigator.standalone?n="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:i:(n=function(t){var e=document.createElement("div"),n=new MutationObserver(t);return n.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},n.isStatic=!0);e.exports=n},{"./util":36}],30:[function(t,e){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,c=t("./errors").AggregateError,l=s.isArray,u={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=l(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()?(this._values.length=this.howMany(),this._resolve(1===this.howMany()&&this._unwrap?this._values[0]:this._values),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new c,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=t.prototype._isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype.isCancelled=function(){return this._target()._isCancelled()},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue() +},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e){"use strict";e.exports=function(e,n){function r(t,r){if(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){r&&r._pushContext();var c=e.reject(i.e);return r&&r._popContext(),c}if("function"==typeof i){if(s(t)){var c=new e(n);return t._then(c._fulfill,c._reject,void 0,c,null),c}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(e){return l.e=e,l}}function s(t){return p.call(t,"_promise0")}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,p,!0),a=null)}var a=new e(n),u=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,h=c.tryCatch(r).call(t,o,s);return p=!1,a&&h===l&&(a._rejectCallback(h.e,!0,!0),a=null),u}var c=t("./util"),l=c.errorObj,u=c.isObject,p={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e){"use strict";e.exports=function(e,n){function r(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util"),s=e.TimeoutError,a=function(t,e,n){if(t.isPending()){var r;r="string"!=typeof e?e instanceof Error?e:new s("operation timed out"):new s(e),o.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._reject(r),n.cancel()}},c=function(t){return l(+this).thenReturn(t)},l=e.delay=function(t,r){var i;return void 0!==r?i=e.resolve(r)._then(c,null,null,t,void 0):(i=new e(n),setTimeout(function(){i._fulfill()},+t)),i._setAsyncGuaranteed(),i};e.prototype.delay=function(t){return l(t,this)},e.prototype.timeout=function(t,e){t=+t;var n=this.then(),o=n.then(),s=setTimeout(function(){a(o,e,n)},t);return o._then(r,i,void 0,s,void 0)}}},{"./util":36}],35:[function(t,e){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function c(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function l(t,n){function i(){if(s>=l)return u._fulfill();var o=c(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(p){return a(p)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,l=t.length,u=new e(o);return i(),u}function u(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function h(t){return u.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function f(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,g=_.tryCatch;u.prototype.data=function(){return this._data},u.prototype.promise=function(){return this._promise},u.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},u.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=null!==e?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},u.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,u),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},f.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var c=new f(t),p=0;t>p;++p){var d=o[p];if(u.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var m=r(d);m instanceof e&&(d=m._then(h,null,null,{resources:c,index:p},void 0))}c[p]=d}for(var b=new Array(c.length),p=0;p0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(t,e,n){"use strict";function r(){try{var t=E;return E=null,t.apply(this,arguments)}catch(e){return F.e=e,F}}function i(t){return E=t,r}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return"function"==typeof t||"object"==typeof t&&null!==t}function a(t){return o(t)?new Error(v(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!j.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return j.defineProperty(t,e,r),t}function p(t){throw t}function h(t){try{if("function"==typeof t){var e=j.names(t.prototype),n=j.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=P.test(t+"")&&j.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function f(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return R.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){try{u(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function m(t){return t instanceof Error&&j.propertyIsWritable(t,"stack")}function b(t){return{}.toString.call(t)}function w(t,e,n){for(var r=j.names(t),i=0;i10||t[0]>0}(),V.isNode&&V.toFastProperties(process);try{throw new Error}catch(H){V.lastLineError=H}e.exports=V},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/node_modules/bluebird/js/main/any.js b/node_modules/bluebird/js/release/any.js similarity index 100% rename from node_modules/bluebird/js/main/any.js rename to node_modules/bluebird/js/release/any.js diff --git a/node_modules/bluebird/js/release/assert.js b/node_modules/bluebird/js/release/assert.js new file mode 100644 index 0000000..d2e535b --- /dev/null +++ b/node_modules/bluebird/js/release/assert.js @@ -0,0 +1,55 @@ +"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); + } + throw ret; +}; +})(); diff --git a/node_modules/bluebird/js/release/async.js b/node_modules/bluebird/js/release/async.js new file mode 100644 index 0000000..edfb3ba --- /dev/null +++ b/node_modules/bluebird/js/release/async.js @@ -0,0 +1,157 @@ +"use strict"; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = require("./schedule"); +var Queue = require("./queue"); +var util = require("./util"); + +function Async() { + this._isTickUsed = false; + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); + this._haveDrainedQueues = false; + this._trampolineEnabled = true; + var self = this; + this.drainQueues = function () { + self._drainQueues(); + }; + this._schedule = + schedule.isStatic ? schedule(this.drainQueues) : schedule; +} + +Async.prototype.enableTrampoline = function() { + this._trampolineEnabled = true; +}; + +Async.prototype.disableTrampolineIfNecessary = function() { + if (util.hasDevTools) { + this._trampolineEnabled = false; + } +}; + +Async.prototype.haveItemsQueued = function () { + return this._isTickUsed || this._haveDrainedQueues; +}; + + +Async.prototype.fatalError = function(e, isNode) { + if (isNode) { + process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e)); + process.exit(2); + } else { + this.throwLater(e); + } +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } +}; + +function AsyncInvokeLater(fn, receiver, arg) { + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + this._normalQueue._pushOne(promise); + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + if (schedule.isStatic) { + schedule = function(fn) { setTimeout(fn, 0); }; + } + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + }); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + fn.call(receiver, arg); + }); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + this._schedule(function() { + promise._settlePromises(); + }); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._haveDrainedQueues = true; + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = Async; +module.exports.firstLineError = firstLineError; diff --git a/node_modules/bluebird/js/release/bind.js b/node_modules/bluebird/js/release/bind.js new file mode 100644 index 0000000..fc3379d --- /dev/null +++ b/node_modules/bluebird/js/release/bind.js @@ -0,0 +1,67 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { +var calledBind = false; +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + if (((this._bitField & 50397184) === 0)) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + if (!calledBind) { + calledBind = true; + Promise.prototype._propagateFrom = debug.propagateFromFunction(); + Promise.prototype._boundValue = debug.boundValueFunction(); + } + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, undefined, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, undefined, ret, context); + ret._setOnCancel(maybePromise); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 2097152; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~2097152); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 2097152) === 2097152; +}; + +Promise.bind = function (thisArg, value) { + return Promise.resolve(value).bind(thisArg); +}; +}; diff --git a/node_modules/bluebird/js/release/bluebird.js b/node_modules/bluebird/js/release/bluebird.js new file mode 100644 index 0000000..1c36cf3 --- /dev/null +++ b/node_modules/bluebird/js/release/bluebird.js @@ -0,0 +1,11 @@ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = require("./promise")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; diff --git a/node_modules/bluebird/js/release/call_get.js b/node_modules/bluebird/js/release/call_get.js new file mode 100644 index 0000000..e643aaa --- /dev/null +++ b/node_modules/bluebird/js/release/call_get.js @@ -0,0 +1,123 @@ +"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"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!false) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \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: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(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; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.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 (!false) { + 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) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +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); +}; +}; diff --git a/node_modules/bluebird/js/release/cancel.js b/node_modules/bluebird/js/release/cancel.js new file mode 100644 index 0000000..5ed6bc9 --- /dev/null +++ b/node_modules/bluebird/js/release/cancel.js @@ -0,0 +1,125 @@ +"use strict"; +module.exports = function(Promise, PromiseArray, apiRejection, debug) { +var util = require("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var async = Promise._async; + +Promise.prototype["break"] = Promise.prototype.cancel = function() { + if (!debug.cancellation()) return this._warn("cancellation is disabled"); + + var promise = this; + var child = promise; + while (promise.isCancellable()) { + if (!promise._cancelBy(child)) { + if (child._isFollowing()) { + child._followee().cancel(); + } else { + child._cancelBranched(); + } + break; + } + + var parent = promise._cancellationParent; + if (parent == null || !parent.isCancellable()) { + if (promise._isFollowing()) { + promise._followee().cancel(); + } else { + promise._cancelBranched(); + } + break; + } else { + if (promise._isFollowing()) promise._followee().cancel(); + child = promise; + promise = parent; + } + } +}; + +Promise.prototype._branchHasCancelled = function() { + this._branchesRemainingToCancel--; +}; + +Promise.prototype._enoughBranchesHaveCancelled = function() { + return this._branchesRemainingToCancel === undefined || + this._branchesRemainingToCancel <= 0; +}; + +Promise.prototype._cancelBy = function(canceller) { + if (canceller === this) { + this._branchesRemainingToCancel = 0; + this._invokeOnCancel(); + return true; + } else { + this._branchHasCancelled(); + if (this._enoughBranchesHaveCancelled()) { + this._invokeOnCancel(); + return true; + } + } + return false; +}; + +Promise.prototype._cancelBranched = function() { + if (this._enoughBranchesHaveCancelled()) { + this._cancel(); + } +}; + +Promise.prototype._cancel = function() { + if (!this.isCancellable()) return; + + this._setCancelled(); + async.invoke(this._cancelPromises, this, undefined); +}; + +Promise.prototype._cancelPromises = function() { + if (this._length() > 0) this._settlePromises(); +}; + +Promise.prototype._unsetOnCancel = function() { + this._onCancelField = undefined; +}; + +Promise.prototype.isCancellable = function() { + return this.isPending() && !this.isCancelled(); +}; + +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { + if (util.isArray(onCancelCallback)) { + for (var i = 0; i < onCancelCallback.length; ++i) { + this._doInvokeOnCancel(onCancelCallback[i], internalOnly); + } + } else if (onCancelCallback !== undefined) { + if (typeof onCancelCallback === "function") { + if (!internalOnly) { + var e = tryCatch(onCancelCallback).call(this._boundValue()); + if (e === errorObj) { + this._attachExtraTrace(e.e); + async.throwLater(e.e); + } + } + } else { + onCancelCallback._resultCancelled(this); + } + } +}; + +Promise.prototype._invokeOnCancel = function() { + var onCancelCallback = this._onCancel(); + this._unsetOnCancel(); + async.invoke(this._doInvokeOnCancel, this, onCancelCallback); +}; + +Promise.prototype._invokeInternalOnCancel = function() { + if (this.isCancellable()) { + this._doInvokeOnCancel(this._onCancel(), true); + this._unsetOnCancel(); + } +}; + +Promise.prototype._resultCancelled = function() { + this.cancel(); +}; + +}; diff --git a/node_modules/bluebird/js/release/catch_filter.js b/node_modules/bluebird/js/release/catch_filter.js new file mode 100644 index 0000000..0f24ce2 --- /dev/null +++ b/node_modules/bluebird/js/release/catch_filter.js @@ -0,0 +1,42 @@ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = require("./util"); +var getKeys = require("./es5").keys; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function catchFilter(instances, cb, promise) { + return function(e) { + var boundTo = promise._boundValue(); + predicateLoop: for (var i = 0; i < instances.length; ++i) { + var item = instances[i]; + + if (item === Error || + (item != null && item.prototype instanceof Error)) { + if (e instanceof item) { + return tryCatch(cb).call(boundTo, e); + } + } else if (typeof item === "function") { + var matchesPredicate = tryCatch(item).call(boundTo, e); + if (matchesPredicate === errorObj) { + return matchesPredicate; + } else if (matchesPredicate) { + return tryCatch(cb).call(boundTo, e); + } + } else if (util.isObject(e)) { + var keys = getKeys(item); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + if (item[key] != e[key]) { + continue predicateLoop; + } + } + return tryCatch(cb).call(boundTo, e); + } + } + return NEXT_FILTER; + }; +} + +return catchFilter; +}; diff --git a/node_modules/bluebird/js/release/context.js b/node_modules/bluebird/js/release/context.js new file mode 100644 index 0000000..c307414 --- /dev/null +++ b/node_modules/bluebird/js/release/context.js @@ -0,0 +1,69 @@ +"use strict"; +module.exports = function(Promise) { +var longStackTraces = false; +var contextStack = []; + +Promise.prototype._promiseCreated = function() {}; +Promise.prototype._pushContext = function() {}; +Promise.prototype._popContext = function() {return null;}; +Promise._peekContext = Promise.prototype._peekContext = function() {}; + +function Context() { + this._trace = new Context.CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (this._trace !== undefined) { + this._trace._promiseCreated = null; + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (this._trace !== undefined) { + var trace = contextStack.pop(); + var ret = trace._promiseCreated; + trace._promiseCreated = null; + return ret; + } + return null; +}; + +function createContext() { + if (longStackTraces) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} +Context.CapturedTrace = null; +Context.create = createContext; +Context.deactivateLongStackTraces = function() {}; +Context.activateLongStackTraces = function() { + var Promise_pushContext = Promise.prototype._pushContext; + var Promise_popContext = Promise.prototype._popContext; + var Promise_PeekContext = Promise._peekContext; + var Promise_peekContext = Promise.prototype._peekContext; + var Promise_promiseCreated = Promise.prototype._promiseCreated; + Context.deactivateLongStackTraces = function() { + Promise.prototype._pushContext = Promise_pushContext; + Promise.prototype._popContext = Promise_popContext; + Promise._peekContext = Promise_PeekContext; + Promise.prototype._peekContext = Promise_peekContext; + Promise.prototype._promiseCreated = Promise_promiseCreated; + longStackTraces = false; + }; + longStackTraces = true; + Promise.prototype._pushContext = Context.prototype._pushContext; + Promise.prototype._popContext = Context.prototype._popContext; + Promise._peekContext = Promise.prototype._peekContext = peekContext; + Promise.prototype._promiseCreated = function() { + var ctx = this._peekContext(); + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; + }; +}; +return Context; +}; diff --git a/node_modules/bluebird/js/release/debuggability.js b/node_modules/bluebird/js/release/debuggability.js new file mode 100644 index 0000000..9f142f0 --- /dev/null +++ b/node_modules/bluebird/js/release/debuggability.js @@ -0,0 +1,812 @@ +"use strict"; +module.exports = function(Promise, Context) { +var getDomain = Promise._getDomain; +var async = Promise._async; +var Warning = require("./errors").Warning; +var util = require("./util"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var printWarning; +var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && + (false || + util.env("BLUEBIRD_DEBUG") || + util.env("NODE_ENV") === "development")); +var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && + (debugging || util.env("BLUEBIRD_WARNINGS"))); +var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && + (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); + +Promise.prototype.suppressUnhandledRejections = function() { + var target = this._target(); + target._bitField = ((target._bitField & (~1048576)) | + 2097152); +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 2097152) !== 0) return; + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._settledValue(); + this._setUnhandledRejectionIsNotified(); + fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 262144; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~262144); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 262144) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 1048576; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~1048576); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { + return warn(message, shouldUseOwnTrace, promise || this); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; +}; + +var disableLongStackTraces = function() {}; +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (!config.longStackTraces && longStackTracesIsSupported()) { + var Promise_captureStackTrace = Promise.prototype._captureStackTrace; + var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; + config.longStackTraces = true; + disableLongStackTraces = function() { + if (async.haveItemsQueued() && !config.longStackTraces) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + Promise.prototype._captureStackTrace = Promise_captureStackTrace; + Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; + Context.deactivateLongStackTraces(); + async.enableTrampoline(); + config.longStackTraces = false; + }; + Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; + Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; + Context.activateLongStackTraces(); + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return config.longStackTraces && longStackTracesIsSupported(); +}; + +Promise.config = function(opts) { + opts = Object(opts); + if ("longStackTraces" in opts) { + if (opts.longStackTraces) { + Promise.longStackTraces(); + } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { + disableLongStackTraces(); + } + } + if ("warnings" in opts) { + config.warnings = !!opts.warnings; + } + if ("cancellation" in opts && opts.cancellation && !config.cancellation) { + if (async.haveItemsQueued()) { + throw new Error( + "cannot enable cancellation after promises are in use"); + } + Promise.prototype._clearCancellationData = + cancellationClearCancellationData; + Promise.prototype._propagateFrom = cancellationPropagateFrom; + Promise.prototype._onCancel = cancellationOnCancel; + Promise.prototype._setOnCancel = cancellationSetOnCancel; + Promise.prototype._attachCancellationCallback = + cancellationAttachCancellationCallback; + Promise.prototype._execute = cancellationExecute; + propagateFromFunction = cancellationPropagateFrom; + config.cancellation = true; + } +}; + +Promise.prototype._execute = function(executor, resolve, reject) { + try { + executor(resolve, reject); + } catch (e) { + return e; + } +}; +Promise.prototype._onCancel = function () {}; +Promise.prototype._setOnCancel = function (handler) { ; }; +Promise.prototype._attachCancellationCallback = function(onCancel) { + ; +}; +Promise.prototype._captureStackTrace = function () {}; +Promise.prototype._attachExtraTrace = function () {}; +Promise.prototype._clearCancellationData = function() {}; +Promise.prototype._propagateFrom = function (parent, flags) { + ; + ; +}; + +function cancellationExecute(executor, resolve, reject) { + var promise = this; + try { + executor(resolve, reject, function(onCancel) { + if (typeof onCancel !== "function") { + throw new TypeError("onCancel must be a function, got: " + + util.toString(onCancel)); + } + promise._attachCancellationCallback(onCancel); + }); + } catch (e) { + return e; + } +} + +function cancellationAttachCancellationCallback(onCancel) { + if (!this.isCancellable()) return this; + + var previousOnCancel = this._onCancel(); + if (previousOnCancel !== undefined) { + if (util.isArray(previousOnCancel)) { + previousOnCancel.push(onCancel); + } else { + this._setOnCancel([previousOnCancel, onCancel]); + } + } else { + this._setOnCancel(onCancel); + } +} + +function cancellationOnCancel() { + return this._onCancelField; +} + +function cancellationSetOnCancel(onCancel) { + this._onCancelField = onCancel; +} + +function cancellationClearCancellationData() { + this._cancellationParent = undefined; + this._onCancelField = undefined; +} + +function cancellationPropagateFrom(parent, flags) { + if ((flags & 1) !== 0) { + this._cancellationParent = parent; + var branchesRemainingToCancel = parent._branchesRemainingToCancel; + if (branchesRemainingToCancel === undefined) { + branchesRemainingToCancel = 0; + } + parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; + } + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} + +function bindingPropagateFrom(parent, flags) { + if ((flags & 2) !== 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +} +var propagateFromFunction = bindingPropagateFrom; + +function boundValueFunction() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +} + +function longStackTracesCaptureStackTrace() { + this._trace = new CapturedTrace(this._peekContext()); +} + +function longStackTracesAttachExtraTrace(error, ignoreSelf) { + if (canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +} + +function checkForgottenReturns(returnValue, promiseCreated, name, promise) { + if (returnValue === undefined && + promiseCreated !== null && + config.longStackTraces && + config.warnings) { + var msg = "a promise was created in a " + name + + " handler but was not returned from it"; + promise._warn(msg, true, promiseCreated); + } +} + +function deprecated(name, replacement) { + var message = name + + " is deprecated and will be removed in a future version."; + if (replacement) message += " Use " + replacement + " instead."; + return warn(message); +} + +function warn(message, shouldUseOwnTrace, promise) { + if (!config.warnings) return; + var warning = new Warning(message); + var ctx; + if (shouldUseOwnTrace) { + promise._attachExtraTrace(warning); + } else if (config.longStackTraces && (ctx = Promise._peekContext())) { + ctx.attachExtraTrace(warning); + } else { + var parsed = parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + formatAndLogError(warning, "", true); +} + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = " (No stack trace)" === line || + stackFramePattern.test(line); + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +function parseStackAndMessage(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +} + +function formatAndLogError(error, title, isSoft) { + if (typeof console !== "undefined") { + var message; + if (util.isObject(error)) { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); + } + if (typeof printWarning === "function") { + printWarning(message, isSoft); + } else if (typeof console.log === "function" || + typeof console.log === "object") { + console.log(message); + } + } +} + +function fireRejectionEvent(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + formatAndLogError(reason, "Unhandled rejection "); + } +} + +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj && typeof obj.toString === "function" + ? obj.toString() : util.toString(obj); + 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) + "..."; +} + +function longStackTracesIsSupported() { + return typeof captureStackTrace === "function"; +} + +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) + }; + } +} + +function setBounds(firstLineError, lastLineError) { + if (!longStackTracesIsSupported()) 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) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +} + +function CapturedTrace(parent) { + this._parent = parent; + this._promisesCreated = 0; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); +Context.CapturedTrace = CapturedTrace; + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit += 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit += 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit -= 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit += 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit -= 6; + }; + } + + 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.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + printWarning = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + printWarning = function(message, isSoft) { + var color = isSoft ? "\u001b[33m" : "\u001b[31m"; + console.warn(color + message + "\u001b[0m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + printWarning = function(message, isSoft) { + console.warn("%c" + message, + isSoft ? "color: darkorange" : "color: red"); + }; + } +} + +var config = { + warnings: warnings, + longStackTraces: false, + cancellation: false +}; + +if (longStackTraces) Promise.longStackTraces(); + +return { + longStackTraces: function() { + return config.longStackTraces; + }, + warnings: function() { + return config.warnings; + }, + cancellation: function() { + return config.cancellation; + }, + propagateFromFunction: function() { + return propagateFromFunction; + }, + boundValueFunction: function() { + return boundValueFunction; + }, + checkForgottenReturns: checkForgottenReturns, + setBounds: setBounds, + warn: warn, + deprecated: deprecated, + CapturedTrace: CapturedTrace +}; +}; diff --git a/node_modules/bluebird/js/release/direct_resolve.js b/node_modules/bluebird/js/release/direct_resolve.js new file mode 100644 index 0000000..a890298 --- /dev/null +++ b/node_modules/bluebird/js/release/direct_resolve.js @@ -0,0 +1,46 @@ +"use strict"; +module.exports = function(Promise) { +function returner() { + return this.value; +} +function thrower() { + throw this.reason; +} + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + returner, undefined, undefined, {value: value}, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + return this._then( + thrower, undefined, undefined, {reason: reason}, undefined); +}; + +Promise.prototype.catchThrow = function (reason) { + if (arguments.length <= 1) { + return this._then( + undefined, thrower, undefined, {reason: reason}, undefined); + } else { + var _reason = arguments[1]; + var handler = function() {throw _reason;}; + return this.caught(reason, handler); + } +}; + +Promise.prototype.catchReturn = function (value) { + if (arguments.length <= 1) { + if (value instanceof Promise) value.suppressUnhandledRejections(); + return this._then( + undefined, returner, undefined, {value: value}, undefined); + } else { + var _value = arguments[1]; + if (_value instanceof Promise) _value.suppressUnhandledRejections(); + var handler = function() {return _value;}; + return this.caught(value, handler); + } +}; +}; diff --git a/node_modules/bluebird/js/release/each.js b/node_modules/bluebird/js/release/each.js new file mode 100644 index 0000000..ac8ead7 --- /dev/null +++ b/node_modules/bluebird/js/release/each.js @@ -0,0 +1,29 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; +var PromiseAll = Promise.all; + +function promiseAllThis() { + return PromiseAll(this); +} + +function PromiseMapSeries(promises, fn) { + return PromiseReduce(promises, fn, INTERNAL, INTERNAL); +} + +Promise.prototype.each = function (fn) { + return this.mapSeries(fn) + ._then(promiseAllThis, undefined, undefined, this, undefined); +}; + +Promise.prototype.mapSeries = function (fn) { + return PromiseReduce(this, fn, INTERNAL, INTERNAL); +}; + +Promise.each = function (promises, fn) { + return PromiseMapSeries(promises, fn) + ._then(promiseAllThis, undefined, undefined, promises, undefined); +}; + +Promise.mapSeries = PromiseMapSeries; +}; diff --git a/node_modules/bluebird/js/release/errors.js b/node_modules/bluebird/js/release/errors.js new file mode 100644 index 0000000..ddd0525 --- /dev/null +++ b/node_modules/bluebird/js/release/errors.js @@ -0,0 +1,111 @@ +"use strict"; +var es5 = require("./es5"); +var Objectfreeze = es5.freeze; +var util = require("./util"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +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); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +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]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +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) { + if (!(this instanceof OperationalError)) + return new 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 errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; diff --git a/node_modules/bluebird/js/main/es5.js b/node_modules/bluebird/js/release/es5.js similarity index 100% rename from node_modules/bluebird/js/main/es5.js rename to node_modules/bluebird/js/release/es5.js diff --git a/node_modules/bluebird/js/main/filter.js b/node_modules/bluebird/js/release/filter.js similarity index 100% rename from node_modules/bluebird/js/main/filter.js rename to node_modules/bluebird/js/release/filter.js diff --git a/node_modules/bluebird/js/release/finally.js b/node_modules/bluebird/js/release/finally.js new file mode 100644 index 0000000..0ee8b99 --- /dev/null +++ b/node_modules/bluebird/js/release/finally.js @@ -0,0 +1,100 @@ +"use strict"; +module.exports = function(Promise, tryConvertToPromise) { +var util = require("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; + +function FinallyHandlerCancelReaction(finallyHandler) { + this.finallyHandler = finallyHandler; +} + +FinallyHandlerCancelReaction.prototype._resultCancelled = function() { + checkCancel(this.finallyHandler); +}; + +function checkCancel(ctx, reason) { + if (ctx.cancelPromise != null) { + if (arguments.length > 1) { + ctx.cancelPromise._reject(reason); + } else { + ctx.cancelPromise._cancel(); + } + ctx.cancelPromise = null; + return true; + } + return false; +} + +function succeed() { + return finallyHandler.call(this, this.promise._target()._settledValue()); +} +function fail(reason) { + if (checkCancel(this, reason)) return; + errorObj.e = reason; + return errorObj; +} +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + + if (!this.called) { + this.called = true; + var ret = this.type === 0 + ? handler.call(promise._boundValue()) + : handler.call(promise._boundValue(), reasonOrValue); + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + if (this.cancelPromise != null) { + if (maybePromise.isCancelled()) { + var reason = + new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + errorObj.e = reason; + return errorObj; + } else if (maybePromise.isPending()) { + maybePromise._attachCancellationCallback( + new FinallyHandlerCancelReaction(this)); + } + } + return maybePromise._then( + succeed, fail, undefined, this, undefined); + } + } + } + + if (promise.isRejected()) { + checkCancel(this); + errorObj.e = reasonOrValue; + return errorObj; + } else { + checkCancel(this); + return reasonOrValue; + } +} + +Promise.prototype._passThrough = function(handler, type, success, fail) { + if (typeof handler !== "function") return this.then(); + return this._then(success, fail, undefined, { + promise: this, + handler: handler, + called: false, + cancelPromise: null, + type: type + }, undefined); +}; + +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThrough(handler, + 0, + finallyHandler, + finallyHandler); +}; + +Promise.prototype.tap = function (handler) { + return this._passThrough(handler, 1, finallyHandler); +}; + +return finallyHandler; +}; diff --git a/node_modules/bluebird/js/release/generators.js b/node_modules/bluebird/js/release/generators.js new file mode 100644 index 0000000..d04c228 --- /dev/null +++ b/node_modules/bluebird/js/release/generators.js @@ -0,0 +1,204 @@ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise, + Proxyable, + debug) { +var errors = require("./errors"); +var TypeError = errors.TypeError; +var util = require("./util"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + promise._setOnCancel(this); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; + this._yieldedPromise = null; +} +util.inherits(PromiseSpawn, Proxyable); + +PromiseSpawn.prototype._isResolved = function() { + return this.promise === null; +}; + +PromiseSpawn.prototype._cleanup = function() { + this._promise = this._generator = null; +}; + +PromiseSpawn.prototype._promiseCancelled = function() { + if (this._isResolved()) return; + var implementsReturn = typeof this._generator["return"] !== "undefined"; + + var result; + if (!implementsReturn) { + var reason = new Promise.CancellationError( + "generator .return() sentinel"); + Promise.coroutine.returnSentinel = reason; + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + result = tryCatch(this._generator["throw"]).call(this._generator, + reason); + this._promise._popContext(); + if (result === errorObj && result.e === reason) { + result = null; + } + } else { + this._promise._pushContext(); + result = tryCatch(this._generator["return"]).call(this._generator, + undefined); + this._promise._popContext(); + } + var promise = this._promise; + this._cleanup(); + if (result === errorObj) { + promise._rejectCallback(result.e, false); + } else { + promise.cancel(); + } +}; + +PromiseSpawn.prototype._promiseFulfilled = function(value) { + this._yieldedPromise = null; + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._promiseRejected = function(reason) { + this._yieldedPromise = null; + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._resultCancelled = function() { + if (this._yieldedPromise instanceof Promise) { + var promise = this._yieldedPromise; + this._yieldedPromise = null; + promise.cancel(); + } +}; + +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; + +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._promiseFulfilled(undefined); +}; + +PromiseSpawn.prototype._continue = function (result) { + var promise = this._promise; + if (result === errorObj) { + this._cleanup(); + return promise._rejectCallback(result.e, false); + } + + var value = result.value; + if (result.done === true) { + this._cleanup(); + return promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._promiseRejected( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + this._yieldedPromise = maybePromise; + maybePromise._proxy(this, null); + } else if (((bitField & 33554432) !== 0)) { + this._promiseFulfilled(maybePromise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._promiseRejected(maybePromise._reason()); + } else { + this._promiseCancelled(); + } + } +}; + +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + var ret = spawn.promise(); + spawn._generator = generator; + spawn._promiseFulfilled(undefined); + return ret; + }; +}; + +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + debug.deprecated("Promise.spawn()", "Promise.coroutine()"); + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; diff --git a/node_modules/bluebird/js/release/join.js b/node_modules/bluebird/js/release/join.js new file mode 100644 index 0000000..b3ec246 --- /dev/null +++ b/node_modules/bluebird/js/release/join.js @@ -0,0 +1,149 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = require("./util"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!false) { +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 promiseSetter = function(i) { + return new Function("promise", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = promise; \n\ + ".replace(/Index/g, i)); + }; + + var generateHolderClass = function(total) { + var props = new Array(total); + for (var i = 0; i < props.length; ++i) { + props[i] = "this.p" + (i+1); + } + var assignment = props.join(" = ") + " = null;"; + var cancellationCode= "var promise;\n" + props.map(function(prop) { + return " \n\ + promise = " + prop + "; \n\ + if (promise instanceof Promise) { \n\ + promise.cancel(); \n\ + } \n\ + "; + }).join("\n"); + var passedArguments = props.join(", "); + var name = "Holder$" + total; + + + var code = "return function(tryCatch, errorObj, Promise) { \n\ + 'use strict'; \n\ + function [TheName](fn) { \n\ + [TheProperties] \n\ + this.fn = fn; \n\ + this.now = 0; \n\ + } \n\ + [TheName].prototype.checkFulfillment = function(promise) { \n\ + var now = ++this.now; \n\ + if (now === [TheTotal]) { \n\ + promise._pushContext(); \n\ + var callback = this.fn; \n\ + var ret = tryCatch(callback)([ThePassedArguments]); \n\ + promise._popContext(); \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(ret.e, false); \n\ + } else { \n\ + promise._resolveCallback(ret); \n\ + } \n\ + } \n\ + }; \n\ + \n\ + [TheName].prototype._resultCancelled = function() { \n\ + [CancellationCode] \n\ + }; \n\ + \n\ + return [TheName]; \n\ + }(tryCatch, errorObj, Promise); \n\ + "; + + code = code.replace(/\[TheName\]/g, name) + .replace(/\[TheTotal\]/g, total) + .replace(/\[ThePassedArguments\]/g, passedArguments) + .replace(/\[TheProperties\]/g, assignment) + .replace(/\[CancellationCode\]/g, cancellationCode); + + return new Function("tryCatch", "errorObj", "Promise", code) + (tryCatch, errorObj, Promise); + }; + + var holderClasses = []; + var thenCallbacks = []; + var promiseSetters = []; + + for (var i = 0; i < 8; ++i) { + holderClasses.push(generateHolderClass(i + 1)); + thenCallbacks.push(thenCallback(i + 1)); + promiseSetters.push(promiseSetter(i + 1)); + } + + reject = function (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 (!false) { + if (last <= 8 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var HolderClass = holderClasses[last - 1]; + var holder = new HolderClass(fn); + var callbacks = thenCallbacks; + + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + promiseSetters[i](maybePromise, holder); + } else if (((bitField & 33554432) !== 0)) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else if (((bitField & 16777216) !== 0)) { + ret._reject(maybePromise._reason()); + } else { + ret._cancel(); + } + } else { + callbacks[i].call(ret, maybePromise, holder); + } + } + if (!ret._isFateSealed()) { + ret._setAsyncGuaranteed(); + ret._setOnCancel(holder); + } + return ret; + } + } + } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}; + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; diff --git a/node_modules/bluebird/js/release/map.js b/node_modules/bluebird/js/release/map.js new file mode 100644 index 0000000..24690dc --- /dev/null +++ b/node_modules/bluebird/js/release/map.js @@ -0,0 +1,151 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +var util = require("./util"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(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) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + + if (index < 0) { + index = (index * -1) - 1; + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return true; + } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return false; + } + if (preservedValues !== null) preservedValues[index] = value; + + var promise = this._promise; + var callback = this._callback; + var receiver = promise._boundValue(); + promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promiseCreated, + preservedValues !== null ? "Promise.filter" : "Promise.map", + promise + ); + if (ret === errorObj) { + this._reject(ret.e); + return true; + } + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + var bitField = maybePromise._bitField; + ; + if (((bitField & 50397184) === 0)) { + if (limit >= 1) this._inFlight++; + values[index] = maybePromise; + maybePromise._proxy(this, (index + 1) * -1); + return false; + } else if (((bitField & 33554432) !== 0)) { + ret = maybePromise._value(); + } else if (((bitField & 16777216) !== 0)) { + this._reject(maybePromise._reason()); + return true; + } else { + this._cancel(); + return true; + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } + return true; + } + return false; +}; + +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) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + 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(); +} + +Promise.prototype.map = function (fn, options) { + return map(this, fn, options, null); +}; + +Promise.map = function (promises, fn, options, _filter) { + return map(promises, fn, options, _filter); +}; + + +}; diff --git a/node_modules/bluebird/js/release/method.js b/node_modules/bluebird/js/release/method.js new file mode 100644 index 0000000..ce9e4db --- /dev/null +++ b/node_modules/bluebird/js/release/method.js @@ -0,0 +1,55 @@ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { +var util = require("./util"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.method", ret); + ret._resolveFromSyncValue(value); + return ret; + }; +}; + +Promise.attempt = Promise["try"] = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value; + if (arguments.length > 1) { + debug.deprecated("calling Promise.try with more than 1 argument"); + var arg = arguments[1]; + var ctx = arguments[2]; + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) + : tryCatch(fn).call(ctx, arg); + } else { + value = tryCatch(fn)(); + } + var promiseCreated = ret._popContext(); + debug.checkForgottenReturns( + value, promiseCreated, "Promise.try", ret); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false); + } else { + this._resolveCallback(value, true); + } +}; +}; diff --git a/node_modules/bluebird/js/release/nodeback.js b/node_modules/bluebird/js/release/nodeback.js new file mode 100644 index 0000000..07b9f11 --- /dev/null +++ b/node_modules/bluebird/js/release/nodeback.js @@ -0,0 +1,51 @@ +"use strict"; +var util = require("./util"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = require("./errors"); +var OperationalError = errors.OperationalError; +var es5 = require("./es5"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +function nodebackForPromise(promise, multiArgs) { + return function(err, value) { + if (promise === null) return; + if (err) { + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); + promise._attachExtraTrace(wrapped); + promise._reject(wrapped); + } else if (!multiArgs) { + promise._fulfill(value); + } else { + 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); + } + promise = null; + }; +} + +module.exports = nodebackForPromise; diff --git a/node_modules/bluebird/js/release/nodeify.js b/node_modules/bluebird/js/release/nodeify.js new file mode 100644 index 0000000..ce2b190 --- /dev/null +++ b/node_modules/bluebird/js/release/nodeify.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise) { +var util = require("./util"); +var async = Promise._async; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = + tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundValue(); + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var newReason = new Error(reason + ""); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundValue(), reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = 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, + this, + nodeback + ); + } + return this; +}; +}; diff --git a/node_modules/bluebird/js/release/promise.js b/node_modules/bluebird/js/release/promise.js new file mode 100644 index 0000000..9fe8f54 --- /dev/null +++ b/node_modules/bluebird/js/release/promise.js @@ -0,0 +1,755 @@ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +var reflectHandler = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +function Proxyable() {} +var UNDEFINED_BINDING = {}; +var util = require("./util"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var es5 = require("./es5"); +var Async = require("./async"); +var async = new Async(); +es5.defineProperty(Promise, "_async", {value: async}); +var errors = require("./errors"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +var CancellationError = Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {}; +var tryConvertToPromise = require("./thenables")(Promise, INTERNAL); +var PromiseArray = + require("./promise_array")(Promise, INTERNAL, + tryConvertToPromise, apiRejection, Proxyable); +var Context = require("./context")(Promise); + /*jshint unused:false*/ +var createContext = Context.create; +var debug = require("./debuggability")(Promise, Context); +var CapturedTrace = debug.CapturedTrace; +var finallyHandler = require("./finally")(Promise, tryConvertToPromise); +var catchFilter = require("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = require("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + if (self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } +} + +function Promise(executor) { + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + if (executor !== INTERNAL) { + check(this, executor); + this._resolveFromExecutor(executor); + } + this._promiseCreated(); +} + +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 (util.isObject(item)) { + catchInstances[j++] = item; + } else { + return apiRejection("expecting an object but got " + util.classString(item)); + } + } + catchInstances.length = j; + fn = arguments[i]; + return this.then(undefined, catchFilter(catchInstances, fn, this)); + } + return this.then(undefined, fn); +}; + +Promise.prototype.reflect = function () { + return this._then(reflectHandler, + reflectHandler, undefined, this, undefined); +}; + +Promise.prototype.then = function (didFulfill, didReject) { + if (debug.warnings() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, undefined, undefined, undefined); +}; + +Promise.prototype.done = function (didFulfill, didReject) { + var promise = + this._then(didFulfill, didReject, undefined, undefined, undefined); + promise._setIsFinal(); +}; + +Promise.prototype.spread = function (fn) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + return this.all()._then(fn, undefined, undefined, APPLY, undefined); +}; + +Promise.prototype.toJSON = function () { + var ret = { + isFulfilled: false, + isRejected: false, + fulfillmentValue: undefined, + rejectionReason: undefined + }; + if (this.isFulfilled()) { + ret.fulfillmentValue = this.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + if (arguments.length > 0) { + this._warn(".all() was passed arguments but it does not take any"); + } + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = Promise.fromCallback = function(fn) { + var ret = new Promise(INTERNAL); + var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs + : false; + var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); + if (result === errorObj) { + ret._rejectCallback(result.e, true); + } + if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._setFulfilled(); + ret._rejectionHandler0 = obj; + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + _, receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var promise = haveInternalData ? internalData : new Promise(INTERNAL); + var target = this._target(); + var bitField = target._bitField; + + if (!haveInternalData) { + promise._propagateFrom(this, 3); + promise._captureStackTrace(); + if (receiver === undefined && + ((this._bitField & 2097152) !== 0)) { + if (!((bitField & 50397184) === 0)) { + receiver = this._boundValue(); + } else { + receiver = target === this ? undefined : this._boundTo; + } + } + } + + var domain = getDomain(); + if (!((bitField & 50397184) === 0)) { + var handler, value, settler = target._settlePromiseCtx; + if (((bitField & 33554432) !== 0)) { + value = target._rejectionHandler0; + handler = didFulfill; + } else if (((bitField & 16777216) !== 0)) { + value = target._fulfillmentHandler0; + handler = didReject; + target._unsetRejectionIsUnhandled(); + } else { + settler = target._settlePromiseLateCancellationObserver; + value = new CancellationError("late cancellation observer"); + target._attachExtraTrace(value); + handler = didReject; + } + + async.invoke(settler, target, { + handler: domain === null ? handler + : (typeof handler === "function" && domain.bind(handler)), + promise: promise, + receiver: receiver, + value: value + }); + } else { + target._addCallbacks(didFulfill, didReject, promise, receiver, domain); + } + + return promise; +}; + +Promise.prototype._length = function () { + return this._bitField & 65535; +}; + +Promise.prototype._isFateSealed = function () { + return (this._bitField & 117506048) !== 0; +}; + +Promise.prototype._isFollowing = function () { + return (this._bitField & 67108864) === 67108864; +}; + +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -65536) | + (len & 65535); +}; + +Promise.prototype._setFulfilled = function () { + this._bitField = this._bitField | 33554432; +}; + +Promise.prototype._setRejected = function () { + this._bitField = this._bitField | 16777216; +}; + +Promise.prototype._setFollowing = function () { + this._bitField = this._bitField | 67108864; +}; + +Promise.prototype._setIsFinal = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._isFinal = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._unsetCancelled = function() { + this._bitField = this._bitField & (~65536); +}; + +Promise.prototype._setCancelled = function() { + this._bitField = this._bitField | 65536; +}; + +Promise.prototype._setAsyncGuaranteed = function() { + this._bitField = this._bitField | 134217728; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 ? this._receiver0 : this[ + index * 4 - 4 + 3]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return this[ + index * 4 - 4 + 2]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return this[ + index * 4 - 4 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return this[ + index * 4 - 4 + 1]; +}; + +Promise.prototype._boundValue = function() {}; + +Promise.prototype._migrateCallback0 = function (follower) { + var bitField = follower._bitField; + var fulfill = follower._fulfillmentHandler0; + var reject = follower._rejectionHandler0; + var promise = follower._promise0; + var receiver = follower._receiverAt(0); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._migrateCallbackAt = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + promise, + receiver, + domain +) { + var index = this._length(); + + if (index >= 65535 - 4) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + this._receiver0 = receiver; + if (typeof fulfill === "function") { + this._fulfillmentHandler0 = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : domain.bind(reject); + } + } else { + var base = index * 4 - 4; + this[base + 2] = promise; + this[base + 3] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : domain.bind(reject); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._proxy = function (proxyable, arg) { + this._addCallbacks(undefined, undefined, arg, proxyable, null); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (((this._bitField & 117506048) !== 0)) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + if (shouldBind) this._propagateFrom(maybePromise, 2); + + var promise = maybePromise._target(); + var bitField = promise._bitField; + if (((bitField & 50397184) === 0)) { + var len = this._length(); + if (len > 0) promise._migrateCallback0(this); + for (var i = 1; i < len; ++i) { + promise._migrateCallbackAt(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (((bitField & 33554432) !== 0)) { + this._fulfill(promise._value()); + } else if (((bitField & 16777216) !== 0)) { + this._reject(promise._reason()); + } else { + var reason = new CancellationError("late cancellation observer"); + promise._attachExtraTrace(reason); + this._reject(reason); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, ignoreNonErrorWarnings) { + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { + var message = "a promise was rejected with a non-error: " + + util.classString(reason); + this._warn(message, true); + } + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason); +}; + +Promise.prototype._resolveFromExecutor = function (executor) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = this._execute(executor, function(value) { + promise._resolveCallback(value); + }, function (reason) { + promise._rejectCallback(reason, synchronous); + }); + synchronous = false; + this._popContext(); + + if (r !== undefined) { + promise._rejectCallback(r, true); + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + var bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + promise._pushContext(); + var x; + if (receiver === APPLY) { + if (!value || typeof value.length !== "number") { + x = errorObj; + x.e = new TypeError("cannot .spread() a non-array: " + + util.classString(value)); + } else { + x = tryCatch(handler).apply(this._boundValue(), value); + } + } else { + x = tryCatch(handler).call(receiver, value); + } + var promiseCreated = promise._popContext(); + bitField = promise._bitField; + if (((bitField & 65536) !== 0)) return; + + if (x === NEXT_FILTER) { + promise._reject(value); + } else if (x === errorObj || x === promise) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false); + } else { + debug.checkForgottenReturns(x, promiseCreated, "", promise); + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +Promise.prototype._settlePromise = function(promise, handler, receiver, value) { + var isPromise = promise instanceof Promise; + var bitField = this._bitField; + var asyncGuaranteed = ((bitField & 134217728) !== 0); + if (((bitField & 65536) !== 0)) { + if (isPromise) promise._invokeInternalOnCancel(); + + if (handler === finallyHandler) { + receiver.cancelPromise = promise; + if (tryCatch(handler).call(receiver, value) === errorObj) { + promise._reject(errorObj.e); + } + } else if (handler === reflectHandler) { + promise._fulfill(reflectHandler.call(receiver)); + } else if (receiver instanceof Proxyable) { + receiver._promiseCancelled(promise); + } else if (isPromise || promise instanceof PromiseArray) { + promise._cancel(); + } else { + receiver.cancel(); + } + } else if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof Proxyable) { + if (!receiver._isResolved()) { + if (((bitField & 33554432) !== 0)) { + receiver._promiseFulfilled(value, promise); + } else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (asyncGuaranteed) promise._setAsyncGuaranteed(); + if (((bitField & 33554432) !== 0)) { + promise._fulfill(value); + } else { + promise._reject(value); + } + } +}; + +Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { + var handler = ctx.handler; + var promise = ctx.promise; + var receiver = ctx.receiver; + var value = ctx.value; + if (typeof handler === "function") { + if (!(promise instanceof Promise)) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (promise instanceof Promise) { + promise._reject(value); + } +}; + +Promise.prototype._settlePromiseCtx = function(ctx) { + this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); +}; + +Promise.prototype._settlePromise0 = function(handler, value, bitField) { + var promise = this._promise0; + var receiver = this._receiverAt(0); + this._promise0 = undefined; + this._receiver0 = undefined; + this._settlePromise(promise, handler, receiver, value); +}; + +Promise.prototype._clearCallbackDataAtIndex = function(index) { + var base = index * 4 - 4; + this[base + 2] = + this[base + 3] = + this[base + 0] = + this[base + 1] = undefined; +}; + +Promise.prototype._fulfill = function (value) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + if (value === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._reject(err); + } + this._setFulfilled(); + this._rejectionHandler0 = value; + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + } +}; + +Promise.prototype._reject = function (reason) { + var bitField = this._bitField; + if (((bitField & 117506048) >>> 16)) return; + this._setRejected(); + this._fulfillmentHandler0 = reason; + + if (this._isFinal()) { + return async.fatalError(reason, util.isNode); + } + + if ((bitField & 65535) > 0) { + if (((bitField & 134217728) !== 0)) { + this._settlePromises(); + } else { + async.settlePromises(this); + } + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._fulfillPromises = function (len, value) { + for (var i = 1; i < len; i++) { + var handler = this._fulfillmentHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, value); + } +}; + +Promise.prototype._rejectPromises = function (len, reason) { + for (var i = 1; i < len; i++) { + var handler = this._rejectionHandlerAt(i); + var promise = this._promiseAt(i); + var receiver = this._receiverAt(i); + this._clearCallbackDataAtIndex(i); + this._settlePromise(promise, handler, receiver, reason); + } +}; + +Promise.prototype._settlePromises = function () { + var bitField = this._bitField; + var len = (bitField & 65535); + + if (len > 0) { + if (((bitField & 16842752) !== 0)) { + var reason = this._fulfillmentHandler0; + this._settlePromise0(this._rejectionHandler0, reason, bitField); + this._rejectPromises(len, reason); + } else { + var value = this._rejectionHandler0; + this._settlePromise0(this._fulfillmentHandler0, value, bitField); + this._fulfillPromises(len, value); + } + this._setLength(0); + } + this._clearCancellationData(); +}; + +Promise.prototype._settledValue = function() { + var bitField = this._bitField; + if (((bitField & 33554432) !== 0)) { + return this._rejectionHandler0; + } else if (((bitField & 16777216) !== 0)) { + return this._fulfillmentHandler0; + } +}; + +function deferResolve(v) {this.promise._resolveCallback(v);} +function deferReject(v) {this.promise._rejectCallback(v, false);} + +Promise.defer = Promise.pending = function() { + debug.deprecated("Promise.defer", "new Promise"); + var promise = new Promise(INTERNAL); + return { + promise: promise, + resolve: deferResolve, + reject: deferReject + }; +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, + debug); +require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); +require("./cancel")(Promise, PromiseArray, apiRejection, debug); +require("./direct_resolve")(Promise); +require("./synchronous_inspection")(Promise); +require("./join")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug); +Promise.Promise = Promise; +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); +require('./timers.js')(Promise, INTERNAL); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); +require('./nodeify.js')(Promise); +require('./call_get.js')(Promise); +require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +require('./settle.js')(Promise, PromiseArray, debug); +require('./some.js')(Promise, PromiseArray, apiRejection); +require('./promisify.js')(Promise, INTERNAL); +require('./any.js')(Promise); +require('./each.js')(Promise, INTERNAL); +require('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + debug.setBounds(Async.firstLineError, util.lastLineError); + return Promise; + +}; diff --git a/node_modules/bluebird/js/release/promise_array.js b/node_modules/bluebird/js/release/promise_array.js new file mode 100644 index 0000000..6400723 --- /dev/null +++ b/node_modules/bluebird/js/release/promise_array.js @@ -0,0 +1,184 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = require("./util"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + if (values instanceof Promise) { + promise._propagateFrom(values, 3); + } + promise._setOnCancel(this); + this._values = values; + this._length = 0; + this._totalResolved = 0; + this._init(undefined, -2); +} +util.inherits(PromiseArray, Proxyable); + +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, this._promise); + if (values instanceof Promise) { + values = values._target(); + var bitField = values._bitField; + ; + this._values = values; + + if (((bitField & 50397184) === 0)) { + this._promise._setAsyncGuaranteed(); + return values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + } else if (((bitField & 33554432) !== 0)) { + values = values._value(); + } else if (((bitField & 16777216) !== 0)) { + return this._reject(values._reason()); + } else { + return this._cancel(); + } + } + values = util.asArray(values); + if (values === null) { + var err = apiRejection( + "expecting an array or an iterable object but got " + util.classString(values)).reason(); + this._promise._rejectCallback(err, false); + return; + } + + if (values.length === 0) { + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); + } + else { + this._resolve(toResolutionValue(resolveValueIfEmpty)); + } + return; + } + this._iterate(values); +}; + +PromiseArray.prototype._iterate = function(values) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var result = this._promise; + var isResolved = false; + var bitField = null; + for (var i = 0; i < len; ++i) { + var maybePromise = tryConvertToPromise(values[i], result); + + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + bitField = maybePromise._bitField; + } else { + bitField = null; + } + + if (isResolved) { + if (bitField !== null) { + maybePromise.suppressUnhandledRejections(); + } + } else if (bitField !== null) { + if (((bitField & 50397184) === 0)) { + maybePromise._proxy(this, i); + this._values[i] = maybePromise; + } else if (((bitField & 33554432) !== 0)) { + isResolved = this._promiseFulfilled(maybePromise._value(), i); + } else if (((bitField & 16777216) !== 0)) { + isResolved = this._promiseRejected(maybePromise._reason(), i); + } else { + isResolved = this._promiseCancelled(i); + } + } else { + isResolved = this._promiseFulfilled(maybePromise, i); + } + } + if (!isResolved) result._setAsyncGuaranteed(); +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype._cancel = function() { + if (this._isResolved() || !this._promise.isCancellable()) return; + this._values = null; + this._promise._cancel(); +}; + +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false); +}; + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +PromiseArray.prototype._promiseCancelled = function() { + this._cancel(); + return true; +}; + +PromiseArray.prototype._promiseRejected = function (reason) { + this._totalResolved++; + this._reject(reason); + return true; +}; + +PromiseArray.prototype._resultCancelled = function() { + if (this._isResolved()) return; + var values = this._values; + this._cancel(); + if (values instanceof Promise) { + values.cancel(); + } else { + for (var i = 0; i < values.length; ++i) { + if (values[i] instanceof Promise) { + values[i].cancel(); + } + } + } +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; diff --git a/node_modules/bluebird/js/release/promisify.js b/node_modules/bluebird/js/release/promisify.js new file mode 100644 index 0000000..aa98e5b --- /dev/null +++ b/node_modules/bluebird/js/release/promisify.js @@ -0,0 +1,314 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = require("./util"); +var nodebackForPromise = require("./nodeback"); +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = require("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyProps = [ + "arity", "length", + "name", + "arguments", + "caller", + "callee", + "prototype", + "__isPromisified__" +]; +var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); + +var defaultFilter = function(name) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + name !== "constructor"; +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +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/MqrFmX\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]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!false) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn, _, multiArgs) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); 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]); + } + + 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] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + var body = "'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ + return promise; \n\ + }; \n\ + notEnumerableProp(ret, '__isPromisified__', true); \n\ + return ret; \n\ + ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode); + body = body.replace("Parameters", parameterDeclaration(newParameterCount)); + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "notEnumerableProp", + "INTERNAL", + body)( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + util.notEnumerableProp, + INTERNAL); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise, multiArgs); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); + return promise; + } + util.notEnumerableProp(promisified, "__isPromisified__", true); + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { + 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; + if (promisifier === makeNodePromisified) { + obj[promisifiedKey] = + makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); + } else { + var promisified = promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, + fn, suffix, multiArgs); + }); + util.notEnumerableProp(promisified, "__isPromisified__", true); + obj[promisifiedKey] = promisified; + } + } + util.toFastProperties(obj); + return obj; +} + +function promisify(callback, receiver, multiArgs) { + return makeNodePromisified(callback, receiver, undefined, + callback, null, multiArgs); +} + +Promise.promisify = function (fn, options) { + if (typeof fn !== "function") { + throw new TypeError("expecting a function but got " + util.classString(fn)); + } + if (isPromisified(fn)) { + return fn; + } + options = Object(options); + var receiver = options.context === undefined ? THIS : options.context; + var multiArgs = !!options.multiArgs; + var ret = promisify(fn, receiver, multiArgs); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +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/MqrFmX\u000a"); + } + options = Object(options); + var multiArgs = !!options.multiArgs; + 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/MqrFmX\u000a"); + } + + var keys = util.inheritedDataKeys(target); + 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, + multiArgs); + promisifyAll(value, suffix, filter, promisifier, multiArgs); + } + } + + return promisifyAll(target, suffix, filter, promisifier, multiArgs); +}; +}; + diff --git a/node_modules/bluebird/js/release/props.js b/node_modules/bluebird/js/release/props.js new file mode 100644 index 0000000..fc981ce --- /dev/null +++ b/node_modules/bluebird/js/release/props.js @@ -0,0 +1,118 @@ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = require("./util"); +var isObject = util.isObject; +var es5 = require("./es5"); +var Es6Map; +if (typeof Map === "function") Es6Map = Map; + +var mapToEntries = (function() { + var index = 0; + var size = 0; + + function extractEntry(value, key) { + this[index] = value; + this[index + size] = key; + index++; + } + + return function mapToEntries(map) { + size = map.size; + index = 0; + var ret = new Array(map.size * 2); + map.forEach(extractEntry, ret); + return ret; + }; +})(); + +var entriesToMap = function(entries) { + var ret = new Es6Map(); + var length = entries.length / 2 | 0; + for (var i = 0; i < length; ++i) { + var key = entries[length + i]; + var value = entries[i]; + ret.set(key, value); + } + return ret; +}; + +function PropertiesPromiseArray(obj) { + var isMap = false; + var entries; + if (Es6Map !== undefined && obj instanceof Es6Map) { + entries = mapToEntries(obj); + isMap = true; + } else { + var keys = es5.keys(obj); + var len = keys.length; + entries = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + entries[i] = obj[key]; + entries[i + len] = key; + } + } + this.constructor$(entries); + this._isMap = isMap; + this._init$(undefined, -3); +} +util.inherits(PropertiesPromiseArray, PromiseArray); + +PropertiesPromiseArray.prototype._init = function () {}; + +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + var val; + if (this._isMap) { + val = entriesToMap(this._values); + } else { + 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); + return true; + } + return false; +}; + +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; +}; + +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); + + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\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, 2); + } + return ret; +} + +Promise.prototype.props = function () { + return props(this); +}; + +Promise.props = function (promises) { + return props(promises); +}; +}; diff --git a/node_modules/bluebird/js/main/queue.js b/node_modules/bluebird/js/release/queue.js similarity index 100% rename from node_modules/bluebird/js/main/queue.js rename to node_modules/bluebird/js/release/queue.js diff --git a/node_modules/bluebird/js/release/race.js b/node_modules/bluebird/js/release/race.js new file mode 100644 index 0000000..b862f46 --- /dev/null +++ b/node_modules/bluebird/js/release/race.js @@ -0,0 +1,49 @@ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = require("./util"); + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else { + promises = util.asArray(promises); + if (promises === null) + return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); + } + + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 3); + } + 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 && !(i in promises)) { + 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); +}; + +}; diff --git a/node_modules/bluebird/js/release/reduce.js b/node_modules/bluebird/js/release/reduce.js new file mode 100644 index 0000000..8f73500 --- /dev/null +++ b/node_modules/bluebird/js/release/reduce.js @@ -0,0 +1,162 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +var util = require("./util"); +var tryCatch = util.tryCatch; + +function ReductionPromiseArray(promises, fn, initialValue, _each) { + this.constructor$(promises); + var domain = getDomain(); + this._fn = domain === null ? fn : domain.bind(fn); + if (initialValue !== undefined) { + initialValue = Promise.resolve(initialValue); + initialValue._attachCancellationCallback(this); + } + this._initialValue = initialValue; + this._currentCancellable = null; + this._eachValues = _each === INTERNAL ? [] : undefined; + this._promise._captureStackTrace(); + this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); + +ReductionPromiseArray.prototype._gotAccum = function(accum) { + if (this._eachValues !== undefined && accum !== INTERNAL) { + this._eachValues.push(accum); + } +}; + +ReductionPromiseArray.prototype._eachComplete = function(value) { + this._eachValues.push(value); + return this._eachValues; +}; + +ReductionPromiseArray.prototype._init = function() {}; + +ReductionPromiseArray.prototype._resolveEmptyArray = function() { + this._resolve(this._eachValues !== undefined ? this._eachValues + : this._initialValue); +}; + +ReductionPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; + +ReductionPromiseArray.prototype._resolve = function(value) { + this._promise._resolveCallback(value); + this._values = null; +}; + +ReductionPromiseArray.prototype._resultCancelled = function(sender) { + if (sender === this._initialValue) return this._cancel(); + if (this._isResolved()) return; + this._resultCancelled$(); + if (this._currentCancellable instanceof Promise) { + this._currentCancellable.cancel(); + } + if (this._initialValue instanceof Promise) { + this._initialValue.cancel(); + } +}; + +ReductionPromiseArray.prototype._iterate = function (values) { + this._values = values; + var value; + var i; + var length = values.length; + if (this._initialValue !== undefined) { + value = this._initialValue; + i = 0; + } else { + value = Promise.resolve(values[0]); + i = 1; + } + + this._currentCancellable = value; + + if (!value.isRejected()) { + for (; i < length; ++i) { + var ctx = { + accum: null, + value: values[i], + index: i, + length: length, + array: this + }; + value = value._then(gotAccum, undefined, undefined, ctx, undefined); + } + } + + if (this._eachValues !== undefined) { + value = value + ._then(this._eachComplete, undefined, undefined, this, undefined); + } + value._then(completed, completed, undefined, value, this); +}; + +Promise.prototype.reduce = function (fn, initialValue) { + return reduce(this, fn, initialValue, null); +}; + +Promise.reduce = function (promises, fn, initialValue, _each) { + return reduce(promises, fn, initialValue, _each); +}; + +function completed(valueOrReason, array) { + if (this.isFulfilled()) { + array._resolve(valueOrReason); + } else { + array._reject(valueOrReason); + } +} + +function reduce(promises, fn, initialValue, _each) { + if (typeof fn !== "function") { + return apiRejection("expecting a function but got " + util.classString(fn)); + } + var array = new ReductionPromiseArray(promises, fn, initialValue, _each); + return array.promise(); +} + +function gotAccum(accum) { + this.accum = accum; + this.array._gotAccum(accum); + var value = tryConvertToPromise(this.value, this.array._promise); + if (value instanceof Promise) { + this.array._currentCancellable = value; + return value._then(gotValue, undefined, undefined, this, undefined); + } else { + return gotValue.call(this, value); + } +} + +function gotValue(value) { + var array = this.array; + var promise = array._promise; + var fn = tryCatch(array._fn); + promise._pushContext(); + var ret; + if (array._eachValues !== undefined) { + ret = fn.call(promise._boundValue(), value, this.index, this.length); + } else { + ret = fn.call(promise._boundValue(), + this.accum, value, this.index, this.length); + } + if (ret instanceof Promise) { + array._currentCancellable = ret; + } + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, + promiseCreated, + array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", + promise + ); + return ret; +} +}; diff --git a/node_modules/bluebird/js/release/schedule.js b/node_modules/bluebird/js/release/schedule.js new file mode 100644 index 0000000..0e3e0f5 --- /dev/null +++ b/node_modules/bluebird/js/release/schedule.js @@ -0,0 +1,35 @@ +"use strict"; +var util = require("./util"); +var schedule; +var noAsyncScheduler = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); +}; +if (util.isNode && typeof MutationObserver === "undefined") { + var GlobalSetImmediate = global.setImmediate; + var ProcessNextTick = process.nextTick; + schedule = util.isRecentNode + ? function(fn) { GlobalSetImmediate.call(global, fn); } + : function(fn) { ProcessNextTick.call(process, fn); }; +} else if ((typeof MutationObserver !== "undefined") && + !(typeof window !== "undefined" && + window.navigator && + window.navigator.standalone)) { + schedule = function(fn) { + var div = document.createElement("div"); + var observer = new MutationObserver(fn); + observer.observe(div, {attributes: true}); + return function() { div.classList.toggle("foo"); }; + }; + schedule.isStatic = true; +} else if (typeof setImmediate !== "undefined") { + schedule = function (fn) { + setImmediate(fn); + }; +} else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); + }; +} else { + schedule = noAsyncScheduler; +} +module.exports = schedule; diff --git a/node_modules/bluebird/js/release/settle.js b/node_modules/bluebird/js/release/settle.js new file mode 100644 index 0000000..fade3a1 --- /dev/null +++ b/node_modules/bluebird/js/release/settle.js @@ -0,0 +1,43 @@ +"use strict"; +module.exports = + function(Promise, PromiseArray, debug) { +var PromiseInspection = Promise.PromiseInspection; +var util = require("./util"); + +function SettledPromiseArray(values) { + this.constructor$(values); +} +util.inherits(SettledPromiseArray, PromiseArray); + +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { + this._values[index] = inspection; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + return true; + } + return false; +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 33554432; + ret._settledValueField = value; + return this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + var ret = new PromiseInspection(); + ret._bitField = 16777216; + ret._settledValueField = reason; + return this._promiseResolved(index, ret); +}; + +Promise.settle = function (promises) { + debug.deprecated(".settle()", ".reflect()"); + return new SettledPromiseArray(promises).promise(); +}; + +Promise.prototype.settle = function () { + return Promise.settle(this); +}; +}; diff --git a/node_modules/bluebird/js/release/some.js b/node_modules/bluebird/js/release/some.js new file mode 100644 index 0000000..400d852 --- /dev/null +++ b/node_modules/bluebird/js/release/some.js @@ -0,0 +1,148 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = require("./util"); +var RangeError = require("./errors").RangeError; +var AggregateError = require("./errors").AggregateError; +var isArray = util.isArray; +var CANCELLATION = {}; + + +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) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + 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); + } + return true; + } + return false; + +}; +SomePromiseArray.prototype._promiseRejected = function (reason) { + this._addRejected(reason); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._promiseCancelled = function () { + if (this._values instanceof Promise || this._values == null) { + return this._cancel(); + } + this._addRejected(CANCELLATION); + return this._checkOutcome(); +}; + +SomePromiseArray.prototype._checkOutcome = function() { + if (this.howMany() > this._canPossiblyFulfill()) { + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + if (this._values[i] !== CANCELLATION) { + e.push(this._values[i]); + } + } + if (e.length > 0) { + this._reject(e); + } else { + this._cancel(); + } + return true; + } + return false; +}; + +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/MqrFmX\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + 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; +}; diff --git a/node_modules/bluebird/js/release/synchronous_inspection.js b/node_modules/bluebird/js/release/synchronous_inspection.js new file mode 100644 index 0000000..fb0c1a6 --- /dev/null +++ b/node_modules/bluebird/js/release/synchronous_inspection.js @@ -0,0 +1,96 @@ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValueField = promise._isFateSealed() + ? promise._settledValue() : undefined; + } + else { + this._bitField = 0; + this._settledValueField = undefined; + } +} + +PromiseInspection.prototype._settledValue = function() { + return this._settledValueField; +}; + +var value = PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var reason = PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + return this._settledValue(); +}; + +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { + return (this._bitField & 33554432) !== 0; +}; + +var isRejected = PromiseInspection.prototype.isRejected = function () { + return (this._bitField & 16777216) !== 0; +}; + +var isPending = PromiseInspection.prototype.isPending = function () { + return (this._bitField & 50397184) === 0; +}; + +var isResolved = PromiseInspection.prototype.isResolved = function () { + return (this._bitField & 50331648) !== 0; +}; + +PromiseInspection.prototype.isCancelled = +Promise.prototype._isCancelled = function() { + return (this._bitField & 65536) === 65536; +}; + +Promise.prototype.isCancelled = function() { + return this._target()._isCancelled(); +}; + +Promise.prototype.isPending = function() { + return isPending.call(this._target()); +}; + +Promise.prototype.isRejected = function() { + return isRejected.call(this._target()); +}; + +Promise.prototype.isFulfilled = function() { + return isFulfilled.call(this._target()); +}; + +Promise.prototype.isResolved = function() { + return isResolved.call(this._target()); +}; + +Promise.prototype.value = function() { + return value.call(this._target()); +}; + +Promise.prototype.reason = function() { + var target = this._target(); + target._unsetRejectionIsUnhandled(); + return reason.call(target); +}; + +Promise.prototype._value = function() { + return this._settledValue(); +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue(); +}; + +Promise.PromiseInspection = PromiseInspection; +}; diff --git a/node_modules/bluebird/js/release/thenables.js b/node_modules/bluebird/js/release/thenables.js new file mode 100644 index 0000000..a04fdde --- /dev/null +++ b/node_modules/bluebird/js/release/thenables.js @@ -0,0 +1,82 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) return obj; + var then = getThen(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfill, + ret._reject, + undefined, + ret, + null + ); + return ret; + } + return doThenable(obj, then, context); + } + } + return obj; +} + +function doGetThen(obj) { + return obj.then; +} + +function getThen(obj) { + try { + return doGetThen(obj); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, resolve, reject); + synchronous = false; + + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolve(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function reject(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + return ret; +} + +return tryConvertToPromise; +}; diff --git a/node_modules/bluebird/js/release/timers.js b/node_modules/bluebird/js/release/timers.js new file mode 100644 index 0000000..1e56acd --- /dev/null +++ b/node_modules/bluebird/js/release/timers.js @@ -0,0 +1,66 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./util"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message, parent) { + if (!promise.isPending()) return; + var err; + if (typeof message !== "string") { + if (message instanceof Error) { + err = message; + } else { + err = new TimeoutError("operation timed out"); + } + } else { + err = new TimeoutError(message); + } + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._reject(err); + parent.cancel(); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (ms, value) { + var ret; + if (value !== undefined) { + ret = Promise.resolve(value) + ._then(afterValue, null, null, ms, undefined); + } else { + ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, +ms); + } + ret._setAsyncGuaranteed(); + return ret; +}; + +Promise.prototype.delay = function (ms) { + return delay(ms, this); +}; + +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 parent = this.then(); + var ret = parent.then(); + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message, parent); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; diff --git a/node_modules/bluebird/js/release/using.js b/node_modules/bluebird/js/release/using.js new file mode 100644 index 0000000..6616794 --- /dev/null +++ b/node_modules/bluebird/js/release/using.js @@ -0,0 +1,225 @@ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext, INTERNAL, debug) { + var util = require("./util"); + var TypeError = require("./errors").TypeError; + var inherits = require("./util").inherits; + var errorObj = util.errorObj; + var tryCatch = util.tryCatch; + + function thrower(e) { + setTimeout(function(){throw e;}, 0); + } + + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + 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 = new Promise(INTERNAL); + function iterator() { + if (i >= len) return ret._fulfill(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); + } + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); + } + } + iterator(); + } + iterator(); + return ret; + } + + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + 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().value(); + } + return null; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + function ResourceList(length) { + this.length = length; + this.promise = null; + this[length-1] = null; + } + + ResourceList.prototype._resultCancelled = function() { + var len = this.length; + for (var i = 0; i < len; ++i) { + var item = this[i]; + if (item instanceof Promise) { + item.cancel(); + } + } + }; + + 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("expecting a function but got " + util.classString(fn)); + } + var input; + var spreadArgs = true; + if (len === 2 && Array.isArray(arguments[0])) { + input = arguments[0]; + len = input.length; + spreadArgs = false; + } else { + input = arguments; + len--; + } + var resources = new ResourceList(len); + for (var i = 0; i < len; ++i) { + var resource = input[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } + } + resources[i] = resource; + } + + var reflectedResources = new Array(resources.length); + for (var i = 0; i < reflectedResources.length; ++i) { + reflectedResources[i] = Promise.resolve(resources[i]).reflect(); + } + + var resultPromise = Promise.all(reflectedResources) + .then(function(inspections) { + for (var i = 0; i < inspections.length; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + errorObj.e = inspection.error(); + return errorObj; + } else if (!inspection.isFulfilled()) { + resultPromise.cancel(); + return; + } + inspections[i] = inspection.value(); + } + promise._pushContext(); + + fn = tryCatch(fn); + var ret = spreadArgs + ? fn.apply(undefined, inspections) : fn(inspections); + var promiseCreated = promise._popContext(); + debug.checkForgottenReturns( + ret, promiseCreated, "Promise.using", promise); + return ret; + }); + + var promise = resultPromise.lastly(function() { + var inspection = new Promise.PromiseInspection(resultPromise); + return dispose(resources, inspection); + }); + resources.promise = promise; + promise._setOnCancel(resources); + return promise; + }; + + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 131072; + this._disposer = disposer; + }; + + Promise.prototype._isDisposable = function () { + return (this._bitField & 131072) > 0; + }; + + Promise.prototype._getDisposer = function () { + return this._disposer; + }; + + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~131072); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); + } + throw new TypeError(); + }; + +}; diff --git a/node_modules/bluebird/js/release/util.js b/node_modules/bluebird/js/release/util.js new file mode 100644 index 0000000..2f001c0 --- /dev/null +++ b/node_modules/bluebird/js/release/util.js @@ -0,0 +1,344 @@ +"use strict"; +var es5 = require("./es5"); +var canEvaluate = typeof navigator == "undefined"; + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +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 isPrimitive(val) { + return val == null || val === true || val === false || + typeof val === "string" || typeof val === "number"; + +} + +function isObject(value) { + return typeof value === "function" || + typeof value === "object" && value !== null; +} + +function maybeWrapAsError(maybeError) { + if (!isPrimitive(maybeError)) return maybeError; + + return new Error(safeToString(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; +} + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; + + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; + + if (es5.isES5) { + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && !isExcludedProto(obj)) { + 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 { + var hasProp = {}.hasOwnProperty; + return function(obj) { + if (isExcludedProto(obj)) return []; + var ret = []; + + /*jshint forin:false */ + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } + } + return ret; + }; + } + +})(); + +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function FakeConstructor() {} + FakeConstructor.prototype = obj; + var l = 8; + while (l--) new FakeConstructor(); + return obj; + 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; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} + } + } +} + +var asArray = function(v) { + if (es5.isArray(v)) { + return v; + } + return null; +}; + +if (typeof Symbol !== "undefined" && Symbol.iterator) { + var ArrayFrom = typeof Array.from === "function" ? function(v) { + return Array.from(v); + } : function(v) { + var ret = []; + var it = v[Symbol.iterator](); + var itResult; + while (!((itResult = it.next()).done)) { + ret.push(itResult.value); + } + return ret; + }; + + asArray = function(v) { + if (es5.isArray(v)) { + return v; + } else if (v != null && typeof v[Symbol.iterator] === "function") { + return ArrayFrom(v); + } + return null; + }; +} + +var isNode = typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]"; + +function env(key, def) { + return isNode ? process.env[key] : def; +} + +var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, + thrower: thrower, + isArray: es5.isArray, + asArray: asArray, + notEnumerableProp: notEnumerableProp, + isPrimitive: isPrimitive, + isObject: isObject, + canEvaluate: canEvaluate, + errorObj: errorObj, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: isNode, + env: env +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; diff --git a/node_modules/bluebird/package.json b/node_modules/bluebird/package.json index a7409f3..d9e1b01 100644 --- a/node_modules/bluebird/package.json +++ b/node_modules/bluebird/package.json @@ -1,42 +1,49 @@ { - "name": "bluebird", - "description": "Full featured Promises/A+ implementation with exceptionally good performance", - "version": "2.9.24", - "keywords": [ - "promise", - "performance", - "promises", - "promises-a", - "promises-aplus", - "async", - "await", - "deferred", - "deferreds", - "future", - "flow control", - "dsl", - "fluent interface" + "_args": [ + [ + "bluebird", + "/Users/akira/src/biomedjs" + ] ], - "scripts": { - "lint": "node scripts/jshint.js", - "test": "node tools/test.js", - "istanbul": "istanbul", - "prepublish": "node tools/build.js --no-debug --main --zalgo --browser --minify" + "_from": "bluebird@*", + "_id": "bluebird@3.0.6", + "_inCache": true, + "_installable": true, + "_location": "/bluebird", + "_nodeVersion": "2.3.0", + "_npmUser": { + "email": "petka_antonov@hotmail.com", + "name": "esailija" }, - "homepage": "https://github.com/petkaantonov/bluebird", - "repository": { - "type": "git", - "url": "git://github.com/petkaantonov/bluebird.git" + "_npmVersion": "2.11.1", + "_phantomChildren": {}, + "_requested": { + "name": "bluebird", + "raw": "bluebird", + "rawSpec": "", + "scope": null, + "spec": "*", + "type": "range" }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.0.6.tgz", + "_shasum": "f2488f325782f66d174842f481992e2faba56f38", + "_shrinkwrap": null, + "_spec": "bluebird", + "_where": "/Users/akira/src/biomedjs", + "author": { + "email": "petka_antonov@hotmail.com", + "name": "Petka Antonov", + "url": "http://github.com/petkaantonov/" + }, + "browser": "./js/browser/bluebird.js", "bugs": { "url": "http://github.com/petkaantonov/bluebird/issues" }, - "license": "MIT", - "author": { - "name": "Petka Antonov", - "email": "petka_antonov@hotmail.com", - "url": "http://github.com/petkaantonov/" - }, + "dependencies": {}, + "description": "Full featured Promises/A+ implementation with exceptionally good performance", "devDependencies": { "acorn": "~0.6.0", "baconjs": "^0.7.43", @@ -52,6 +59,7 @@ "istanbul": "^0.3.5", "jshint": "^2.6.0", "jshint-stylish": "~0.2.0", + "kefir": "^2.4.1", "mkdirp": "~0.5.0", "mocha": "~2.1", "open": "~0.0.5", @@ -62,21 +70,54 @@ "sinon": "~1.7.3", "uglify-js": "~2.4.16" }, - "readmeFilename": "README.md", - "main": "./js/main/bluebird.js", - "browser": "./js/browser/bluebird.js", - "files": [ - "js/browser", - "js/main", - "js/zalgo", - "LICENSE", - "zalgo.js" - ], - "readme": "\n \"Promises/A+\n\n[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)\n[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)\n\n\n# Introduction\n\nBluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance\n\n\n\n# Topics\n\n- [Features](#features)\n- [Quick start](#quick-start)\n- [API Reference and examples](API.md)\n- [Support](#support)\n- [What are promises and why should I use them?](#what-are-promises-and-why-should-i-use-them)\n- [Questions and issues](#questions-and-issues)\n- [Error handling](#error-handling)\n- [Development](#development)\n - [Testing](#testing)\n - [Benchmarking](#benchmarks)\n - [Custom builds](#custom-builds)\n - [For library authors](#for-library-authors)\n- [What is the sync build?](#what-is-the-sync-build)\n- [License](#license)\n- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)\n- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)\n- [Changelog](changelog.md)\n- [Optimization guide](#optimization-guide)\n\n# Features\n\"bluebird\n\n- [Promises A+](http://promisesaplus.com)\n- [Synchronous inspection](API.md#synchronous-inspection)\n- [Concurrency coordination](API.md#collections)\n- [Promisification on steroids](API.md#promisification)\n- [Resource management through a parallel of python `with`/C# `using`](API.md#resource-management)\n- [Cancellation and timeouts](API.md#cancellation)\n- [Parallel for C# `async` and `await`](API.md#generators)\n- Mind blowing utilities such as\n - [`.bind()`](API.md#binddynamic-thisarg---promise)\n - [`.call()`](API.md#callstring-propertyname--dynamic-arg---promise)\n - [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise)\n - [And](API.md#core) [much](API.md#timers) [more](API.md#utility)!\n- [Practical debugging solutions and sane defaults](#error-handling)\n- [Sick performance](benchmark/)\n\n
\n\n# Quick start\n\n## Node.js\n\n npm install bluebird\n\nThen:\n\n```js\nvar Promise = require(\"bluebird\");\n```\n\n## Browsers\n\nThere are many ways to use bluebird in browsers:\n\n- Direct downloads\n - Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js)\n - Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js)\n- You may use browserify on the main export\n- You may use the [bower](http://bower.io) package.\n\nWhen using script tags the global variables `Promise` and `P` (alias for `Promise`) become available.\n\nA [minimal bluebird browser build](#custom-builds) is ≈38.92KB minified*, 11.65KB gzipped and has no external dependencies.\n\n*Google Closure Compiler using Simple.\n\n#### Browser support\n\nBrowsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported.\n\n[![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov)\n\n**Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`.\n\nAlso, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+.\n\nAfter quick start, see [API Reference and examples](API.md)\n\n
\n\n# Support\n\n- Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js)\n- IRC: #promises @freenode\n- StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird)\n- Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open)\n\n
\n\n# What are promises and why should I use them?\n\nYou should use promises to turn this:\n\n```js\nfs.readFile(\"file.json\", function(err, val) {\n if( err ) {\n console.error(\"unable to read file\");\n }\n else {\n try {\n val = JSON.parse(val);\n console.log(val.success);\n }\n catch( e ) {\n console.error(\"invalid json in file\");\n }\n }\n});\n```\n\nInto this:\n\n```js\nfs.readFileAsync(\"file.json\").then(JSON.parse).then(function(val) {\n console.log(val.success);\n})\n.catch(SyntaxError, function(e) {\n console.error(\"invalid json in file\");\n})\n.catch(function(e) {\n console.error(\"unable to read file\")\n});\n```\n\n*If you are wondering \"there is no `readFileAsync` method on `fs` that returns a promise\", see [promisification](API.md#promisification)*\n\nActually you might notice the latter has a lot in common with code that would do the same using synchronous I/O:\n\n```js\ntry {\n var val = JSON.parse(fs.readFileSync(\"file.json\"));\n console.log(val.success);\n}\n//Syntax actually not supported in JS but drives the point\ncatch(SyntaxError e) {\n console.error(\"invalid json in file\");\n}\ncatch(Error e) {\n console.error(\"unable to read file\")\n}\n```\n\nAnd that is the point - being able to have something that is a lot like `return` and `throw` in synchronous code.\n\nYou can also use promises to improve code that was written with callback helpers:\n\n\n```js\n//Copyright Plato http://stackoverflow.com/a/19385911/995876\n//CC BY-SA 2.5\nmapSeries(URLs, function (URL, done) {\n var options = {};\n needle.get(URL, options, function (error, response, body) {\n if (error) {\n return done(error)\n }\n try {\n var ret = JSON.parse(body);\n return done(null, ret);\n }\n catch (e) {\n done(e);\n }\n });\n}, function (err, results) {\n if (err) {\n console.log(err)\n } else {\n console.log('All Needle requests successful');\n // results is a 1 to 1 mapping in order of URLs > needle.body\n processAndSaveAllInDB(results, function (err) {\n if (err) {\n return done(err)\n }\n console.log('All Needle requests saved');\n done(null);\n });\n }\n});\n```\n\nIs more pleasing to the eye when done with promises:\n\n```js\nPromise.promisifyAll(needle);\nvar options = {};\n\nvar current = Promise.resolve();\nPromise.map(URLs, function(URL) {\n current = current.then(function () {\n return needle.getAsync(URL, options);\n });\n return current;\n}).map(function(responseAndBody){\n return JSON.parse(responseAndBody[1]);\n}).then(function (results) {\n return processAndSaveAllInDB(results);\n}).then(function(){\n console.log('All Needle requests saved');\n}).catch(function (e) {\n console.log(e);\n});\n```\n\nAlso promises don't just give you correspondences for synchronous features but can also be used as limited event emitters or callback aggregators.\n\nMore reading:\n\n - [Promise nuggets](https://promise-nuggets.github.io/)\n - [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html)\n - [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1)\n - [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)\n - [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)\n\n# Questions and issues\n\nIf you find a bug in bluebird or have a feature request, file an issue in the [github issue tracker](https://github.com/petkaantonov/bluebird/issues). Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`.\n\n# Error handling\n\nThis is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled.\n\nThere are two common pragmatic attempts at solving the problem that promise libraries do.\n\nThe more popular one is to have the user explicitly communicate that they are done and any unhandled rejections should be thrown, like so:\n\n```js\ndownload().then(...).then(...).done();\n```\n\nFor handling this problem, in my opinion, this is completely unacceptable and pointless. The user must remember to explicitly call `.done` and that cannot be justified when the problem is forgetting to create an error handler in the first place.\n\nThe second approach, which is what bluebird by default takes, is to call a registered handler if a rejection is unhandled by the start of a second turn. The default handler is to write the stack trace to `stderr` or `console.error` in browsers. This is close to what happens with synchronous code - your code doesn't work as expected and you open console and see a stack trace. Nice.\n\nOf course this is not perfect, if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages. In that case you can use the `.done()` method to signal that any hanging exceptions should be thrown.\n\nIf you want to override the default handler for these possibly unhandled rejections, you can pass yours like so:\n\n```js\nPromise.onPossiblyUnhandledRejection(function(error){\n throw error;\n});\n```\n\nIf you want to also enable long stack traces, call:\n\n```js\nPromise.longStackTraces();\n```\n\nright after the library is loaded.\n\nIn node.js use the environment flag `BLUEBIRD_DEBUG`:\n\n```\nBLUEBIRD_DEBUG=1 node server.js\n```\n\nto enable long stack traces in all instances of bluebird.\n\nLong stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, even after using every trick to optimize them.\n\nLong stack traces are enabled by default in the debug build.\n\n#### Expected and unexpected errors\n\nA practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about.\n\nNow, Javascript does have a perfectly fine and working way of creating error type hierarchies. It is still quite awkward to use them with the built-in `try-catch` however:\n\n```js\ntry {\n //code\n}\ncatch(e) {\n if( e instanceof WhatIWantError) {\n //handle\n }\n else {\n throw e;\n }\n}\n```\n\nWithout such checking, unexpected errors would be silently swallowed. However, with promises, bluebird brings the future (hopefully) here now and extends the `.catch` to [accept potential error type eligibility](API.md#catchfunction-errorclass-function-handler---promise).\n\nFor instance here it is expected that some evil or incompetent entity will try to crash our server from `SyntaxError` by providing syntactically invalid JSON:\n\n```js\ngetJSONFromSomewhere().then(function(jsonString) {\n return JSON.parse(jsonString);\n}).then(function(object) {\n console.log(\"it was valid json: \", object);\n}).catch(SyntaxError, function(e){\n console.log(\"don't be evil\");\n});\n```\n\nHere any kind of unexpected error will automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`.\n\nOk, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors?\n\nBluebird defines a special error type `OperationalError` (you can get a reference from `Promise.OperationalError`). This type of error is given as rejection reason by promisified methods when\ntheir underlying library gives an untyped, but expected error. Primitives such as strings, and error objects that are directly created like `new Error(\"database didn't respond\")` are considered untyped.\n\nExample of such library is the node core library `fs`. So if we promisify it, we can catch just the errors we want pretty easily and have programmer errors be redirected to unhandled rejection handler so that we notice them:\n\n```js\n//Read more about promisification in the API Reference:\n//API.md\nvar fs = Promise.promisifyAll(require(\"fs\"));\n\nfs.readFileAsync(\"myfile.json\").then(JSON.parse).then(function (json) {\n console.log(\"Successful json\")\n}).catch(SyntaxError, function (e) {\n console.error(\"file contains invalid json\");\n}).catch(Promise.OperationalError, function (e) {\n console.error(\"unable to read file, because: \", e.message);\n});\n```\n\nThe last `catch` handler is only invoked when the `fs` module explicitly used the `err` argument convention of async callbacks to inform of an expected error. The `OperationalError` instance will contain the original error in its `.cause` property but it does have a direct copy of the `.message` and `.stack` too. In this code any unexpected error - be it in our code or the `fs` module - would not be caught by these handlers and therefore not swallowed.\n\nSince a `catch` handler typed to `Promise.OperationalError` is expected to be used very often, it has a neat shorthand:\n\n```js\n.error(function (e) {\n console.error(\"unable to read file, because: \", e.message);\n});\n```\n\nSee [API documentation for `.error()`](API.md#error-rejectedhandler----promise)\n\nFinally, Bluebird also supports predicate-based filters. If you pass a\npredicate function instead of an error type, the predicate will receive\nthe error as an argument. The return result will be used to determine whether\nthe error handler should be called.\n\nPredicates should allow for very fine grained control over caught errors:\npattern matching, error typesets with set operations and many other techniques\ncan be implemented on top of them.\n\nExample of using a predicate-based filter:\n\n```js\nvar Promise = require(\"bluebird\");\nvar request = Promise.promisify(require(\"request\"));\n\nfunction clientError(e) {\n return e.code >= 400 && e.code < 500;\n}\n\nrequest(\"http://www.google.com\").then(function(contents){\n console.log(contents);\n}).catch(clientError, function(e){\n //A client error like 400 Bad Request happened\n});\n```\n\n**Danger:** The JavaScript language allows throwing primitive values like strings. Throwing primitives can lead to worse or no stack traces. Primitives [are not exceptions](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/). You should consider always throwing Error objects when handling exceptions.\n\n
\n\n#### How do long stack traces differ from e.g. Q?\n\nBluebird attempts to have more elaborate traces. Consider:\n\n```js\nError.stackTraceLimit = 25;\nQ.longStackSupport = true;\nQ().then(function outer() {\n return Q().then(function inner() {\n return Q().then(function evenMoreInner() {\n a.b.c.d();\n }).catch(function catcher(e){\n console.error(e.stack);\n });\n })\n});\n```\n\nYou will see\n\n ReferenceError: a is not defined\n at evenMoreInner (:7:13)\n From previous event:\n at inner (:6:20)\n\nCompare to:\n\n```js\nError.stackTraceLimit = 25;\nPromise.longStackTraces();\nPromise.resolve().then(function outer() {\n return Promise.resolve().then(function inner() {\n return Promise.resolve().then(function evenMoreInner() {\n a.b.c.d()\n }).catch(function catcher(e){\n console.error(e.stack);\n });\n });\n});\n```\n\n ReferenceError: a is not defined\n at evenMoreInner (:7:13)\n From previous event:\n at inner (:6:36)\n From previous event:\n at outer (:5:32)\n From previous event:\n at :4:21\n at Object.InjectedScript._evaluateOn (:572:39)\n at Object.InjectedScript._evaluateAndWrap (:531:52)\n at Object.InjectedScript.evaluate (:450:21)\n\n\nA better and more practical example of the differences can be seen in gorgikosev's [debuggability competition](https://github.com/spion/async-compare#debuggability).\n\n
\n\n# Development\n\nFor development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies.\n\nInstall [node](http://nodejs.org/) and [npm](https://npmjs.org/)\n\n git clone git@github.com:petkaantonov/bluebird.git\n cd bluebird\n npm install\n\n## Testing\n\nTo run all tests, run\n\n node tools/test\n\nIf you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+:\n\n node-dev --harmony tools/test\n\nYou may specify an individual test file to run with the `--run` script flag:\n\n node tools/test --run=cancel.js\n\n\nThis enables output from the test and may give a better idea where the test is failing. The paramter to `--run` can be any file name located in `test/mocha` folder.\n\n#### Testing in browsers\n\nTo run the test in a browser instead of node, pass the flag `--browser` to the test tool\n\n node tools/test --run=cancel.js --browser\n\nThis will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled.\n\nKeep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active.\n\n#### Supported options by the test tool\n\nThe value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`.\n\n - `--run=String`. Which tests to run (or compile when testing in browser). Default `\"all\"`. Can also be a glob string (relative to ./test/mocha folder)\n - `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `\"html\"` (use `--cover` to use default reporter).\n - `--browser` - Whether to compile tests for browsers. Default `false`.\n - `--port=Number` - Whe port where local server is hosted when testing in browser. Default `9999`\n - `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`.\n - `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`.\n - `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`.\n - `--js-hint` - Whether to run JSHint on source files. Default `true`.\n - `--saucelabs` Wheter to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser.Default `false`.\n\n## Benchmarks\n\nTo run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too).\n\nNode 0.11.2+ is required to run the generator examples.\n\n### 1\\. DoxBee sequential\n\nCurrently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections.\n\nCommand: `bench doxbee`\n\n### 2\\. Made-up parallel\n\nThis made-up scenario runs 15 shimmed queries in parallel.\n\nCommand: `bench parallel`\n\n## Custom builds\n\nCustom builds for browsers are supported through a command-line utility.\n\n\n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n \n
The following features can be disabled
Feature(s)Command line identifier
.any and Promise.anyany
.race and Promise.racerace
.call and .getcall_get
.filter and Promise.filterfilter
.map and Promise.mapmap
.reduce and Promise.reducereduce
.props and Promise.propsprops
.settle and Promise.settlesettle
.some and Promise.somesome
.nodeifynodeify
Promise.coroutine and Promise.spawngenerators
Progressionprogress
Promisificationpromisify
Cancellationcancel
Timerstimers
Resource managementusing
\n\n\nMake sure you have cloned the repo somewhere and did `npm install` successfully.\n\nAfter that you can run:\n\n node tools/build --features=\"core\"\n\n\nThe above builds the most minimal build you can get. You can add more features separated by spaces from the above list:\n\n node tools/build --features=\"core filter map reduce\"\n\nThe custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features.\n\nNote that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build\na full version afterwards (after having taken a copy of the bluebird.js somewhere):\n\n node tools/build --debug --main --zalgo --browser --minify\n\n#### Supported options by the build tool\n\nThe value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`.\n\n - `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`.\n - `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`.\n - `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`.\n - `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`.\n - `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`.\n - `--features=String` - See [custom builds](#custom-builds)\n\n
\n\n## For library authors\n\nBuilding a library that depends on bluebird? You should know about a few features.\n\nIf your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require(\"bluebird\")`. Instead you should create a file\nthat creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains:\n\n```js\n //NOTE the function call right after\nmodule.exports = require(\"bluebird/js/main/promise\")();\n```\n\nYour library can then use `var Promise = require(\"bluebird-extended\");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic.\n\nYou should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API.\n\n
\n\n## What is the sync build?\n\nYou may now use sync build by:\n\n var Promise = require(\"bluebird/zalgo\");\n\nThe sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards.\n\nThe normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility\nof stack overflow errors and non-deterministic behavior.\n\nThe sync build skips the async call trampoline completely, e.g code like:\n\n async.invoke( this.fn, this, val );\n\nAppears as this in the sync build:\n\n this.fn(val);\n\nThis should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism.\n\nNote that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads.\n\n\n```js\nvar cache = new Map(); //ES6 Map or DataStructures/Map or whatever...\nfunction getResult(url) {\n var resolver = Promise.pending();\n if (cache.has(url)) {\n resolver.resolve(cache.get(url));\n }\n else {\n http.get(url, function(err, content) {\n if (err) resolver.reject(err);\n else {\n cache.set(url, content);\n resolver.resolve(content);\n }\n });\n }\n return resolver.promise;\n}\n\n\n\n//The result of console.log is truly random without async guarantees\nfunction guessWhatItPrints( url ) {\n var i = 3;\n getResult(url).then(function(){\n i = 4;\n });\n console.log(i);\n}\n```\n\n# Optimization guide\n\nArticles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome.\n\nA single cohesive guide compiled from the articles will probably be done eventually.\n\n# License\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 Petka Antonov\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n", - "_id": "bluebird@2.9.24", + "directories": {}, "dist": { - "shasum": "ab3f30a7a40c383d14779a63b53aad667cc98ffb" + "shasum": "f2488f325782f66d174842f481992e2faba56f38", + "tarball": "http://registry.npmjs.org/bluebird/-/bluebird-3.0.6.tgz" }, - "_from": "bluebird@", - "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.9.24.tgz" + "files": [ + "LICENSE", + "js/browser", + "js/release" + ], + "gitHead": "37393eae4b6c8a48d16b357768e624ce2b347cac", + "homepage": "https://github.com/petkaantonov/bluebird", + "keywords": [ + "async", + "await", + "deferred", + "deferreds", + "dsl", + "flow control", + "fluent interface", + "future", + "performance", + "promise", + "promises", + "promises-a", + "promises-aplus" + ], + "license": "MIT", + "main": "./js/release/bluebird.js", + "maintainers": [ + { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + } + ], + "name": "bluebird", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "scripts": { + "generate-browser-core": "node tools/build.js --features=core --no-debug --release --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js", + "istanbul": "istanbul", + "lint": "node scripts/jshint.js", + "prepublish": "node tools/build.js --no-debug --release --browser --minify", + "test": "node tools/test.js" + }, + "version": "3.0.6" } diff --git a/node_modules/colors/.travis.yml b/node_modules/colors/.travis.yml new file mode 100644 index 0000000..ec43125 --- /dev/null +++ b/node_modules/colors/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.8" + - "0.6" \ No newline at end of file diff --git a/node_modules/colors/MIT-LICENSE.txt b/node_modules/colors/MIT-LICENSE.txt new file mode 100644 index 0000000..3de4e33 --- /dev/null +++ b/node_modules/colors/MIT-LICENSE.txt @@ -0,0 +1,23 @@ +Original Library + - Copyright (c) Marak Squires + +Additional Functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS 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. \ No newline at end of file diff --git a/node_modules/colors/ReadMe.md b/node_modules/colors/ReadMe.md new file mode 100644 index 0000000..beb5b14 --- /dev/null +++ b/node_modules/colors/ReadMe.md @@ -0,0 +1,167 @@ +# colors.js + +## get color and style in your node.js console + + + +## Installation + + npm install colors + +## colors and styles! + +### text colors + + - black + - red + - green + - yellow + - blue + - magenta + - cyan + - white + - gray + - grey + +### background colors + + + + - bgBlack + - bgRed + - bgGreen + - bgYellow + - bgBlue + - bgMagenta + - bgCyan + - bgWhite + +### styles + + - reset + - bold + - dim + - italic + - underline + - inverse + - hidden + - strikethrough + +### extras + + - rainbow + - zebra + - america + - trap + - random + + +## Usage + +By popular demand, `colors` now ships with two types of usages! + +The super nifty way + +```js +var colors = require('colors'); + +console.log('hello'.green); // outputs green text +console.log('i like cake and pies'.underline.red) // outputs red underlined text +console.log('inverse the color'.inverse); // inverses the color +console.log('OMG Rainbows!'.rainbow); // rainbow +console.log('Run the trap'.trap); // Drops the bass + +``` + +or a slightly less nifty way which doesn't extend `String.prototype` + +```js +var colors = require('colors/safe'); + +console.log(colors.green('hello')); // outputs green text +console.log(colors.red.underline('i like cake and pies')) // outputs red underlined text +console.log(colors.inverse('inverse the color')); // inverses the color +console.log(colors.rainbow('OMG Rainbows!')); // rainbow +console.log(colors.trap('Run the trap')); // Drops the bass + +``` + +I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way. + +If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object. + +## Disabling Colors + +To disable colors you can pass the following arguments in the command line to your application: + +```bash +node myapp.js --no-color +``` + +## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data) + +```js +var name = 'Marak'; +console.log(colors.green('Hello %s'), name); +// outputs -> 'Hello Marak' +``` + +## Custom themes + +### Using standard API + +```js + +var colors = require('colors'); + +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); +``` + +### Using string safe API + +```js +var colors = require('colors/safe'); + +// set single property +var error = colors.red; +error('this is red'); + +// set theme +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); +``` + +*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.* \ No newline at end of file diff --git a/node_modules/colors/examples/normal-usage.js b/node_modules/colors/examples/normal-usage.js new file mode 100644 index 0000000..2818741 --- /dev/null +++ b/node_modules/colors/examples/normal-usage.js @@ -0,0 +1,74 @@ +var colors = require('../lib/index'); + +console.log("First some yellow text".yellow); + +console.log("Underline that text".yellow.underline); + +console.log("Make it bold and red".red.bold); + +console.log(("Double Raindows All Day Long").rainbow) + +console.log("Drop the bass".trap) + +console.log("DROP THE RAINBOW BASS".trap.rainbow) + + +console.log('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported + +console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse + ' styles! '.yellow.bold); // styles not widely supported +console.log("Zebras are so fun!".zebra); + +// +// Remark: .strikethrough may not work with Mac OS Terminal App +// +console.log("This is " + "not".strikethrough + " fun."); + +console.log('Background color attack!'.black.bgWhite) +console.log('Use random styles on everything!'.random) +console.log('America, Heck Yeah!'.america) + + +console.log('Setting themes is useful') + +// +// Custom themes +// +console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); + +// outputs grey text +console.log("this is an input".input); + +console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +colors.setTheme(__dirname + '/../themes/generic-logging.js'); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); + +// outputs grey text +console.log("this is an input".input); + +//console.log("Don't summon".zalgo) \ No newline at end of file diff --git a/node_modules/colors/examples/safe-string.js b/node_modules/colors/examples/safe-string.js new file mode 100644 index 0000000..111b363 --- /dev/null +++ b/node_modules/colors/examples/safe-string.js @@ -0,0 +1,76 @@ +var colors = require('../safe'); + +console.log(colors.yellow("First some yellow text")); + +console.log(colors.yellow.underline("Underline that text")); + +console.log(colors.red.bold("Make it bold and red")); + +console.log(colors.rainbow("Double Raindows All Day Long")) + +console.log(colors.trap("Drop the bass")) + +console.log(colors.rainbow(colors.trap("DROP THE RAINBOW BASS"))); + +console.log(colors.bold.italic.underline.red('Chains are also cool.')); // styles not widely supported + + +console.log(colors.green('So ') + colors.underline('are') + ' ' + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); // styles not widely supported + +console.log(colors.zebra("Zebras are so fun!")); + +console.log("This is " + colors.strikethrough("not") + " fun."); + + +console.log(colors.black.bgWhite('Background color attack!')); +console.log(colors.random('Use random styles on everything!')) +console.log(colors.america('America, Heck Yeah!')); + +console.log('Setting themes is useful') + +// +// Custom themes +// +//console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +// outputs grey text +console.log(colors.input("this is an input")); + + +// console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +colors.setTheme(__dirname + '/../themes/generic-logging.js'); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +// outputs grey text +console.log(colors.input("this is an input")); + +// console.log(colors.zalgo("Don't summon him")) + + + diff --git a/node_modules/colors/lib/colors.js b/node_modules/colors/lib/colors.js new file mode 100644 index 0000000..59898de --- /dev/null +++ b/node_modules/colors/lib/colors.js @@ -0,0 +1,176 @@ +/* + +The MIT License (MIT) + +Original Library + - Copyright (c) Marak Squires + +Additional functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS 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 colors = {}; +module['exports'] = colors; + +colors.themes = {}; + +var ansiStyles = colors.styles = require('./styles'); +var defineProps = Object.defineProperties; + +colors.supportsColor = require('./system/supports-colors'); + +if (typeof colors.enabled === "undefined") { + colors.enabled = colors.supportsColor; +} + +colors.stripColors = colors.strip = function(str){ + return ("" + str).replace(/\x1B\[\d+m/g, ''); +}; + + +var stylize = colors.stylize = function stylize (str, style) { + return ansiStyles[style].open + str + ansiStyles[style].close; +} + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +var escapeStringRegexp = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +} + +function build(_styles) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + builder.__proto__ = proto; + return builder; +} + +var styles = (function () { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function (key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + ret[key] = { + get: function () { + return build(this._styles.concat(key)); + } + }; + }); + return ret; +})(); + +var proto = defineProps(function colors() {}, styles); + +function applyStyle() { + var args = arguments; + var argsLen = args.length; + var str = argsLen !== 0 && String(arguments[0]); + if (argsLen > 1) { + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!colors.enabled || !str) { + return str; + } + + var nestedStyles = this._styles; + + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + } + + return str; +} + +function applyTheme (theme) { + for (var style in theme) { + (function(style){ + colors[style] = function(str){ + return colors[theme[style]](str); + }; + })(style) + } +} + +colors.setTheme = function (theme) { + if (typeof theme === 'string') { + try { + colors.themes[theme] = require(theme); + applyTheme(colors.themes[theme]); + return colors.themes[theme]; + } catch (err) { + console.log(err); + return err; + } + } else { + applyTheme(theme); + } +}; + +function init() { + var ret = {}; + Object.keys(styles).forEach(function (name) { + ret[name] = { + get: function () { + return build([name]); + } + }; + }); + return ret; +} + +var sequencer = function sequencer (map, str) { + var exploded = str.split(""), i = 0; + exploded = exploded.map(map); + return exploded.join(""); +}; + +// custom formatter methods +colors.trap = require('./custom/trap'); +colors.zalgo = require('./custom/zalgo'); + +// maps +colors.maps = {}; +colors.maps.america = require('./maps/america'); +colors.maps.zebra = require('./maps/zebra'); +colors.maps.rainbow = require('./maps/rainbow'); +colors.maps.random = require('./maps/random') + +for (var map in colors.maps) { + (function(map){ + colors[map] = function (str) { + return sequencer(colors.maps[map], str); + } + })(map) +} + +defineProps(colors, init()); \ No newline at end of file diff --git a/node_modules/colors/lib/custom/trap.js b/node_modules/colors/lib/custom/trap.js new file mode 100644 index 0000000..3f09143 --- /dev/null +++ b/node_modules/colors/lib/custom/trap.js @@ -0,0 +1,45 @@ +module['exports'] = function runTheTrap (text, options) { + var result = ""; + text = text || "Run the trap, drop the bass"; + text = text.split(''); + var trap = { + a: ["\u0040", "\u0104", "\u023a", "\u0245", "\u0394", "\u039b", "\u0414"], + b: ["\u00df", "\u0181", "\u0243", "\u026e", "\u03b2", "\u0e3f"], + c: ["\u00a9", "\u023b", "\u03fe"], + d: ["\u00d0", "\u018a", "\u0500" , "\u0501" ,"\u0502", "\u0503"], + e: ["\u00cb", "\u0115", "\u018e", "\u0258", "\u03a3", "\u03be", "\u04bc", "\u0a6c"], + f: ["\u04fa"], + g: ["\u0262"], + h: ["\u0126", "\u0195", "\u04a2", "\u04ba", "\u04c7", "\u050a"], + i: ["\u0f0f"], + j: ["\u0134"], + k: ["\u0138", "\u04a0", "\u04c3", "\u051e"], + l: ["\u0139"], + m: ["\u028d", "\u04cd", "\u04ce", "\u0520", "\u0521", "\u0d69"], + n: ["\u00d1", "\u014b", "\u019d", "\u0376", "\u03a0", "\u048a"], + o: ["\u00d8", "\u00f5", "\u00f8", "\u01fe", "\u0298", "\u047a", "\u05dd", "\u06dd", "\u0e4f"], + p: ["\u01f7", "\u048e"], + q: ["\u09cd"], + r: ["\u00ae", "\u01a6", "\u0210", "\u024c", "\u0280", "\u042f"], + s: ["\u00a7", "\u03de", "\u03df", "\u03e8"], + t: ["\u0141", "\u0166", "\u0373"], + u: ["\u01b1", "\u054d"], + v: ["\u05d8"], + w: ["\u0428", "\u0460", "\u047c", "\u0d70"], + x: ["\u04b2", "\u04fe", "\u04fc", "\u04fd"], + y: ["\u00a5", "\u04b0", "\u04cb"], + z: ["\u01b5", "\u0240"] + } + text.forEach(function(c){ + c = c.toLowerCase(); + var chars = trap[c] || [" "]; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== "undefined") { + result += trap[c][rand]; + } else { + result += c; + } + }); + return result; + +} diff --git a/node_modules/colors/lib/custom/zalgo.js b/node_modules/colors/lib/custom/zalgo.js new file mode 100644 index 0000000..4dc20c8 --- /dev/null +++ b/node_modules/colors/lib/custom/zalgo.js @@ -0,0 +1,104 @@ +// please no +module['exports'] = function zalgo(text, options) { + text = text || " he is here "; + var soul = { + "up" : [ + '̍', '̎', '̄', '̅', + '̿', '̑', '̆', '̐', + '͒', '͗', '͑', '̇', + '̈', '̊', '͂', '̓', + '̈', '͊', '͋', '͌', + '̃', '̂', '̌', '͐', + '̀', '́', '̋', '̏', + '̒', '̓', '̔', '̽', + '̉', 'ͣ', 'ͤ', 'ͥ', + 'ͦ', 'ͧ', 'ͨ', 'ͩ', + 'ͪ', 'ͫ', 'ͬ', 'ͭ', + 'ͮ', 'ͯ', '̾', '͛', + '͆', '̚' + ], + "down" : [ + '̖', '̗', '̘', '̙', + '̜', '̝', '̞', '̟', + '̠', '̤', '̥', '̦', + '̩', '̪', '̫', '̬', + '̭', '̮', '̯', '̰', + '̱', '̲', '̳', '̹', + '̺', '̻', '̼', 'ͅ', + '͇', '͈', '͉', '͍', + '͎', '͓', '͔', '͕', + '͖', '͙', '͚', '̣' + ], + "mid" : [ + '̕', '̛', '̀', '́', + '͘', '̡', '̢', '̧', + '̨', '̴', '̵', '̶', + '͜', '͝', '͞', + '͟', '͠', '͢', '̸', + '̷', '͡', ' ҉' + ] + }, + all = [].concat(soul.up, soul.down, soul.mid), + zalgo = {}; + + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } + + function is_char(character) { + var bool = false; + all.filter(function (i) { + bool = (i === character); + }); + return bool; + } + + + function heComes(text, options) { + var result = '', counts, l; + options = options || {}; + options["up"] = options["up"] || true; + options["mid"] = options["mid"] || true; + options["down"] = options["down"] || true; + options["size"] = options["size"] || "maxi"; + text = text.split(''); + for (l in text) { + if (is_char(l)) { + continue; + } + result = result + text[l]; + counts = {"up" : 0, "down" : 0, "mid" : 0}; + switch (options.size) { + case 'mini': + counts.up = randomNumber(8); + counts.min = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.min = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + + var arr = ["up", "mid", "down"]; + for (var d in arr) { + var index = arr[d]; + for (var i = 0 ; i <= counts[index]; i++) { + if (options[index]) { + result = result + soul[index][randomNumber(soul[index].length)]; + } + } + } + } + return result; + } + // don't summon him + return heComes(text); +} diff --git a/node_modules/colors/lib/extendStringPrototype.js b/node_modules/colors/lib/extendStringPrototype.js new file mode 100644 index 0000000..b6b5b03 --- /dev/null +++ b/node_modules/colors/lib/extendStringPrototype.js @@ -0,0 +1,118 @@ +var colors = require('./colors'), + styles = require('./styles'); + +module['exports'] = function () { + + // + // Extends prototype of native string object to allow for "foo".red syntax + // + var addProperty = function (color, func) { + String.prototype.__defineGetter__(color, func); + }; + + var sequencer = function sequencer (map, str) { + return function () { + var exploded = this.split(""), i = 0; + exploded = exploded.map(map); + return exploded.join(""); + } + }; + + var stylize = function stylize (str, style) { + return styles[style].open + str + styles[style].close; + } + + addProperty('strip', function () { + return colors.strip(this); + }); + + addProperty('stripColors', function () { + return colors.strip(this); + }); + + addProperty("trap", function(){ + return colors.trap(this); + }); + + addProperty("zalgo", function(){ + return colors.zalgo(this); + }); + + addProperty("zebra", function(){ + return colors.zebra(this); + }); + + addProperty("rainbow", function(){ + return colors.rainbow(this); + }); + + addProperty("random", function(){ + return colors.random(this); + }); + + addProperty("america", function(){ + return colors.america(this); + }); + + // + // Iterate through all default styles and colors + // + var x = Object.keys(colors.styles); + x.forEach(function (style) { + addProperty(style, function () { + return stylize(this, style); + }); + }); + + function applyTheme(theme) { + // + // Remark: This is a list of methods that exist + // on String that you should not overwrite. + // + var stringPrototypeBlacklist = [ + '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'charAt', 'constructor', + 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'charCodeAt', + 'indexOf', 'lastIndexof', 'length', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substring', + 'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight' + ]; + + Object.keys(theme).forEach(function (prop) { + if (stringPrototypeBlacklist.indexOf(prop) !== -1) { + console.log('warn: '.red + ('String.prototype' + prop).magenta + ' is probably something you don\'t want to override. Ignoring style name'); + } + else { + if (typeof(theme[prop]) === 'string') { + colors[prop] = colors[theme[prop]]; + addProperty(prop, function () { + return colors[theme[prop]](this); + }); + } + else { + addProperty(prop, function () { + var ret = this; + for (var t = 0; t < theme[prop].length; t++) { + ret = exports[theme[prop][t]](ret); + } + return ret; + }); + } + } + }); + } + + colors.setTheme = function (theme) { + if (typeof theme === 'string') { + try { + colors.themes[theme] = require(theme); + applyTheme(colors.themes[theme]); + return colors.themes[theme]; + } catch (err) { + console.log(err); + return err; + } + } else { + applyTheme(theme); + } + }; + +}; \ No newline at end of file diff --git a/node_modules/colors/lib/index.js b/node_modules/colors/lib/index.js new file mode 100644 index 0000000..96d2b84 --- /dev/null +++ b/node_modules/colors/lib/index.js @@ -0,0 +1,12 @@ +var colors = require('./colors'); +module['exports'] = colors; + +// Remark: By default, colors will add style properties to String.prototype +// +// If you don't wish to extend String.prototype you can do this instead and native String will not be touched +// +// var colors = require('colors/safe); +// colors.red("foo") +// +// +var extendStringPrototype = require('./extendStringPrototype')(); \ No newline at end of file diff --git a/node_modules/colors/lib/maps/america.js b/node_modules/colors/lib/maps/america.js new file mode 100644 index 0000000..a07d832 --- /dev/null +++ b/node_modules/colors/lib/maps/america.js @@ -0,0 +1,12 @@ +var colors = require('../colors'); + +module['exports'] = (function() { + return function (letter, i, exploded) { + if(letter === " ") return letter; + switch(i%3) { + case 0: return colors.red(letter); + case 1: return colors.white(letter) + case 2: return colors.blue(letter) + } + } +})(); \ No newline at end of file diff --git a/node_modules/colors/lib/maps/rainbow.js b/node_modules/colors/lib/maps/rainbow.js new file mode 100644 index 0000000..a7ce24e --- /dev/null +++ b/node_modules/colors/lib/maps/rainbow.js @@ -0,0 +1,13 @@ +var colors = require('../colors'); + +module['exports'] = (function () { + var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV + return function (letter, i, exploded) { + if (letter === " ") { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); + } + }; +})(); + diff --git a/node_modules/colors/lib/maps/random.js b/node_modules/colors/lib/maps/random.js new file mode 100644 index 0000000..5cd101f --- /dev/null +++ b/node_modules/colors/lib/maps/random.js @@ -0,0 +1,8 @@ +var colors = require('../colors'); + +module['exports'] = (function () { + var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta']; + return function(letter, i, exploded) { + return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 1))]](letter); + }; +})(); \ No newline at end of file diff --git a/node_modules/colors/lib/maps/zebra.js b/node_modules/colors/lib/maps/zebra.js new file mode 100644 index 0000000..bf7dcde --- /dev/null +++ b/node_modules/colors/lib/maps/zebra.js @@ -0,0 +1,5 @@ +var colors = require('../colors'); + +module['exports'] = function (letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); +}; \ No newline at end of file diff --git a/node_modules/colors/lib/styles.js b/node_modules/colors/lib/styles.js new file mode 100644 index 0000000..067d590 --- /dev/null +++ b/node_modules/colors/lib/styles.js @@ -0,0 +1,77 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS 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 styles = {}; +module['exports'] = styles; + +var codes = { + reset: [0, 0], + + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49] + +}; + +Object.keys(codes).forEach(function (key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = '\u001b[' + val[0] + 'm'; + style.close = '\u001b[' + val[1] + 'm'; +}); \ No newline at end of file diff --git a/node_modules/colors/lib/system/supports-colors.js b/node_modules/colors/lib/system/supports-colors.js new file mode 100644 index 0000000..3e008aa --- /dev/null +++ b/node_modules/colors/lib/system/supports-colors.js @@ -0,0 +1,61 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS 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 argv = process.argv; + +module.exports = (function () { + if (argv.indexOf('--no-color') !== -1 || + argv.indexOf('--color=false') !== -1) { + return false; + } + + if (argv.indexOf('--color') !== -1 || + argv.indexOf('--color=true') !== -1 || + argv.indexOf('--color=always') !== -1) { + return true; + } + + if (process.stdout && !process.stdout.isTTY) { + return false; + } + + if (process.platform === 'win32') { + return true; + } + + if ('COLORTERM' in process.env) { + return true; + } + + if (process.env.TERM === 'dumb') { + return false; + } + + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { + return true; + } + + return false; +})(); \ No newline at end of file diff --git a/node_modules/colors/package.json b/node_modules/colors/package.json new file mode 100644 index 0000000..f626e56 --- /dev/null +++ b/node_modules/colors/package.json @@ -0,0 +1,79 @@ +{ + "_args": [ + [ + "colors@1.0.x", + "/Users/akira/src/biomedjs/node_modules/winston" + ] + ], + "_from": "colors@>=1.0.0 <1.1.0", + "_id": "colors@1.0.3", + "_inCache": true, + "_installable": true, + "_location": "/colors", + "_nodeVersion": "0.11.13", + "_npmUser": { + "email": "marak.squires@gmail.com", + "name": "marak" + }, + "_npmVersion": "2.0.2", + "_phantomChildren": {}, + "_requested": { + "name": "colors", + "raw": "colors@1.0.x", + "rawSpec": "1.0.x", + "scope": null, + "spec": ">=1.0.0 <1.1.0", + "type": "range" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "_shasum": "0433f44d809680fdeb60ed260f1b0c262e82a40b", + "_shrinkwrap": null, + "_spec": "colors@1.0.x", + "_where": "/Users/akira/src/biomedjs/node_modules/winston", + "author": { + "name": "Marak Squires" + }, + "bugs": { + "url": "https://github.com/Marak/colors.js/issues" + }, + "dependencies": {}, + "description": "get colors in your node.js console", + "devDependencies": {}, + "directories": {}, + "dist": { + "shasum": "0433f44d809680fdeb60ed260f1b0c262e82a40b", + "tarball": "http://registry.npmjs.org/colors/-/colors-1.0.3.tgz" + }, + "engines": { + "node": ">=0.1.90" + }, + "gitHead": "e9e6557cc0fa26dba1a20b0d45e92de982f4047c", + "homepage": "https://github.com/Marak/colors.js", + "keywords": [ + "ansi", + "colors", + "terminal" + ], + "license": "MIT", + "main": "./lib/index", + "maintainers": [ + { + "name": "marak", + "email": "marak.squires@gmail.com" + } + ], + "name": "colors", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Marak/colors.js.git" + }, + "scripts": { + "test": "node tests/basic-test.js && node tests/safe-test.js" + }, + "version": "1.0.3" +} diff --git a/node_modules/colors/safe.js b/node_modules/colors/safe.js new file mode 100644 index 0000000..a6a1f3a --- /dev/null +++ b/node_modules/colors/safe.js @@ -0,0 +1,9 @@ +// +// Remark: Requiring this file will use the "safe" colors API which will not touch String.prototype +// +// var colors = require('colors/safe); +// colors.red("foo") +// +// +var colors = require('./lib/colors'); +module['exports'] = colors; \ No newline at end of file diff --git a/node_modules/colors/screenshots/colors.png b/node_modules/colors/screenshots/colors.png new file mode 100644 index 0000000000000000000000000000000000000000..7200a623590c35e8b4a8e74a8df49a42998ca9c5 GIT binary patch literal 79787 zcmZ^~V{~RgurB<@wrx#p+nFS9oJ?%nwylXKnAo;$+qP|ebMT#e*1GHNU)@#pRPCx> ztM}^aXGbW=OCrGH!U6yQ1ZgQTB>(`F0{{Rih6ep7p@odZ0RXV6EJQ^Wq(w!E6&&qM zEv!ud01cQ*4>!J)?eFi_D~s#S=PfV0x@T*L_4^^4WJQ?}Y8aec5fqtzXle7m#uVf* zh2b(JIJf+6`=4LlgxlNC-P@1u8_SO!y2l>6$1b|Z+Q%JJ=aBy8*~lm;k%j=`Xlyyh z4HNR6t6D99APkc~7%>3C99lpTCG_cOY3IA6D^7^ABYQm2ice5@O$K1VQy>6b575#J|Ra2{p#(02es-8l?%)x6@hW+*8TF^>Ju^g+wH64eIt*Cv1bgCV?ARB-QR9Ga zz3{pqc7=Qg=Xkqfiwuxr%!0X9D zl>p0sZLYApo!Zm;7+wNss6WNo<_j(ji^K?i-|+<{O8edB@N9iAyliu%2e{3Ef%xIT zvculPYWbaiuN!63Oo5xlvi3{o&Cj@;FgQcCL2X8Mfq~CF&&r+XKJc@A87*(CK`V$n z!LIfz_P~11A`N_al6~1+cXy!QBkjjQ^3d?8?m%0i2t(7sy%j?&>#0F~GSV~0?;>cy zhiaGm4eiJ2U^AcSs79kmV7=kIVfTmbg4SVUoH&R^3*dvPQh&Okf46hi^?au`8~Hs_ zfOmv_LPtIEVj~=*G9ku=lR-d$OTc0GEzSWYdIC?#sL1{n{4D_;v0_XI>#5tXX2&o% z|5nHJ#RF7&axL3@|9;&8F-L~H)h5bK*h{7LG#l7qdq%@Q06wm;<@k=myX*!D05Gz94d-fcKI$K(qEm+>qskv*iVw6MKf!7{+js5{6@;`XeV` zlcR8l8WXRMcod+QirA7&N!(#-4diR64Km~4Nnu9K59t_FaL6;efG;7^^J*# zAS;YPbU9CJN839#TZA!hnVAcoRRTZ;Cpm||A9&j|$^_M7dJjnN{-!op(E9Kqae zUSi&KPHk4;Z&tyl@USeEq?z#X&r~sWv1KVvvFG&cMBU`Acwa#uJ|99K0w2LoQZR}j z>>y^afL$h06j9cG>i!>Otofw*1V-5VG((m{ghSkvd`Z|zG)au}4n>YdP_lOEvlD$2 zLlXiM!)c7Hf`-{9y|v->8a3ec#x>ezr$)aFO$=2HTuk^!GzUE6Tp|%BDThpZF~?j( zFFDqs*CBZs+ezAq-ld;3pGcnA5p5B{5CvnMWAX4Axj48Wxa7D+xuzYrcD*MQ!P;aP+=&EE@dfSD=8{-E&EbYRwpZ6ESoHkD)B1CDvz_Q zF<-IDoI6<>u*9{Xv}m%dvMRL@x7u8K%cCzR$kVChFD9$nFLwHMTv-**Al$6tCIb|j z{&}6amE84LK)74hZ%AmRXZdg6PEc-vLCr3E|Fi_G1bIGWKD!b9zUa^;rFoJLIiB_&;2vz3L)WgGI<;Od zai`f%UZ&4wS8}VobwKa!ULXGV)~B$m?qlg|>6?oCKF?MURWBQq3uu#IRXezA!)pp6 zqa5!X2tBZE?QIW1oo?%Hq_4KG)h{QIHV|%*`+&CqkANuQA>reoF33Mndhoh%wQ!~I zt1vEbohTA0M;J@8#-yRhM4|T~MDRq>@v%}7X^{(&d|0hwb)>3dB#Q5O8F|0-23WS@^JkG7`)e-kAMs_N^^s8B1VskXQX+ z+V#rD_)Mzau+cE59zlAKd_lLVdlu&?>#rw?yU7@u#!|0&%K1)KdDiN!w+D(pU(CNB#Ce;la~hm*4NK)m%9Qel+4{t~z>LnO&qBtc&E&~s8S0)Bvzl(WLZU*_ddOPxGW0Ts z7oHoD8-X{jwZqltxM`>BqP8>4k#S#O=o3C0UKbvm(hiddQIAlN#4iF6B2-EIXXhk7 zaVE@wsQ;8qg;YnXR*`#_)6mn<4AFY1c3_-5jlz>Kk~cHS`Ez7H-!9P)-;9ssw_);G zf&`BTPbX#m^Fp(1HtW)_u<0c;#-qrb`-$;UKb0C+-MW!{uF8X{kky~Eg>NP#hsBI~ zt#fM3ny;0SO`2sxADTUn3u|R~Ks(>oN!?<->+Sei4X@&Ai`tOAD*f^y{&kM!_t;Ag z0?aH*BzVFzzB%`b4T^30&HnZJN8^Ljn5|?pueXCY*SB}bDWo?f8h)th;V?YCgJ`kn zwHTTXWA9czfx9x3y}9$`(HhPv<+b@h)|d3bX0YosGq^1(-xbbc)@lCkF9+jX+uMoa z_-Ru;@a_vb8$UF?Ck^gqp4y@ZGBY1DR#PjF_ns+4d_Ow<5av88YEY-}AC9QM#9H%1 zXWsQcoI%e0jfOh=xAR*>eu@2-)RDdScMZ}FBZ;^rVa*WFVGpQG`9z?C!`k@mq2xjP z+V)}wE&$hsg^Srm+Bz$IMHU^t{vGC1KQn}Vc4w{;usj& z_#^dvK@tpk>3y&P6O&*Y`{UfQ8^X0@{7{q+yyYSpx8J$yUp#*0@mMBB*PX)skNS*u-u;KO7}Yr|~Z^4)eYdmDUg zfg%R3iSUVRhwzFcMvX* z)E?(TaLqIOd+zre*JbbM)B_ZbPH}b?;bx8}cV3XV!i-FX4x^rpsMd{rrRWl6V)NOJ=KnCdi!VZy$$n?Fn1V z@2S;PFI4BnL=%ZeP=bOwv%j_}$?xWss#~@n*^`tk+1eyy{J%MKiZi@`CE3$yhOAeh4%1BHT8az{W?x_y}2*%X^v{ftw4dPE(>3qFWLYl;jP|d(a`>raLipAlxMQ# z{Dpj^fen6t0dpdC-0qYU`x7d~bM0RZ+d9+ha7@$>hYoqs%P^*C2>vbL zOG#VFuM#|SbMqgTqn1BUrOsr|q|e9kN^s9`({Xq+E;td`f3EyC&^1;xTD5$f@SHm; zCm70}7ap4J8C~R_pcrgixXga1jhp1>^Ll)Ky#hX4-)i2a+}u9VKj9(iBRRv3ArT@S z!rfD?N-`D-rXP8SOi3 z9LX+a*OPI3IUe63Vk%(h{+MGR?6yBiG(S~%ouw_qfK%r!kE#-1UfV+Nj#=omG;c{- z#P?j@AuPI-_HsSW4%>@UYvb{9%zhJ`zbGbh7gXWC;P2z)`C|G0eQ#AX8c2x9hk1;V`U<6sS zv4VU-mdSSonvIhq-7BjI=|sj@x>x#I>SexXfnknyVtEpT{enG&eV?|G{+cdW$5x+h z0%yQ^jC?%cH0AKwXWxQo^tO}g)96#87O~wq4y2@8RDhpwwStzZ4 zU(8)>bCvO$@cKD6IY^pBcJ=nRosJdM?&3?P=(CEQAXv@C%YZ1sk#4*c}y1i&iU`y7d z?5gdd|6zaR;MgoRJzoqneeiw+`6DziOjXi8AC1wjTj`H^_JZd;UnP&zXV#AO(t8Z| z^=lObjr)?+hwO)8J$ci^?RktH;dsg6IBgkioVt!$SU0Z^k!HPi`?KhmMa z=%d6Z*U1lZ)!giin}WiWLz?AS^29Ax+oC; zX~>=9)vT<^x~#06!u;SAWBiFlEIqP(Ny$;a%a7+r!RL~7_q)wG?tk|O zSr#f9&Kh#EJVtgl32Pt@qd~)Tk(@>$SDwu+BupKvokO=u#gJC5)%{iIU1YtD2Yk@H~im>pVZvh*`9}y z(ap_`!Ht!{&e4pKnVXxNk%@(og@yi~1-+Apt+RnUy{!}3e>wU8{fL=3897?mJ6qV< z690!^14BC(XMR%B{|NLy&wstAiMz%BiDc{a-)a3zknuk>jLZy7jQ`{NAC&Juq&x~1 z?k3h6ViqKN9#~3H?{K z{!{v|TmrCsjQ>-50ayqF<4*uU2p}yctl|!G(FxFh&*|hR{_EO`lctmfULlP?W$iHoh75j}01A5i^Yp1mhxwrlwDB z#Irf=BA1)H_;z}x;2iC=0E3wRe3;KX1BTXfV9#Nt=>rDqdju>*id%4=@8a(>iz=sANKAFr7iJQc~{13?!-!YAgfu-m9oSyvpCncIhA(e@`pKvu?$S_3x<7WdvvqyBxPUdpj>gS=bFtLF z1Mq##UOKmzE9f_jg#`G(U7RN10>eL+0ReeQuHI{tjDL6B(ZeQ|#y%AB93kflCH|-S>8((l)`_It!bEM8SG3_^!YZ9Fj`%W{4N{UY?c- zv>Qu7Ej83f#`64~esQ-l4(T*e#^C`?n7A4dL4A`e7KgtT>Xwzi`|bK^Ol6>KuR5?` zk##mUIzSyl`hFfPp1Vl)v=`I4&)&F^L@)}M;-GuB|EYdkmjmfzki1@}7|7pk1XmbX z6bJbEg+Hg$8Oi@yd3n@q5>S@uD$=AbV>erj&i})uX6a&q5Vc}kfJ;Y*oHW9&IH<*) zGHqL1!{vs*J)kC?wUEZ+ z@D&JRx-2YicA|n5F?7Xx?LAV3gfb7DJV?$)E2b62ePnlw6nj@@9|Mm})lh$ElcNsv z7JI199by?tjXFai`-s-Mlxjxon9`n$X6HWF6J|mT%e&4GJ|WiHg^upf70HBV+hdwC z;byzidR>u{mgb#MtTP<5{Fg9w)7#d?dX=r;vKG%*PbakAeOR;LW}issc9X1 zLr&hzU*RivqNbQ}*O||^B&}3oUZGsgdnlGDbbdq?51QGZ)Eg2_!pN71O@+qjh8a2> zO%?9M2r({_;cC-1)?9UM;VKNx_N#AMOo2v~t1R}Mzag6cK;bfC8ZPEE#x4XU#HNZ% zt}Zp!-`^FXV}2W)>uS&gZTln?7n%qXLO{i^IFaBrZxK zw-oz1mb%lUR$CB$FE(wnqmkGv=uU?xBl}A~oh`G+T;HWF_Z^3xu`UVwmBH{#XeObV z0=O^qelCrF0hbE0gq=8>#H^t_rsa8-skblOGNj($oY zH$TvrPz$}aFL~TGuUmDYk( zhKZaae!tWmnftIX-3wL>DusXY^=xMQ{utL@Ig*q)aFShQ-#Xu4;HYPMV z-*f_m(a@oP9xXiB1?uaGdlJ+?5usfj=mT#w;d!*pANs(aSw%;un*pQl6ESRE#n z3=S*SzhPFi_FIXl)SOy$bPb!wa0*@FEk?s5q}#_BRoLrk{_$e&S$}4_aVki#q!pfQ-oPv-XPg*BgSrYD#rFEw1aJ ziVDQxu*uCgUn#>_#5ww|)U*n7-r+NaX!xx$FY(Uo>v*ia1mb-`xl{u>*>%yb-!gE zB$%PAOB~0XmKHa0M-d^V>)Kkv2 zH?CE}O5A|vu>4xLZK?S~^#fig-nJM*7T0mEN9$KTR${H?eo<U%MILCv}cWREG; z+HAZOeY!s^iWD$mMsd(X6q?q!!+E26mF~yLK{{Oq(s=HYSdI5yW`Lu><6h#k>6Mo? z9ZBI;5>`vT1SyxD*5Pg#lh^L$E*6Ejx@Se3lZZ3hCKusL*PHa0Rm^Aqe#oKerfy{rUTz!wHCp} zSL4rLec*7dZ>>unk@hnLbkkh6;oBlGEiJ8%?gBv=96N@x=!{uX)yb&nIlX%*2kV<2 zyMXIU`RM&sD&p3qhzU)AvC<5*|K~JCM6>Ip-xq!5=2t|AqJod~wELF=AfL%I@gK#6 z<7^U5W~vavUw}sSc6aRewYn8Q9brn30zFsk?)}~y*kOnDr^uXuu&>2)l{NxLsy#Q5 z#v`l=SZVg`*J1M6q@6<`Yw5%G#WG9P465-fvKct$ySa- z`WvO88NuA(PcB-Ul!zrP5J$o8d_aZ|g_<4N^{5Z*B(7IyyWj0{qvhSoWZd`E(Tq3y z^`n4n>3L8wQ<`sf$Cxd&1}FNET4q53edX?nkqKtP_MUX8ckU;@;JMYM>juMgFs78* zGVoXJMPTC6P?Hmd+epQ?*lMBeV^1i{Ueo3W=C-a@t(pY5=_f-O?Wuq7tXGzUr5&U9 zfC8A!p((`zz(E}akc$z$TYTDQ^iD4syG7QEwZbN`EbCt;-u49TE3%~o497OK8S*{m zSt9&nmoWQ;pHCr=HwJR)vjryJJBDf^+?>MSr^&MK=PHYRBN+QYX6jy>@y_fCL>}tD zM|o&M!cfq1hZwgHp5X6fDC7IX1+0h?9iX0P&gWU-pl|3xX+;J*KdnU>Nq%diKI8?u zv#r37AzABje;)-OKP3g6*?$=u%`UxKKjJyvBu*%-)eo_dEgkb zKX3(v_WAbNf!__!X$$Y9@?F2aI*daD(Rke=+4~H~Z?|8@J&Q(3Abihx4y)8s|GEAo zOPMm!>Ml7-R`6Nre!Z$!?PWS@6$Y(qQNMg;c&I78B~8S=8(>nv^l|)o`E!5utE-iY z{|UC7v&Qfgp1-&H>BT^J=yFr+n#b|&jy)S(X*R9SdeU<50q;-hvkmR}GCE4o^c0$( zo>OENrG0aOCRPi!AI-bcMi<;*jf40D}98IP%AEt`j+9=Jp4F<`jeQcuqACV_>}}R^2syNpGUMO z)6TzW5AH3JxOul{iCuXoM%V7z#5UxFiz_6dwjz^n;J68op{qR)n(%eQC6W&|GAGc` z3338K)b@Ebh*up8Ym(uIujl1@J7TsaiF}PMy{Y?82kBi|f={P*UU{3skcwjYnzdh0 zylMN&w&S}56mU^dm<+Vs3ZeuaLx>!6IOM`tT;f{^!iGNyY|=kDeDhX=vbkuN92~Ca z#Y5^-J16lIT$k;kY#WOF4MPZW+MGYmd&HJm>7gyPt7XI4s5sZfB<`4jr;L5unWT;NmI z#@Q{|Mzh^{HS)Q;Xo}d;l3+;O8%Ab=*hvh@_vP|ntMYtnOL3~TBC6^m4L8w}AO+CV z&bML%!DmB%^!TiNwKq%bEc6Wp3cA3pJboLZ?Naii&&D>AQ*jd6BQ%-MF{&GHJ;ecX zzw4^9H-nquxC2A-6poU~_M`hwNDdu&9OueB4?a4?MGg`Y&IcrTT}fHy5oRg#Q6aIM zBTE?77>FjWFVAiO&+iJFS_iJ3jZN1PRn&5*CPs8^f?8KihZY4n^r++R6S~aj+A(g! z_9a9xcJzm#%D06vyfJpzugTw;RLU|poY5AT@C7@_8WI<8c+`fLJC|#PG9>cv=rN%` zyZ!)y=FR@Le|fYq6s!Z?S83Dt^1`l&dRAWpjt=V|9MR<)5XF<-1_s6bs0;eO*|hO@NWb6v3zfjhfap%%0^}WJ zj0@RON9bY5yY|}m*3oB-J2oq~u>ZwhK{hFUt6XNP4@6o#WG*|S4(Au}-pCXKzM5UE zeg5a!+1tO)5_=2ZZYQXc^ki1H^7y#m-A;#QJYKDbVUpN*z>eD}n(ia?kqmL=h~G3X zn=ymYJi6Mw8q}zf>!O+6BDYdIwEFM;aW*T{Gdc6j<3*4} z@8w~QyC2Q-+_F+p@o(8j%TDE&HVUba@GhU%>RO*7Pl>RdTjMorC28Y8b=*6ZYul>3 zVcS#DQ=SQ&9l?f)D#d9VB47QL)2#LfN~Abhb4|(3(H}_h0ETh~x#iFOe~Y0sb{Zul zd?S&`d2AvSmjC4R81J8g@L3ACU%0@7asf&TBjNy6AgO!XMuFD&qr9^HeWhFXBi@ZK zVq8fUW{!s3jH%k*m5#~($quncQ_*|wt{K0@sLy@R_fk&8Mb)}8|1n{Q+PmFE(6?Fq zIzq3^?rr9$jI_D?Za^RksGt>i+AHkV#kr8U2@e19>Fs7rKpD#%Ei|+&4Y!E=n?p)r z5V3T)$rbJyFFb){2k-{AP|QFH*+0nmff!s0++E!lUPU{$<8{pH)IO*EaV+fo1*{^V zjCHOY2rXpQaQ*t{OdkK^BPs6ZGydxlx<=ul1-3=`Sns^cjFWIZ!P0UnBBG*dJFMMi1?ZiaAmOS{nk~)Q+?%_pX`UAiu;k z0GJCYUf3u15ay_%#o@kf03CUd!#ZEysk3(+{pdf*>meOHEd2>m&ZKm49O|E2Sg5Q| zg;2u#(EBjJTeU_U+D$a%ZgJ081h-l8>O`AEeDwUb!hj+MK(=zSB5>7mV^P_oe zMU1Txf!0SV)ay3Fn`d&n-VAByTx6K;LjqfzuHxT$|1u7>MuPTV)$$ zDy-xv^Y95^|9Z780Vv1Gf;m1c}0KEA+dy@D7!v1q$rr;#PpikMyZ5tZ|U@ATc z0L?B2YVpQtzVKp>pa7_U)d-0LMm<%_4#;5#1V4l~kZ)1>sJw~oW{^Z^XlymY5fC@p z`j2&oiqj==r_wt7hoc_%Tk6vk}$<+mMM(`5Z+EAU7aP6$!mUk zx#>2ugHRWUBOOF`$dPXY{Dn6&Oy9+5YHmoaGH6++^Va3zg~OQp)O!e%AF4l@g4R+= z>9q;5|JBV|OJD5k-M6xUjQ2qa3=CZmB}inYB@w29;`ke!&y#Ng#5p%&-D11PxY9#V zJ3ASqMUyNDNz=kF3r1GXzughEM5<+n1VDi_WU&s*N&mpchs~UV`z~GAH1)k1t(XlG z#US~68#dJZ&G7gB0YY^6*mCF9vv|?wvN7kg>(xlWkWT!An`%-jGAfvwTmHg!_eXf) z0#F_s59#NS%hx>R)?B^{d*&CL!EhAiQ%t?<(I<+%=j_s2{jiq}`Hwh#!qp!hZD3U{ zzPWhp+%&X=U7l5ML>aNSKPfzqJ}v2#RemFCAWY-uA_w;fiT30~pcdQpZoZkYo~InR<>wQ? z!Ewa)V@oUjKIAaEX^b46u4G&MS_L5D2w^{KsB1pdpJ^pnf5_W7zrH7?ua zcg4|aOgbmkF2>(s1?44}cZ7hF-Z^Y;6i_f65Z(H#+_Iz$o}2Jp@D={2uhk8Kqt#6N zpAg>3yZ0?m5j&-@g_>8Rr{lk#MlGCH({!+5>BlM8((MDohW&~eefUaRLGl*;M{CL#ZG*#fYZVu!+``B2xP>*75 z_v`p3!I6~QRB{WBvdfA$;TQTgnp{JCQ*1VnL;ad3^6~bO8%Fs$mJz?YuEz62OFfG_ z0}V7fG<&ySSBEgF&{0!B!=;Q=2``}jj2Tx$N0CqJLGacRfZTZ^Pd~b1O0((i@Gi{i zPjF17JZH~8cP*9ORcb>d*|6WEHOv``u-?R%f=#z{S?&8opgtNK?R>IaYP%GqDeH2% zCb>VFkUr_DZ+1BZG`NQY=9+AHML`Bu%Ex_gR+z>aAWJ6xHGA(ya5FOsFP(RB0$CX( zZM%Ph&cjA9tPT2Nf0z>#!tAiK;qaSos(7P{bM3 z0M#lB{lxP8r>j^pUq#T%Fc!Qne|b4LqP-cs*8!%Z$ZlWuS!Hq)>LT(8G^_|TyaxD3 z8a2T93>t`w;{_gcJn0SJOjHxoH0R^RobIamQ|~LG&h=;>!-lB4pS(Y%_-5F-EujWD zqpmeuhw+ub{D34I)lQaWui&3f{RfVra-k0>_56xb9qOx=mu)S2q4#x7!=fj7o}&ZK z;g=F9$4#@4glYc#nN_F?y!J!v3r~5|8!|PtAUN)_2oO9>eLVfe^i5LxLX)Q$1!;yx zUt0g%4B*B9yZxz#hIe~*6(@lsZ4^^xhyslB;+p)A&X zs63xRkn)zKBKhAKcR;))N;I_-BeJ zq3Kjxi6iUqyH^5!EBlNGuSb$%?cpU=AnMY(W?|`ZN%xBTIqR5%%8u`iM7sl5w3bHx z!h&a0oa^LUlD0B9BC*{3JWx`p5~lS_?E3dHfqmg{(e3PX^GhhAT2z7zgJ>{*rF(wEXHsVX;L-{Tb7*<;~tZg@OYj|wun2yK2YUPNkF-0 zV|`wYb)PnMvd6QPtB)mNN+b>ww(}`CzxM#x+ovA!49?e!%>K|Ljj^u9xERDUMw)HI7+wn41a)t3y zym-VJSb{sdH=TCUWv4nj4`aiQL`0ni237^#+DWvq3OH@@waQp4-uLV6)@RJ{6dI)> z^N~FM%56lx{xN}9g(Qc;z0nJrH9Ix;moLSRwt;!W&V_RsKEU)y|J-$;LTF8+#f*W0 z9?}oOddYEu3F;aKy>0EyZCtiNvvPaUN%Ghk-jNvGRu=ptIxp~##W&nSsGxv@^-luF=|Yp_h=Y}ks7b;N+- zpjs{lzfgT(AEZfboMe_1j0_&VEm%)3Fi7YwqMOEo!Q3Df8Y9RT1(cH#ba_E60vlUs z;n}*i#tbgBOMuGuY%`)cE)IGat!OiY$x?a!v|N=TaY3OZ;*>1KF}J`6Bh^ApWMcK# z=HAHAb0ru2(mcjPO{nA&l-;lU*F9`&$xtPJ7c~)gj#`oZAB;wnuWv=6ftogG`2`w= z%v|c)ZdMa_wu~k4SSR1@MKDs}ZK!D!8I^{_XY-^^uIgVgB_+%HQf$ zGyG7^V(>M$Xl`{ud~7Z59QA?xv+s2UhBcwKK`U?H0IJu5zooPhhnD(qGU=~eXk7V` zGu##QLr$_L6=B;c@CfrPf+5CdJGMwon^)YM?Y#h9(ul^=9+ebHME@`8%r#|XhWjZJ z9J8gw-Nq=PvgSi{1aXn196@lpLV4(YMKEz^xX`U7KCcmpjY@RWi*L#iD~p{B>0ej9 zx88M#jxLo|O;hrC)#Bl*t{fiE!GamS7vr~$+h{?+a_%OtUTE*d zP-9+7yLZ{i9}V0oNrcK86{eS(fQrh}W8@P)Euf8Lz^?rIDof7VOANZ=Ik_mO#|mRn zqH0N1h3$QD8+}i99XR_APQG}pQB7}_^+Z3}GNR>& zyW4cU#pu16QYzo$gLiMYak%1UYWc-SE%*NI9|-h)!l|$MmDta3+wyBw@`AAA1Izk) zHv7AJ5Nub1%l@W@wKpQmq@tuvSNM7&fqS6}Buf>Qr>&$|`f{=3Vq0%fx6)MXje=_sJT`e5di@i&YZ~#$}`bw=+~hfxq>NVaVdE z47C468gF&n%S6WwfNXqKfSC7;)Q#({h~g0VIKsKHL!Lx%8Zyq+=9!HE0A4XvOOJqoR`2MX zrh9w3_TsE9Tzpm%A8{v12VzEjB=WnFNjyd`aj%3cda-~0o7s6Pf}Dppbd4}Kdhaaa zld5bfB2@l``pe_5_vh6x-S^BP^^@M0~n4-!URCR;h2@27zL#M z-nze3{Z;=9JSODdFXXH7PA*@RV0dSAl(~%Gnmn?FcB-}l)D?5Jau|4Dvs*L03D9&P z**JkL1*Hx(o}*C+stav!m3j5++HZb>9Xdl7bySEVttVQ@5$RM%wxW5^8;CsOHuGoV zzu(77Tg5Wiow>3q8$++(Sb|AgF0XQdYC3OAM$qCj;8haG<59FoDt$pi6~k7oFJzc8 ztmsYGY%sWVA^8L0rA=S>|2XlR_Mv{^F@-rA#U+|lh&-Pa4O&X!zJd26dO$^WAWB9< zrEm4`m0(1y!W6n4;A^CksC70nfymApng8Sz(v4&eS{5rG{uaJ%9nD^U*5V<-`^b1o zRoR}>B6V6qW>OVP^P0DoVHt`94$J`viK+t&y(9o=$O7 zpiyJ~HFDyiiP0YGt6{k##<8fFQW^BIESht*Tz#JwK|%bHv626&*@+`}*M9VFY0Ujv z{A${cYN)Pklj8ZuNV};Q22_fFT1T#VNx)J5f1JHzlx$tMt(n?s?zC;&Hg?*!ZEL4( z+qP}nwr!*GeZO8s0iF)1XDr!P$XyvD5W64TyVuR>1GsX)zyn=>mTz;P^hh?`4fdj}IG^ z86@81Bm{hihm@vn?c;1sfBEGw#rl^(e8Rp%>G;!5l`@+UEGWM`IM?UKvWHNB z7n@wA*L^3m8&GBw@D9Qm-d3T(w@lA}kWI(rx+RY?zs}PzVjc!P1p_utg#Fl@e-a^r z`Ax&`a~K?xT8te>U?CWB4nqB(o=%jnN2rjfe8KzzWqbx?Z@yfL##4x12(YyznybBDm6_`!n%7#ulY>iASen&u}$uABs#DGs%hCyDFWA2+#LtsLQDZ8 z!4LBT0|!qjvB+b-z4WudS0BWsc$3S!KNRhZ6!|FVK$%Slv^Wu3DH(766`q7ij$kJnM z&6mge){9;cQBaShl4QN`I=vaH@D7X0z3!L$<-_g z|8@&upde_;0wy*SBT+7BZ%j-?cGv@&U<)3Cnk32rz^leYzBMdB7#%_OaK0iHiV>jpIosxEyD~ofeSj~;i@vygHpkRVd^g6W`fM=N=P*cmrD??n`_Z!hw`bIg-N$ik?1 zxQOCq2=7+3y2N^8-7@dD=PPr&Cn@zZONxwWE@GabAkt6;6x#74H z^jM5=L3{+O?mhvs{gw-odkX!~rM4WmrAj}xHU8gt zBwom5u=@_Qe6rAx4I*gl#!d5GXrNpm_Z9M_mNAuJo-up)kS-wrG$xBbijEe?eRM{W zt7%zKcZ*iw&nhWNeHL-aEIkYKUF~WKI}M&>JMm*>qIkm$z+%q4hl|(|6^e<&C?!l~ zzy{jp8S`iZ{7;k zZeJ7}BGSuU)06v^lZ7RA3bw7mNAszQ!SVgD;D*NIVl>q!zMJBemm-^HvCM;kEA48z z1k7o{>J16TccUsl)Y)u`SINQs>ti=+iCp+HMW^@7L?k@Cupi5ar3xIK{(KDr1$m^UJIV+YHy?7+9HHT)){R zds~~j3`K=T`#DsDZh!q%nLeZNL$(~M5w*q-enov!oY$dXxJ*ZX!xtQb4WCU^eGyfm=51q5Y!rS$U*I<&dV z$=io|xlgGfp`s!AVnia?C{NZX3haF(-U_g+S9vsC1IVP5ZQ0xXX+PEg<)|Mg)N&(F zZ{CGf`W@N&sFv1@*^V@fxMY`@kPPjgy&TBLn?`mV{cUX+TIZ<7$F=lmXdEg3dz3wI zDU8KlGmvzpvDm`e8ff)Tq3T9bHGby*0u31j{{anw7Dk>gL;$dI;w#;ML@~+V2VlF* zt-nnl=>N{y3&31>7Tr}dCS}yg{P2m2T-%@}qxv!a>hk>c#Hyn4k#H zj!O+}jE^gn7R5z-0wtfDR*Q=8y*H*Roy7R@Ciy2$#V;qv%OX&c&TSw|igfZOuRiJl z@tT>k2&QxvHhzY5;H&WYj5N+ycL?(~krC1GOk(;nd|>#%+Nz-PvCuxAg?9UINR}AB zo;$x6(4D)(AVs@>Dn1`P0=%iw1c6DNtGZi7k3#q;12a2T*!(bJrj&_7Vm3Ny3oETb zObAY?{FEik!O4EnB?0M6ncGMH>@YMaKIxZJkO1@ahuKCSItT3&#BY#=ZU_NuvLwGf zO^t8s)KGmO_3rZGJK9^ImfAg|xV~*L7Td4%m`+tjr6!c!u@8rb zRgZ#8F*kgva#~cK{?I$7LOoeI3^x{hCZuC6A%#CCZo+AGg&|o3`rvlZdA+}p$ zIeb0;s+>UYC-TzL3V+rG0^RZ_@c?Nyp0OK|ea5exRuUJ3o_L>Lr? z6&K%1^tm~m?gF6O(BTYE?CSaiYUYoIxJUMWhMJJcIBSeY1fVPatB5x$rshQMcj8YS zhUPY>dVm_NF5aCIT^=To?B2nRAg=3vGfYKjA zk#Dnz2jCx?G2+-HhurRJbfk#E!kvtq(s?Vrp0f`!0G;K}ymQfycZ_02DeUnIrU;!Hnd@yT0C|aB0=^ALW{*7h>13eIHM@SV;U#musmjVO$V0l6933SQ%S6>YrhW16@kpE}>x(hi20Nox1ng^lrGwWc>W3E+Po%YZj}`r9M#pg7!wtsQlV1p)sP*ay-jxJ3{dA3~wI+7A3}xn^O~J zRe2%Xq#%dBbeVzQjGjqrOD3#(jpq+dj5<*rr&&}lbtC_!bS0wyTj|0Bn2vuD-r<6l{Ko%<@q2eu4C& z+|P`p|I*cja?%;`{_*Q-h)gZ^JzCV z^@lc;sS3LqJ_?-rqM+U^>{6z35(yaccY&q|Kj9l_z}#IZfZ?VLZ!1yG+5Mv(!}`yg zY02rX{!?F%PduDf+rzpVSpLi{<<~i04wwZ?^xh3wi;8pS-OBdy9sM!TM)D4_6wI1L%rOm{rm#1xjO$;1tOrW>|Gg^j z9jByTfAqf&^0l+cn}*y!SlWfMipQ6LSlfgxd;*z3@c#@kwUmM1h{|#DrrRnV66%5b zWdj1;U%!8u#7HIx2k?Cp;&q@be%r%~{y#HM|KDQrf5=OD;`eMjUWGpeMJNnkPlQGN zWu@xDj5LgjrcwTEJr0^69YgvzYSr=u58ozB?b<3US}D00yY1?-&eLvNNagx7{789> z@Q}gv50JM^rohgSQ>Pv(@w(bEAWy`^*q9D)*_OV@&0v^y z>EcS0r&Y=Tpz=C~qEe%QOP8B|8Par&Wv2JemJl(CPn96#fM7WtNyWvpsstwmx#hFv z(8%nQVd-`dtg=uJS45(d#gHK)(;%0_C6b5t6{d{&cza<(4q!32GQrsE`*@ z5pqMt%szrcv+R4`D}c?pWE&xM`fQpT>mu9xk)WVLIQ0St|yL7 z)ta0tz-;%k6KMq6Pbm*P9dip=a?6i~nVRtNtSx3r1=WTK1|QxLM0F`7X3%CtU>K&a zdp9XZTz|DV=iF%#WF;e$rg`4!s#f+6)`h3H=Vm?QkF!bo=B%-U z?Ugky+8RFfzhOCFR}jz009^+dkJ(d%8wy`atX@n%IM zy3@dZXxnUA47{dyb-#06y@zD*fDv6(8y=y62b3fM`e~ETvVO}zVFns1w-A1FTc%w= zLjp0J_iK9{++~2I~5WKHY?w3o`)l7*HcZwF-(hE_F z|Ng=H^k?W3^%1(uZVghM!u0-thZdkV( zYdPOp>21(a&6mX@AUGfzJTb9!%nsGDX1SK^^I)K)_nAv!a%eS#re!BJ5h+K?Fwc?q z-!-h|1!TEQv4C{o+g|MytS)E+q|r9?mMZsiOumiDWW?Tms3XnSqqJBDtMQI8+aN?p7$pkc|dG?7!f#c5Gx=~|B>Yhe~ zb`awGRpG#_g?vLS*YwEA%$V88vv8@)sFOn|F{N-QsQ%n!dtd^6ht-j2T~sOYv$1f| z!F-Gy<9kWshAC5%60rd{A%#ya7J4NYI&_;@&;C+Hd6iw7dz1uy*zWE3Gi2>Gj~K3z zISpKko}1LOi`(s=pJhRSINLr55MEyU^^bLN(YX~+L>Og*8;6mTmzLj5FCu;sqo0-s z%*GU+>+?=afy;t9ZJ4+>dG)Q12-Mfe<%dkX$59ko?`W9O8Os()_14J*01P(pizAw; z@h_mq_g3MMBUru*nZpwh>R|m`#|X##3Lcoij)*`{aHu`&Ge^zPGPUGvjB?4iw6~xp z8c=ijxN-GmV`J;eAB_<$@dG(BYl`O4QZGtY`piNBE0uBDvUTygmIN>Y_P<>D{bt6D zNx|G4(2SXWT$Vh31;+(;0AIm#?6Y57+SFXKQj!JGG7~w$4Lnbn{v{zL%ZMW|!CxTu zd*KR>KzMPT2))t}q^+vaFKzte2h=a4N{nQ})p1ka_aud3ut=Go#*hejAfUg2urPa+ zq?R@uw-<5 zk^wQ$WA=e|CYK>Ez{xDse|Y}s640|v6CH$8LzcASxMt>3Ud

lt>d3ueR)29x+c zZm{l>z1MP`dsEaxN>tAeO@UK)2C5;U_b)7XSF{+9f7C*Z2kTBilMWmo8XWXb5}_y^ z(YZ{pb;h>!o?m&|s)}MpuwFeFaTO*CYITg>GeXOzUd1Z!pArUK-}sDx7_p+*@g1^A)1zsZ zCa$qMnHx0arnuTjC2Z;zFMq0u^C_pO$!JNUR`NVOV3JKCKwa)t!5UlsdjV#DEM)QM zK?zfy5N4(T>ILE!CI17w1PS|;_wu*2OFF`&qUD7$mHj?3P=-M|w&i8)*j&Si*4kpk zHBvF#mfEk*nup>N;6cbja~^=1EOA%IvtDR}nVH2W0%xrCjt=!kQpPYJ;Xsfs5HnpT z;36k4Egc`UFKx5#lpJ(%vz7Bc(emEKRmS+J=qZ)Y)Cz+o$)v1ILsmWsWF=5!6PZjo zaDg3A{+{GeNV~@`L#IPILhRyA_fha<~_&FDyk+GE?|K{Qm6R4`9B zDuGNs=J}Z~+-pl>vfb~@%OheAY=|x@kY*Fd0&uWndzj@?SaUFAnPv2LYySjnKmR_U zGRzpn3=onR`qd!smUcJ~{|ZK$zpo}t=sySnM4v`nX`!cUpy1o?$UMjs+z%5BP#Upk zI%&gcU?M~QvO$%mb^?^2%g6Lhurfs(_8~)14HOYzhd}1lvR;QM3emP^Mr`&YL>F6Ys3*7G<9WXneEcN5y z@JYrO1CwKv&q_3zC9JU@dfa)z(mW{?r1#LWW^Fz53S3FGErG{1gXL{7rKxd2%>RI7 zFBl^@6c2lZXaSa9Q&d{e(oWq^U}z0|*Vtub*SBA#$y4M_0(_sVjnMn#b@o%4^(DgV z<-M#P;2ge(92OALhu^!*6yA}Aac=g1%>sBTMhFuH*JK5MVUV+JXV=W!>fyL$jMW|{ zWhhY?tkI^cAG|rQSE1RJLmz#s3|;UKqr_!|IIEb~W@l=;MyNVh=h(mrp>$tzf z-e%`giP&IaZP{2X1{Uutdxg1_oTnYoL@&z#1aO<6^zXFxi%xZ~sf>svTDa@orQoxf z0f*XErKNG0y4BbMWeW}WwJ-ra6VpW$%Rw@AtnA*U? z!xhloA>3IPdY#`sVxs#)TEgmx_yj@nZiG~Rh-AE9W@h8nU&WCkMXeZU`eh=vKx=+; z7-MZwj(I}<4#o>vTUZr8OhQOvZJk2sd+CYAGcb8+2yf%thi~Y?q*n$Fa57Ps59BzW z_)JtbmR6hTcaPY&3gz)4?O@T2Nfc)~Vy|z&caJPEQ>NSqK)!{$bYP9 zC+VT`K{c$*&|$t7A1ec&ANX(N6k{E(fqX$Q;c4gHVWVjxReyoK95?o@v|dDiwNE_^ zoi83>NrutrnIyg8S_Oqm!&iZ$<5aZ@myi0VgKjP{O$tuP^<4jv3jo*yWeAZenzK80}w* zkot5{p>5J8PDc0eXzCXP;^s!hnl&g@het-g|AK!8JBl%hBTNNM46e!pdQ)WelmO3~ z;u&-ok|@ms7B-2N$^rN}KN9gZ&j6aQTi3jvGm>+7jNO$3yCYcJxH-c>3$UU@?RUC7 ztb$0LT>xbn1U4J>;h6_VtZLWq;Lcnt2j$auJy6(1LY`c{e5y$(3_bsCyg=s|G1`{eC}@wix`u{Hs_fWy-mJ>sv4_sFK&l_{^i z*j^d7@`8x!Q=rjT3*DqaH0Yn^7^SAFcD$DvF6rnaFhO~OVie$W} zM;2|d8eP|LviH`7jknHZ7>A5e0p~QHHm#*-n#Oo8s>*8S^v?WUp82IaP@5#Uq6;&c zOFb)4!&5;YptJk5C&sPUI(adtr&8;gK9F}={`piC$|?MR`-;Is=zm;k;6G~3$iD65 zDU3~ET6tk$EqLR6fGhaiV%wAvv$c|)E7GSdnE6C^h~om?O$C+M?7c9G0_C_OrNmRy zeD$!cZ|#YZO4`zB0`@%=me9sL{Ljv$mC5Lx2ynlZE2tXC(lG^%&w`QJeT`TaU#)zo zy>n{Bw*6%7{A~NHC(Jw6)$Y)EU}L7z%B<%BYpby(>)P7E3R*Wo0*_aMh4V$oPBzUSKnmCUwzxb!%z4kvVAwZz(e8bV6PyL%|ann~fuU96e9q|6~ULgRcLd z$D;iILIgi=<#&$b_tmCFfW{YrmiZ>1p?PWlX}fnvne{wUFc9tgrsSkNjQB5$uL9G-yh*~pUmh+G1JfQ>vYIZ~^hNF&B zq(hx;^;D* zJD@!rff7)=M6QDEfW598?QHLTRN~EJb&Y#!qJqvi*~Akgkx1m_V1Q`{*3#m|!QvPT ze0qC8rW*4;%d$O^uC(M@Mj8b#EHO0Tq>lg-@!A7zWN{xqjdeMXvz4 zm@b!RFqD(4+aP=Wa6UFrs=$;eJ@NIf)#d?>LbC+=4Un#Om!-2b!o(*HOsvMwAD~W7 z+O?gLg$wK(6YBpNYRukYg8E*e%wUJzy)3}EDvf!m$G}PzStDjdkR=1=#BIORioHgc>d|Ol)>cjo@Cu4tj!5sY+0v%u~l zDBvAFIcwk`+RwBjngqT$nHoE9&_AaHNu4xgMZY?h&LMdQg38zji8FIz$Fsnza>?5U zLh?yEBn&4vQYn2t)sz(qam(0vW*U+S-H_(7q*=rhFLsOP{m3|nvVnu14yL8`669HAm6emVapTd^#ENGMcJk-JuYQEy2Rd2QTiH0s zav1DO4Gr`>|6=(oOx&PH#)}?nJ7>+BjE@F4(e35{DT(wB(lQn9$vU88KI|$F7CupANSTfb&m>OA__Y|jnNE?71K3w1@=KGcZHcwTCOolUrE~e}Eo}Y;oJ7KZNpjQWaF|#>7hmCbe$xWopk@u;`7)ePFd{?6~o&h6~JFZj}iJ05jt`%?5R7Y3l4H_}s^3W@%3bE*PwstL@&T)@t0ArauToeEbtL2jaq#?#EKVx{ zWSiWTlayyLRHL&{NoVuA*?mi#)z--n~a^-mp! zq7+5M0L-@pY<`CU;maeo@r2tw`~c@I;ofWG9^&;3WD(?Fa^ZE^#g~Y|$pj|GBBOU~ z(rC2_mImphTv;Cjm7;7B38!N32TgMp+!T);YHz4)8N_b-aZd%q3{Rtzp0I2*n$K6Z z8}O3)C&6q9X`23mz(7D${3ZUsqSkjE=LL)5wGPVAN5fw=xmjsiuse){#Qc$wKH`Jr zpF#nZa~HUHBZyIbTP=oaF5=fkEE(j2b*TaKsY=5wS8a!Q>>dH zW_Hc6Fq%x<6~X1g*Erp8VwD%hEq+2hyG`n;`Vi6hCdVsS1uZ5*@%P=_o$qiq27O(yIOsA<{|Cl4lx}@g*(FF6^z{A}ri~kVHO4_xcd; zAQ_!kJL|q3Y310e($F7%m$zb)Nhu`CkGC~%D zE2PnH6Vf3Y!0>?LB#;gA+Y&Bx*~rn_j-*PdmPvEXW5?UipC8{ACHY-zY2KoDj?@k3*9aPJTO#is2$FEiQJw9K4R2RD0SGYgCoo+=M#* z{yC9`8ktbX;LvHmKIw<*`o4kZ(e=A#>@LVV5O%bCZqw$zOmUyM706FNvmL(@A1X_D z6l+Gbfi(JS(3u!(ZpqfW;na%ET0cF6^4neY^3Y~+YPvinM#pYGqwM=r!=-g}bA7&f z$mr1Wx+5{v%xD zL4eDT>*ay-WbF_3_Q=Amwl{hP3SpK4c0(u>1}s8%R51q_&AMnKbG%Gey5^#`aH74k z<%MOIWf{ei*K*BSSN^?<_FHXe!4hmZMNa6v!a=htn-r;F z6kr%Yb<*2x-G-F1yHW`QaPi`_#6tW${}b)^^TN|#R|AKJuT^1~1FUWVZZp8el2^TJ zVs(_glh2dwM`G89*nH;jwA~^53kaDAZ!8zF_vCD>WKl(zX0Ll0rSmih2lGz{r^z?z zy2G*PzjvKKrZZ!qTIB~#sLx{rmHi*kqk@A(@KW0r}JS)X#B zW#I;Rpv(8bY8bGcZ8wGdz*Et;x%$bOCo!jWVljPsE|;SG)SN_0n;?_P83$MZ8Ll(Gq5X1Z5CD_)m%Qj=9@!H!gY~dK<&S7+`gfnlrr!~L-=(#Gg zt#TC&a`A9I-R{y0gA~#bB%6w1HAxWE#?_T>7Ij;*XyT1brSqt%Jcs*-m7c#bjTd7l z3$tiAk=D@kRpCww-4|i!8L6`}zyZGv-(v@yS$my-l)aK_dv>}{^P78DAA1}G+bJcSU*S3zs zz9>xtJ(9o(D#sF0D11CRKHa4a$BCZPbQvwf)bv~KXMiom-#g(KHk=@hi78PU`1Aa# z$Hb~{$ORJ=g9EG_a4|+XM-rqk_&y;c7=_=DYfHK->iolkqMt5G0r-Gs25(Cnz@iq* z*J>5h%8wbu9l5z`6}GigoDGVks zuU>X_Oy=Yzwd-o0v4Sw7m@PWRY>_xpLvb=KEBz?nBXnG@JVzOCnLDHw{b9 zbsiHd%?Sgt{#F*km>vQ?%ULveUItK!FvU6L=SNqPmbO}W;Tp=m$SxK($gy;q%qT8g z37It%q~1!>eP_EZy!@FW@G0)%wG!qY(jn%Mi#zZ{USHXWoC!>$OA6V0kuO&?bx>8x z+Z?UaAJxBr->?S)mN9CSF#)`!Hy+f)8BK_#vSXRN>`g^k)wW!TZl^CegitCjmQ>4B z01PP&#L}K{zVzuR?R?lp%>+iB^Oqa^P6*;E*1PaI;dD)jn9B?bID9@>7t#BGs1>n| z&KS{zI;~09RdahDAy!R{Q}CA`eF2m*_8g5k>a09>dFC?F5E%31U(ln$|XF ztAU&VrtAvYNqNDS1)eWf;yb#C=v+HKT-*EthppqHQr*l9JOVdb`xSa^%guk){?;ni zBGjz|SjRBkX^h4>e>Vqu^ZJ8{D5I_3Ej-hq6AWN8tR9=uy%)yJgC@ui7*q2~wAOA< zrJ^)1=r3m1ddjexDCnP z+pJCeZQ1hPwH z2!X!W-uMtYBIK?T)yJEI^aARz=3@l1u(@FoMfFBC#jS!FT>tIj1+^IZHGHU2Y_^qJ zLbQgaGzAKeV)>8!epn9t!vAMwS5UWA$B%$CD@zjNTLYIy<=7 zTMF(8(#IjNB%?DRD7jLt6*K^aO$8`~(^9L@oU;1EOBT*WRR;x*%ivbPInPStWm1(8 zqAHJh!7s3E+~~Qn>}aPhk*SVB(hi|@((=pp@lBm(^>e-7?VD^&MvU0Rf2vH)&rVY2 z#S<~vWk{2N6DKG?yI?h3q*7o<;v5lJDf?6Y#8E7^xGEX4X*)~5w{isa*BTv@P)T_2 z175BSz-zTcSUV^Y=4ZVXmzzoV;{+*pNb;KjMc+u zSJ>nG)ha!mr{HRhrZ;$(fidkyjw9^j`fIEA*6jeiPu9(7^jZ}K*Vkh=Fu;Erb@Hlk zcBLYjL5hbK=RiM_!&%>jm9$lN?h7V>(%dsh@p+lhUxw`9+Mbo&Fjmzos97Iq3PEeB z7cMt}%u<(Nrw|m1oReOum^3o#ynBJbb5K|x3QG(fIsdq*jX63)iypm%hLZ^IER#bh zX{tyWfz_k#ujW{o>g)^lbaPIg6~*`6r8T&k?r~hpG9KG3MP{Rd9ApbHtG)M^LXom1w`;4{ zIR&YV9nKIL!v2M+{X$LPe3|jQplFb8>2j|34-#o+lSohp;(e(vrD)9^oiwK zMwB^`LDTTnVmuSWEg|jI)2;`>U@%CDRVHJ7)h~G<#?pO$NZ`GEWd%lrnP*uM5Hpy` z&f>rkelT{A!d7bIP}1HYXDIrxdDDjT-=jEW;Zlu6)TJrJ(a6X(^}SAUo}{&YNK+!x zY3Da+mx7jE`*FAh7#_}a(|=&TQW*9SLLRd!@Sa`F9QJp9f-Ltx&dTYcB`s-c{$cY& zD7BeQPN^W=5dX=-cTRJ%rF$JjCb5)1eN6#|0Mi1tu5vi^*Sciv+m$12Fja5#(}}$6$JThZw{4hjlTPjSO&bTAgM0hub}Zq$IO= z6-1x3Jlwlh{xn+TjBD-3=$$w4HR+}hbPU3{P@s~G-K#kz=uNg5;>Q;k*znHZNvn)p z=I{Fy5+<5eUB86j>$gUwS@`5m1pz|D%6Ktb3ItBVQ$RIxPFq!MyW#{jF=I)Lr1^J3 z+^xqc@Xld8H(;7)-0`Q?)FPyH*eVr3F96*?StG22sS0>;YWY|sAMf`Ac;fw1DVUIM zp^1diBxs~X@^6sjCiV5am{|$l7ii5#PqTTMFmcNFh4N^$x-zZvp^|B%JPoCP!9$Wh zQ*`WZOm`PNb?m|(ZfaoJK=!L{EI;bxP=9`I^HB+=QH|rE5iWTLl3C>V_3~6 zMEYCZ!gCtC$tdQHYcv?B4IY;x(fxYnsa9KiCF#MsDQZei4t*Q!G6bB8eW7ury zGECz^cTp-Vp2&;V{at-pjDd=V$Zn$daEV5rLEMnJ{imhiV|g1_*ox41ee%>@taio9 zR2}KhL8or4^D>KfX#0329%A#rK3H%^v6GG+kgGvb?}dA%UyT+L;YIVJJU0~;7)M{9 z$|mdJ%W4DK%V>g;h|Zg;h}jo$Qc> zs3}ow?ZRabWI=Lg?2#m(s2d)n)(a*xJH9*KI}Zx~xYztLUX$6v>i&5?L>F!9Hdc2k zx)^4kD|t!Bm=X@LxZyiKtS2Mm(sNw@^U1=F(e^L(fZ%Y1R->HL^|9^h;CX4?g%|Z z0s5D6kt+X+WsuRFKR;&6gdnlQ(mmagjP{r(-Unp*;& zg8j8M0(7xS$I+V7+Djjc5SHIfAVjfLJ4+Ef&39_7%^#l)$=5emXOF@D%26bgsO1>w zl4g=z&a8!b0Irt;pQPlmr3cfD()pRw8Hhv2+vMHPkl59ZnGl4NB_YVj3Ed=#eUUze)#w2!=3Lf|D3Dze1%rP|Ja-0UU#3l-K|=v&QJnQtcxpnfZuQ1TIH^L8_LTx$E4ne1SAEt(p9t!Wv_AY8pm{Z# zLpvKj>?LLal-@^Bh*;uPWVMk5CkanB3<#{wQ~$;B!_&{!1hkExg88NoZsN#jtNlfe z-y7>#OV#usSQxM{NApR#r#tBGo}591+{c`~F$G7WIkl=l%Z+RV`!f)&-$E<4x}Y3% z$|;`N7zbDN$KKCv%I^ZTmT|{3x7{C#*Hsbz9w9Uc0WK}Y^H-cL^{rPTw z4|{FYXygyWt1Cq*y zTU(k$t@n&+e%S?G3S`R#fM!hsdW+y|O9IP#stoO<7jP8&r;FXL zqLN-&uN2Ys>P3e3p1%Qkm%&rg-M-j&)n{R}QVInKU)#h3bTyb0CxZ7EXnFScIr5$n zgw`LsO_~<9NL%fqzs+>>gE9IxF3`Ch3H|ZmsoQ_$-qy?tBagYt&Ky-)lapyI;B}>^ zH$2cX8Cl)iCO)n=dnJZDBs$W-xVTomJg8x1s)E{JaVDK&ND=OytU)@S-#(K)1_oB} zLm?G9xyb~!Lj4!H_Ct6qjFiH^J)g-J{QO01ge`?R(|HJ zad*z^Jx-wg@rSOi-Bl+qsZ(t_ZQZsiPJK(HXK_Vf>I+iSoEncDg4t^d_qMwrs=e|f z6(Csn>Fd>0)^50+k`i5%SG?#|!+;jn0J*aB8dfizk*{Al#Kd7HuqsK8N+McFMAqDk zoR(Q9^u(|aI(Fklr7jo?Xz90Vn$@Pif(`{+S8h>ZZ`5 zQZ1|a`^R#9(=EUkISJkeM6{xX(BSRA?B>1868qI1SLrcE+$e`f#@yyTw;#N=BVHGm zyiXi2_9-N7M)0}7&8LG*BPOhcoFa!0?x*eF^Cx!BgvKLQS zjha)$mu_B-RLKu;D(hYJ$9V8HY>F(&1p~P-@B3) z8NEl$Hj|?lpH7cTeHAbwkYFCOOaMid)C9M^lO`-LV}P^x|Cx8k_ly_QDK67E5|l5Q zd^lTK|20zq+hTH6Qm0_$;y0aN1*`fLcTmyDgeQP(#8uyv3?4G@pF{Q^3xGlLB}=?| znf`H}Svjm+Sg|3Z3tcoRiUE4vo~Av^MEu@bX7I+y9K?o4!Tp;{#~N&S^)A|!J`rd^e(SkMXEkWuxe9PNiwO<3 zHrZl(IRyzEOgA8|<6$>Uu_eo9phhoe;Xemn6k2wIg?}6>R{8!nTx(Xm8>(x5RM@h53|QPbafT; zGq50K885P2US46raNf?x`xYRWj9bZn+%`;_G z^}!y$4#=$5h}84Ei4TSAB596$S{cs|5FX4E%Vz55DE#0D}U`@|DH$5=^5N|Bx-hjrNoLCWiQar(&4c= zrAi+_^oR>(c@|&VW6O3p`eg2POH&%LZ43&iSV!{W<^Z8A7E>l<7YFtHOU=ynM!ALFzlY; zwV})>*gf`1j@}*z1<5MHy6>s--7=f1euSEWFKr zJ|l2ylWq1%q~Nw_eb&4zekhK+R0iF68qF;fnOY!P!QDwPy9j8-+2L@Fo*8J#7afyUJtjj`XAdEPfnUj31)r`8m&O$>Nc zV+uD%#0|cNr{Z$tD6k!LN1AT8iD=d7B&v{N4*hR2dXAK<```-q1#dRj-W;D%YP$fc zTt7g3097aE!kUxDTuC$@Npl~Qqw(!zK(x9al zG3J%O%wCLf)p;^4Z%Q$2x-*LzEGFjFHG7)tbXfy%1bcs^Q&3@IYUDgUB%~KL(?*)m zn$wxXj$h(QpHypAtb=!BTD_SExm35cX+6HCKH<6OP}E&R=yB$7p$!Aid_g_V!IBW}?CWDT@(vRYVrkAby)2 zJ8|5dR#r9VVTe3A(UQfhki?cvp)_O09@YkP*497m0)22qD}6sw@mqGe8#DmsEW= zP<4dU+hxS`_Diw$Fj>kF`g9?o2!&RFx6`gC$R4q6uCH*WZ?GSOklcDp^fEBH_p4|# z!_sa`gw6fHP@g(M`@2xb;jxaMfHOjH`zN}?tXFcsunhVw<`{N7JSikysH{fxvF=;2 zNuHzgy96}7W45X2fPhVy%#k4Mzj4_HAMjw(j#+Qiu0Jm~ln<=Z0Lou_KJ7 zzKo}tQE&bF*JNDHhJsyb+`eb>*a>r%J;-j%nv=(j+=WbJ^AD;~>a3X}eP+HsS;|(A z=I>r5D~&0WY}R8Vkh_LIW{Rcc)c$JFjug=|ARYZQrgHBt27fMt&5uH?UdiC2Bu}z+ zpQ@trd`)yreQ8OXcyh5=C#Q>Mny^c4%xFmUVdh~;!Y-=BT9?h(a`nbE+Iwg)C+bv= z0%5K0J?Jug=)!91_bb`6;{L^r6Htg+t?Y?ow$_Nmu0T~1BC0VXUv#IN>!MdFc zyT9?-deV(mM?~UGDXS#C$YC)@eJk(eS@21%4jrcQL?~hDRzu>CcJT054%E=X=egA13Y$_XN+NGIabo{Ny z_r6}u*)wqu7=^mQ>tByqDX1E?<(|`m?tB$Awg4AG z^4APLW0wOo)VF&(BxJAjsvotxmn!JRKgI#DeY+Izudux&M7^*a|1lzGI6%TxhbC9k zYB%+bJ9xRzpSl~p$su5`xE`)f=R>U`$Y@SK*EU5I_MaJBfz4xyP1oM#;@^tz!c5?6 z%n~|zg^v7gK{M6w`ngUM(*ppp*X!~2Bc@YZaIssw_YyD5DQ28RkDYaxR6l$OO*-cu zYC;N{ArVK$q>G8BzT2W?UhM=InHZ?MatD^Ht%ZzQoJ2HnS1^t4?b8id(-xb^zkUmsT?_9|9i#qFg|{1cOl z%1+y2a3nMZ0~6^|q#~gYAV8vc;tdcV`S=IpxchJ8p=^$O`$( zxdMJPOsAh1WI=JlP^TYIb4@1bF$m!kIInJJ>KMq~)Aw_jU#CYmE0xifRTh<`-UEQk zSVF-bf>o&OF+cqO1{NrYurdl0E_goJ=EabQvSpf9bn{N+Xzm=RWO`0NOrdP5a@|A7 zIU4VHV@^7;;;u0AZh55NAMOshmg@QI0CaaN@{R`G^Fz4x6I;an@KH|SJoGs8t6Mjk z6`v$tU*Dqx0cGp?)7;>T)%CAHOz}^~SL9 zwk?0PhF#T_FaVbck<;~|Qq6H>oVVQ0RKiw_Y%0(Xy8E*+h|CA(=q(#a-EA8+J9?(3 zt{XfUr6i@+=+G^C$)6emP+)jm?@x1oy)Z>>f4K7b^cjrYfW8h)5=31Y%lff@B){ix zM#^}V73iBt5O2)q$qXckG?Bnbg~cdBcB>~zCGXgdo)P_Oqn4h_%flA2QxAMN zq*t3g6WbT4GpJ~xB0xfAc?A}xxHWU%|yE4^Y?w2TlHD( z?6WFIllv-s`;lkq3DOc5oQq0&es3NUKn-ua0|EmEp5Hun69moa_3%^QHv3)m$dRR;tXv>%e^ z9}_>A-wg34>x7t{77zDvtI5z*@%P>(#p=^h|Mk@$V6rv+$v*W{jSQ_)lCR^v!|j>G z&@ln{#ASQt&o)iotI0%{kEpP4oEh`gM{ZeBiGo?-l((Z`Vugt-oc$Syx&GN(M5 zUbU3cakV+U=36@kr?xuJ-vuI^NW^6Nh8T{wH8jA^E+=gwn!M-Ol_S^Ow_Jy!2f$8#p`IQIwQo|nwfm@5C! z)qm@art65q+QWveZGv3NaMz@QVn_X0L=&UsGO*rf_#_)X3OM|<6@cK5rl>!U*-3d> zX{AZ7-H1bwwFI6|ReN1H>zNbr2?d0h!b32vA8+lRxoruGu2|6@=l_K;Y@npZTDyjD zNf8c{ARZjalOEY<3MpC6eFSp3`yaj?l;e-IpJ2N~CBT%W~k1 z^*K146m@SfeI0)8g=vHR^R2sWbLbF_;YIg#UFOf zma}@m#+3y4U)%hXTiOia_k1evqneiB=-=Hi*;E19`q+)Vd$`eJKw}J>Q!o!?MJM%4hBVt#BC_ON3?{|!GE0%9 z|E8~PJU0^O_`oV)#VM$0ezC{YQI<0#F`dK?HhBXLU_$gb35jY*O?MeQ`)$^M5IN}Z z4}hCEy?zs3m%E9`dkKFGd=4TRgI+@p*M{nt{>=(s;x$zVG$j!;5hs{@^zmhQDEjuLeba+Khu=ck z16n(@zev}$?pwdF0zn5^U?<^DD-HFtkxu1PEcdc9T#%+kB+2S`=qP;attX>8crWo* zme)5F^W+#Qe{TTI87tBHOXg7vrpR@-%~5w-n3oi$hs#MCgK%{5G}rA-%H3BJ%H2)J zPdkYl{k;K};Ih&KKy+`SwEU=KdBa2(Yzn6;Ovz(O2pW^C#=Wx?2p@I%t{RNA(}L3f z>&z;*jRZwSz61{vCh}b_!xcbpMgLHSK>%LQLjBIE|5q%L7|rGPolgK|fHl~L^43%C z`>&2h=GWC(s>hSBOu1Zd=Vq~{tLT=pnunTMjMpKICPx}c%1&C8@AAIZuJ{NPZX;s0 z-w>nrt$A=Mm@qYH3lMgTioEs23|vs`nm8&Up}2mfw?^RW6Dw)A0_EzMEV}_(xKmMR z_tkG}-e>aS0VotdRuNkWH##B`3CfY|duD;pA>F#7A|eA+%2bB3qIm0D%Tb#%!<=+xt|Q!%uZS-b`qvq@_pj!+=Aq!L>Eg%zG%vD|Ter%*^7| zL|1}+&K(k5R5CIoh^X+eN8=(Sds@Ht;m>L*V1mo)%B*EesGAeU)>o$yugSW3L{N8m z+G#T4#CL|ylQbcDvbp%d<$CPZ6oSY_ODrvb^qp|lb=3&m$k{#z#)t;- zB2sZ|opH^K*ySosTVRv`kiO%3C~qRgf5E;12^JKd@dE%AwXK8)7&QusCbi`nlID>E zOYADx4T2`}aq8wvqZKJfL&15L*4gTsFwp^eAObBD0!gnQ2rZ_KGGyTp&tP6iJ6$<* z`t0oDM?|Tj3ix1t2Dh)d1IGt1bjiIB#}~P3=yLd8C4;?9*eAAf+`qKikfCSFdaO_} zxEz<r4s^jrY3zFdPOi!QH|R^xA;en54nwFK7WR{jdw`a}K=Tj|c~ z_PbXod4oCyjG}%Mvgb3FY{IjW?vsz)wgp@Ook$cO3QNFb7*{Ov2Vls>cCwv(eVU!r zA>i;Q>SZGL`Wvbucg=dZiS^Tc?U!=t?|wQx?f&Vx&#!mGI{Hwn#@>nE8T zwsfn_E;mH2@jh&pq5V1|Oj;ErraAN-OBWDoh)m|6jaUTA3i{ix+0Q3`ciOEOygv-G;{wDX+UcO? zCH#9Y)@Gw8PpDg25PD1)UU;Z1T&p|wQhLF_r5Q2pb;^qt4cBIPsrP`x;_eLq#DyX( zl;>iiyLeKbbYIhE<>>QQM>l_?mZt&rJTt4n^JMJc01~3;t_Yu!m*aE<zR=bYTPJL=rLK+K#;P9#jt}+g~lujbS6y;V1z!3260lV8AWI7Be{7 zQc`P8%7kg&TUp&(Rq1V@h@cS1$HD=Dx9P9-qs9F2y|*IxmsL<^Gm+gCSK}feug7ud zd{=fv{Wo#R)3Krle{L=?gP*%KZ-5`Grw7pU|1=8f^b2b8L1KE)X^9U*yL9$(o9cEn z4@>Ap_XdK_84wGRBw}Yx>+Z05>)u5PTbVp)9N9B_i09@0Y%VJ!IUY~=%iF5;u%nwF zVPV1fD->lw2=v4|Z{-#X9N)D!ypNLTb!kv&JP31Yo$58}%06pRavY^+M?@{NV{`VY zN?WN>&d5*1QNel&(kbmi6lv+UOquZ)wVvv#&R=?r%h@X~7d)GGcG$iU68b`s7WzL_ z6*6kw3V>a+yZ2O0QcBv%{XMK`Khin;iyE0OMkAF$;=MJ?v6~+weDGYQi~;-eHj1t` z@Y|&TACaA9+25({+gi^Hen>^p?3&L9`;B5lr9kGeCQP>v$eH~HMPk+%*Pyj!KfC1? zUxbq;G%d$LYi$PyO0dl7IIiMh=?)<&m$?1mM-O+e{$*4eW6e=MB+{gi%-I0!>@>kh zQp?@$gB*Kw?LGrY4mqugQv`INsQeK^l<2y(3in%HkM&cS_4J{|J?BIq@W57ve1dj1 zQMc#RP9PV+eFADqCU7=-?KU_!nwF8m*GJo0vGU2btIgEz(T(mhmUwnsaAj}Vqq)(kNYHF#}!w6 z%3M8K6heMMwc1JFbcxXooJ0`=X&vK9c}!nJIZ>7#LcG*04C2;UMOpy9V+Its9RAEq_HjBa z-WgHes^CaWscW7zq3y3*a)1u&i)M`~TGfAj|NJ_SSC*%sA-y+x-MV z^BlRTXpqRSqPExvo2Tw!`UHC^=2v3ho>^`b5eH8A1F7y|_THifhJDpHOi#BE+@MT% z#a)xx$;(F~V^gWLUh^}V@q$;t_49BB0%(YwlVpP@klw_KsqRj?p(zL~I)5{wM2aLZXZG+1(qg;Hv$`+4&>9BW6`bt4u5)kGxs?g(8w1xrOsN#C!TnmZM}aLHmNd+ z?j%b5b;(9Z=*1q#q@(JEor5)H)rY~!E*Z}|eL|i&`REaHE@kdil+uwy(VD2dO1V3S z=`ux&hZVa|aJ6nzZSRk=XJbI=^gglT>j51rTZkG|hAgDA08Ots5dr|i$`xuw2u#C6 z0dkV*zPcDB_TyioWHV1$&D2Zma6hLqeCwm8U8A-eVK8R`sZN8Li5D3_J>eEOZVFyt zl&oOfQr9u2!v`3bj>muQk2MZSh24;YAz9my!?a9V{+8fE&I=@wj1R!3-pUmb8m;`- z2Z+F_Wv5vJ2=)G>kheRl14gfHdI}P$pXAxHF5o8jbqEmLcgCkOH-9wmrdAWaSHPgE zh*c69d|073K!d+DKL3riqnagqC~*l(9gx#j4H zV6qC!g#O*he$_Rq+dGBy?kA160V&OmHp69>dxq|kDTt1jSWSnQ%Xc-T>S|NuRml`* z9#41?*wx2pSPtvV;y)>w^BfM0N_d_(xfUeWS((|nK>``iusbYbaKBG4Ny}bUEg=$J&C;sN z2lQuJ2$-R-SjW5H0B{B0Jo#?r@ph!SzPY(%yRVT7ZY+B~a9g1n?oTc|?#5}L`Ga}}X+Qjksfqz-Y zY&tH%`g~ZpGG*;Lpl{qw8;58K#i*^n77?2oWj};YGS+P@xx_hSkj4Fa6`No2+4%TQ z8Q`gKY`o2VzS5)|IXMp$^)L7jp~|;1%UmvS8~!`PKx2X;pR~RxEA1;4Y}~3qC`e8* zsde}pg*DBj>WCmZ;XfU;XaHOK3?|W3355;1jt}2vXLwzXMEe37R=kG>e2IcWcu-5m zrKq!xW%4NEdmFB0NUpqbLJ-=+5aDGMGQzfw6w0KVmw}{iW&ZPf+V%= zy>mLJQ;>t~(fAl-5|z%$Oc4i(Zw_$b5)Q_-1#qV~6{^+KZU z#OwgR+d%I_A27z>Zt8yFBjkH|Xz91jrRxzjWV&yuf8qHrOcAMa3wSy8xR{A;<4|BA zeiF9|ijnR6;rK1FC-@?L0R5R<$CC_G03tRebBxj zN?W+}-bgzaK+sQ?vTq5!o*`hBk+6teOu!4ZaH#;^g2j*3kTLBeQm8q30783Q!kt&@ z;Q43n&jZJlOqxU2uual-7G`;Kz!^LkNO;jiAqw&Ra&DOnsSP}sO!|*7sh3LT9ACpU z@#KW#g{e!?Rc>6@611dyvkzQZiKUZ)A_u^Qd}eK{EuY#C4%eb=gIOoJ4rjSZNMQY= zSN~10xvSq;NN2O&wa~x{y>s25QP2ygu*RWoSG*nvK}l?6RG9m`w?N@5g%m7*V)C5U zp5~nds*Y_86bACtIhmz_e=#u$hh1u!iEk{c2*pfoT8B$_d$3^O9VPX98*gWv=Oc}$#XHLMX*lQ{hepdwbAp;#wNq06k8{Z9?`lLo4;Cx`h7pGfvOt(%8wH`S!z6vM`3j!sh zmjf3(!K5OirC@ln`v;E6kPi;f4nSwS zK%suG>Y6Gme?GhDsQ`s6qQ1#5z3>@q5VWApT}WJ*tH$33QvI(Py6F?+Yr2OcY> zm{E2dj87ByMuv&8#+Ep+nP$*x;=tkr1CDDB3);}aI>sMZiiN|M>(nW-9Lg>`C8xgP zk&TCI0ryR_T8+#K%R`5HnWqDnLk0rcACYEziku_Zzai&$h{ zluKenBDn(5vZX2&gJ!e{nFLXF)L%){SPUHzNl0I+8Uqi6T?%wPOTq-A7HkFQiy-jR$g*olHac1B(@@7uTHT059lacoL?OeQuxgQUk=g$B2=sy3SBpYx*v z0Sf4b%0fo(zXbp5d^pQDaM9&_wiVc4jB2q$QO_-^N#l-}+eaATv=i|;N06Z>+icwO z`#SiKaL=_R2z`(APF>OHW<0S{+8~0rThX~!g}D*znzi!z(BHd$uG_9#@l#L`*iq5B}Hk>cGJIg zQ?z)Y(%wQ}*Rjc>qx~9dGPJwnVK9)slYih8mNQWBdj#EvbLyb27YFPgV}o*=Y3|v= z&L#I)rYL{ZfUY4$kJn-U%H=}>E#U~&QAB^?HJrw5SQ|IqvRREF{5ZUVKPm+w2b+#| z$lyZZtBRfaJ>-6tJ$apwZ$_`5GSvC{5o4E07)^m#nA_y&O2)3F(F{1%^d?lnlIQ~c z5DXG?pPJ#4Mu$Wd@itUc=Kt;s%F(HhCM~X%VBYpPdvkp;sXz{Xs&T9iSP% zy1(GmZml3YtI!e@MbN`N%~OXhwdHYKvu)EDas`3WQ*!{9h%UTD^j~zfWn-2p6z*-c zE1&+mYqO`v!vL1Ev~ei9fg@AhJo|ts;5Jk2Tdmk@oN1vJ<>X58hd+=g@UK55yno8)H&f0BAjidEB_=0{ejDf0q~RMRQc}7#83Kfi(*l&ADc!3HG2hSm zEPqb{^pGWvwBW;=a8{ul!Fmz^tkVOP{aV!T1{^wO zu7Z7GwF_^Lib2aLIZHO%)c6;)B`;os;jjT>)Ah3kr9~oF!0AagKPoGI3MT|7Kfu61 zW&JnCD>u}48+-?`H|%YN!8oqLEi7pVD{(AC95Jx%pXrN}q(9R1Ne#?T|Ki_!NJ<~T zZsGMU%f;#C_Mnu5WIo!nD51S_E1UhPC{RLd47&OpGuwPXj?Thjjyoe!ZNB6aOHja< zo>oAr-W$B@nD2x91j(MXbZG`Uh$p1`X&kX09T8mf`dJ|i8hukfU#{`5i#q+KF>zF1 z^8Ox`GCwDeQN1nh`@O(|iu-kOE5|&^aP>EWis`f40#<;UQg^;7j!qD|W~UXFOzr*1 z9R~AYOc9U7Ob&b!BQw<&n$DqP|0d*UCmXYjo+SBGnsQi!x$qLrJ4e6K%MXn0Ps;D` ziNfVnoG`T}x7pl1RhG>GmNaRTJ|wut+1fC0Brz6` ziJ4vtd;7`91zx(u_5%Gs#Raqjd$5;<Bu`|bX<@LTaCUW>lZSs-#!D)F~vUo+c|sW}o_IPAQFssVckT))w~Sy;mF=&?}} z)%ZLow1sZ3mTVZRO8`$gY~QV!1JSf?!>?|7$J9z?23_EjcKQR7gJj|eb3*+(q6R!`}vr*Wh;ArT$ zW33dG*+(|t=~oCMwFQ%shC8rIWUxU8x~&4--6mk*hLmy`Tv2XuL!Y;d-XI!H4!LJY zES6h!Pe9;whHFnD@vsY&%oGW>UD5pc;dm+)7H~@4NeaAm2U-_LnJXvdvtY<$6@rD6 zDsc$B&{5Ui@|igfOG5teW7EZpxZ~?C{V5$)uGu9Aksk`65U_T9iU~@F%S-yVZZ_U% z6oR^Q?y4)H)6{AIgijRdvzuVEKlVhofbP@EnU^m9ixf`^CjJT&klfb36PE(0R`_ot zqn5TG)e$a7uZFq24U@)>%BTMLV{k;WP`ScDKL-=G>|>0UQ6|V3oDP-?1pDBo59mk(XId%^U_S)tux6C{u6Nl&leDLAI5K-a+h+9IEwr^nk?e<^fm z6HAFvAs18wfK#biD-!S)<+r(Lw98<~QBr1hf7>J<@@AirOoR#kfLI{_n_zcGD{Imf ztLd8SnY@&dxM|lFcXwjF!`(|&OO4wl*cUjwclkkanQn5}-7mT}KLuMELD{R-N*hd|k!|d901rt^F*Ho9dK@-R zRU)bVNqb~9R#*@}vx8@vhH)cGFC|&qo?{OMP zttGqu@X$PJQJ7i_@KV}vk$i?0n@iZ+bLxo3a<0d&`=rZ;dDt!$()R=B4g%m&A*7N^ z5Ou3y<&QF8E%{9Q(;Bxi#>+tE7_Dh(zr#t%Zbol?aJgu2=4i&~g*cmTH$@Lj=~iyV z#m#to&nJoyB%-y>6`RFPR2r?y$ORI-leZ+YvXR`}>RWgu3@Y47L|^!AHckXQX>-ke zqzbxSG%tBSH&RzH|9Hj_s}v~Cdj?5a-s?C4Rp{Vors2{b>Y3p)76oa?hjilp{7|qR z$3X1DBwF^~BQtCdy-GSCZwCXUjSeTC^Cu-kS|)L7$>cevQ-qMAr#iGhMNh-eKi*B< z{RMbnir(D@0&en3ZTYSk0uyVN{Aok~)Y45sub7!G#?&+~VX3j@JYh6zdvDd~%(<0eaN@a@fZckNVhrc{fq2aP0=kUJUz#HL>cUc6LD@Mtgr)57&e_hCf9p1;I% zHyb02S)1|H@y%|-r5!*Zw6`Ii>8FD7Cw^sFW)-}Y^80Ie^$__aQN6yv+8hv#yzM(G zq1pcEoDA(H%NKui%0tVy7yEPD{1VO|TS0+;$Zx!i2Q+-1Ta+!?<#G|? z7w@4;i(~|))(3NE)tP1`XaXjo{U(9G@`B4fRl7VQOLM>|{x34`uv1QXsX(e!Y@NU; zeUONs`@bL5rwPc);8%tAFRE%bLi-hI_2{x%?CHG%woXtI=${7I2>|f&4HSclYzaUx zZ#4M3rWCqQu7!y_fn9o6TK*3SQ6u87A$igWq!?I6}v= z_B~>7pE-TzC*%TRIl@1%*w29E%?AIzbHPc&kT_~U{n?cGE>)lD!^QnxC*oOlROF+PWpyUO}d4S=Bok2dHfDk477$TosVL6mw_og6#Z=L&* zETm_pNB4*kDI)(oAw7^_{t^W9VQsP&*gXiIc;JHcU+Of!a+Gz z4;B4^>^8Oe)hwBTvIF5V#+}L_Da8>T9}w#)tac^vZ6G*jKt|6K@5jLwG%4X3ohUol z(G6$>1T_T-1)t5w#BmK1Cs44Fz#lzF&oQ|y#7*R>jhmB*UwF`K$cCHx+>@~Na&vaO zrwa#Sz_ST?(|Q0P+0*ibg24dzfDWjS>S;TSmIb4=Hy5au@fL>C7f!R9pneXK!|=K_ z0M}v|RSDD#JN9c|N-ieY9wFedAOJDHv`QpZ#)M21)jOmEIkKMSLz@;GucWR9YzP7z zsXfwKfQ&+&TRu}cgN7qh4K)iz!+MQ|NmWZYntRhX*(!k<0K}o7JP4TSF?C-7=$!01 zVr0z<7F|orZv9Ip0->ByZdwE5W@~45dL7G9!J#Hx>Y7dgyzkhj@~$0_ZX+mMl83=H9QYxYZ=qzXXD z@N5kFo6O^L`NNFO-wZBAxx<#fXxrvml_Y;GQfOlJhRanGiR5vARo=F~m3yR~qIsHn ze{9evAImqcZoC;tB-f-Cwk)E(&@vhG>#PYoFs5gcC)cXowmLk+A6wksPKPTa(AmvS z|GGY-_q6>EzR<6u!@t_l()rZHeIEKm>ZddG%X1P!0{wx15CKih1nark0CXeLSUsH> zWng{|OoMVgBK<%ldyP*w8D@>x86`k){<=FTmU(M#^E!F#vt_=RNVkNG_5O zhTgxO84cPqG3`hFiD=8TgWPjeO`|=Ycrpzj=|Ve6o=S!CoVUJ^HWPq!5EGa`3Xf<%5j9h?AQJr=GiB=ZJwpn=eD_SssC((#TjT^N)l$}}lHD+8 zx-PZ*C=JL|OV7-D;41!Hq)PJ!sN{9C=mu+|Aq!$O)zQOE?Lnous$X5x<#TDJExvA_ z%{RPp+--W6)m|AAhJlV%M<}Xi7p4uy%zw)HQjrf%9PeuGvam`V1vuyza*h?X#66I| zYZT9M2psQvReTlmOw-C{B5-A#e*v>{aZ-WJed~-{GD#OH-$h(RoZ?Wx+Ik<1Iy=v4 z-{2-|nm$)Jcx(pYyGXgAmsh*&ZR>{^tfcQf4Qi~KtdO*V?->-Axe-zzOmx|p+4|QC zSMrj=|JD?DqMuHxR=*_6Gd_CzSUWpd^La)3I1D-)x<@<{n1GnvGo+JaqviB~E0&9j z(9FTXBOJuB*M%ES)ggzzAf}YyH&7hx-yfMndNQGpmX3mL4K@Qr^ z9Rfmwkvv&mdGMh%2vk^+|5gTWcs*&jZw|Bt2 zCw4}jw%qVxJ%3}ctH6wH0WmOQhq@?|zFFP_{T9IF;SHI%xUvTFhzx^U+SMVO{^E_m z)0O~6VG0yC9{2jT00O_4PJywWVVbg};4!Y5ncB?ihg>+{D6d1&J#Z7XqGo`I`?FyF zxNHiG3{o6K`|c^d?G3MIp&t;r^TTTobfT_V4zW;UCL>T8LnuvvI7{f zTcVC()-f;{7R0y?lPawbIp+IqS}Z3+VXa3;`y!>_qagHIP{d*2y&I+J(=iFrO294n zqivI!rgPt{qNaOTb9Z#@S1O1&>S2DEBQHyh*f3ARLgnkBkx9V;_2e4xkRr>e?RB%x zyhWfkM=#0Egbv{|WPKsL(=k!w{oFX&8iTZi3gCc7c(;ghi;ygt@R4nC&lOEvqiA>M@IH(U1 zbDt^C{XGaoFFp2kFP=R2TbCj>?ao!f6yCQ3V%xzLXlsGWcBdPMe5!_vFGNidTo(_# z1?Vh$<-fV4OC~AsGndu`_zOka_wIvkOx9kJZ*K?Zd8KVS`72;~xr5JQe z0MMz7wD-k_8?0N4LNnfQvD997ksF4jT@VWdYeE;V$E$5CZYFg z-3uggQc~Gw#+c#~$Wvw|koT#O&6dR3H>NGOEoP~X-Qc2jsvDiko+Vc}f;oHNHifQ} zC+Uq&S&Di14YciG`&l#@KW5DhA%D^()5~YoP#79|_so<|WBP3=7NB4KJ&44Z&af6g z2FxdM{p_Q2PsoLlr@Dz)DU)P`+VenZz`UD^;fv^W-OqNy?kQ@|S=?T{*$VVSjG2i- zL{L%K=_wk@-)Vu-C1Uo%-kOy!39@WT`_&$(m_A5nqi-(|S_~LQj@nDX&NF?kl@N^= z9)ZC12~lhi)F%ke5W>-zuz_Y*a!oIcC)dJGmkb&m0}=Kui{4;9yb!qW;ImabaeQG0 z`l`Y8K-X>9K^@Ov4NO2K|L#q|g+6|8HDE%Ko&3sQKZw$+VQPtbhN7&g zRK$xQj^b=DY1e(3G>jLl0&jcqJB4dNf?1s^@D+TXHOqh6r5^RO=2o|J{kZ`2hb+dOP9 zg%{{E{{oh2)B`MMN>(gk^usr5ebzr9#wFp7j7V<=GoOlf-Jm{d-Rxj?GHa6u(h3L@ zK#QhF$+&u2!4F%c8lkQr2wc5kt)(df6KdtvH3UX)x@1yf_LUF};EAz*b09Hp7_G+K z=CvQwlQ049fP|1-+K25fp>k!4wAGGZQeteiRvKF5Vcld9JB zepce536_YoU}#gO)ZHIIx#_^4tw0FI^rT2aDa5XZfk-tH<-)@vu&7`Cy~v90DrCT; zCEzYLx}vWFaa8W$FAo#8tdeEPg!1N78mz_RC2#8IfQO97s!eJ`d_|tvpdpjnrX#jT z){@(6@Q1Jf7|vs2*s-$;3?bA=EwTAeu-G%>B*J_D ze$qv3slTaQW={G6zCIzEo6(-F)!>u^{w&)6vX=kv&;QTkj;KJ75AB&~nH&7V{1m3v zGr;qCMp4K4@VegeOWqhEh^;!vjOGID`0>V?Qkx zME;MQy!G3E9Z;WW&#*ZRFd4b0AG(@(|BwiTVvGyucLL8hM^!UuFkCwGuPUR;P9{Oh zPPl;J6FweXJn=052`9$NL+Q;(xpQ}gk*J?iJL3hoW=ztbmaALGA^muZanu8MuY}rl z?!C>9h!EwfflToIn$pw;;U6k*L$)B)9hL7}6yWDEB=OPiE^9hf7FmXhQG}I*edy?4 zE}H?k;Zsrw!k2#UcZTIAS3m+7`%?NEI=*_2bg7!6U=!T2B;FAb+1%87l57d5p~7UP zhfrFHi$nqxqmi7&2Pn<&Yjcl}z_3C&CI=!uBJ1Q1;icG6Rd`<6gZ5>#CqJIzJt|t^ z{@r^>`qZL^O9-tzn=P50vE6=go38)}5s<^ruPh=WuD5quVu|d#1(n1Ym)DmseCj1w zdme12{w*D+K<{dv_Q6>;!=eLgt0=47{-V~b>D9Sa9fIt0V>lWPFuj}Px6u}r(V~jP z5!~|_T#w?%3hfjCE6r*6ge(NlvDv0f43`ZmT>I%^L9ry_0W z9j~8S=tWK2Su#9woNlUJ`f%dwd{U!~h_6WYRwVu3@PY%3-$qRlq^9uJYvkwa)joWj z0)5oB4WLuMD-o~k##vYqXu#2CZR4%E0K1Qjo(N&O>h>|WG**USK&Wd>&i%R!W0C3# zt~WEZUHcFL?pHnP18SC*`=yo1@>D#+KeA$K zS;5odGKr1HY^%Wu$4T=j)7QwE&PpVFnqJq~rD^wfeBnw!Evy6d=l$JgHex(8R)Osk@xY)Sb==@D^@b3Qy`)~5j}a}p70T*h0Xv78dQ02rkQ zj06y{dc1oPK_fJnkDj2%)F}V}(%X7-s|VeGcOMEOjycO_%P&F6!_jW>=-BKNl5lmN z7;F$!d^af%roKsC_EY)!k=LEJGyJ|NkZ4sNMR3Pc0N}nd+<4Po0_xUis5zBWjnxau zeMrAvsZb8YYv4!4f;tPI)pOt-tIqlOl}}C*slYXB<8G}seVixZFWh=JHrP7!cwMvV za_7w*Npt(WpN`LW8v5Odw#GQr@-a+=vz<=4-{(cwtWzY9x*JAs&aYWdYnPEpI*1cU zr-%@|w!xQOd0YeO_|}W_ut#{lM?gL)PuZ)kX0x7Tw>g!L@JB6~m%nh>UD!ve)MBI8 z2f*DViuKTwdN2m4adj8{sl{}<*VPl~w(JdtPZZCV!282OF4G8om9!ej_jf&&HXuS% zK8nUKI-EN8O1CKHtX?2oMrPAm-qyq=XZhb>HiFEF!`iy{15(;+S(il-v9YKq2bc_QBjZXtChEZz6Lek< zRs7?Mw~hO*Mmbt5v1+QaG8Ak(tHApl&m}oZR`^~LDRcCBjUf8c5BsF zybeu-OgnTsED%%2UaS`;eaCkFo@V6YNaTAPu2!+ny1bI-<=~*bqUk`Unf$VlNkO4hpC#xe|7lbmzffsn$6F8EAjeT|XWy+N8Tf!1e$g>PbCPUU8_e)+mNVW$#xn@}|qW!{KG zROIR(UoOaP9U--R1Xg!l;|JLM`; zPcVsJjok-b^b=NtL8Ka-oU^75ojzj>SK<4MmN>Ei@o?>Is)aC|bp_zo%eXG!O_g4^ zw+@c2+7*hU!?Y_3(pnG2JP+^WT>3N0H>;WOaJZZX8~b)XPr$3C@`fg8l{qr87Br~e zo`=4z+C_b#UCl*lmZ6RP$5-kDtnIi-yXln@x$DOCJ%07AmL_EBvMwh)5(d(Uxb2S5 z9!$P{w##-pq87wAw?p`==P`CUcL*ZQhW)y#3W*HA`}KSzNqKmTKqjHpyENG|=ClZy zj(bFcJ_mA)S~}gIsU#I_yey}F{~yBMG03tm=o&2B)n(gVw%ujhw$asP+qP}1%eHOX zcFpbQedmk$F){P=o)b6D*%>=e=3cpSrKQ**!=J$EiyFi%yZZGgQ?JoH9uzb8MEUsV zUEO%+i+p$!i1#{P57#UX1GZ(ft1SjP5^AI_rYRR4xagD~_QLN}u&t4iqtbG7nwnb7 ziA=#j->w2*&@~=`-!DQAyu(CS#rCfCkJ(x$dC-EUw(AX98HXf>o(`x=*HXtnC?;l? z4B3_1%F@MS6_7AYGA{mv<5xF?sDM`o)6#eQta{1sm}A z*LL2d(4I*kfHIK7X6MlnmI)$shDW*ZD;-UNSF_cL2~`Xmns%7QOkM+e_bw`Z(9wR} zH~gsdAuLGFzKDOsNdo6HJ-U2R4%}9_-5T)b1Xp&R-SUsJo5+(Gs&+GiE6T++@lhqK z$t{R*G&N1M<7zNf#RjVXi%ttcz<^~AvQ5Agm5g6)f%UlQeH8QuBL_#kIix=JU00{+ zpovGQyd$e<2z;S2o7ST54lWk-adpVfTZ=a$nP5(R%JUVt=+N;BOBTbD>h*3X+Q02Z5}=+9xTmwc!hi35@MB{x#UQe za;$m!?4Lhh`#uFT6`M5fmNHjb5s#L5?{y`~nI%f45Pdjy@0QVos_~TNe?*PW(c-18fn^coRpTmWl3XesDw+E7Mmwj@%JnX=P?Hn~_Mb zw09d$u%vf=jmS!l)X~&qs(?)$_y|XEn23}Xm2Hh6q#D=1MAiXa1by>=tUcUOx>HIh z&BqkcVEnD2xP`hFskLN zZ95#Uzaxzu8A8X#&=W zwO=oQpI30uAuF^tFg({Q#!;;OIqlD0JW2ldE%_5?H#XGXi2zsfPpDk+I#9A4!fhi} z-ib38zTHon#*tJee+!1!*~sqc+I7m$*IT6mes5~0-S7}*JFLXa*aZqA)%_=%vv^GD zKl#&|6rLfKvx54KM_a=?K86`vsya*cF0Vndk&da3XWpEfW@21XGS2SiAf;_yKS~%g zAA{lX!=pyeKRFc#afJO|!l*KaocO79*(~_ophkDeXI5eGsajTi)6?V*^hXG{=m9E{W>1-sI14z$zkkh(vQdZ1dDL7 zLVoqWS-~M)|Pv9z8d=BxK`P}GGwWw?s`#LVv!Lx9TN*{ z)#GM}S`^Bx8YyQu%sjO1igH#3`n$L1c#>r4?va>2`$=r0&i=e!n!HQ@F}?&J)5px+ zQ9IOgWBA?RJI6)mN5CP;QCaDR!$5;qL@fmCig{JSf(QK__prG^52X}>vl1( z>8#m+H+!Sf@P2sfd;)v`v#Y-kq%bw{^O#XlUR=nz-G33`sEKPln)Mcw1i+z67s<_1 z)s-jk940%CmWrPamZAjRGH-?*k7tC5j5fJn??yBP3l6?V#n2p;_RRHqxHp)iJrnj51M8>t{aEf_)DBCf*2BeAs@=S2(_~;4M!p?Up89&ucC`Ni95}!NU zOZL8a^=!Z1QiMaA(S9&OgHLa)PP;3AZ`ixP)k+yMNO$tK{N&$yTj&`cItSr=?46MW zW%9{U&eZG33A?#&t2w$r-DM9_WHy~+blO26Pxdp}E-}31yN@zF<+?P8II{-Vk*-0V zd~tar%Z==W0@hRcLB{mefHe@&Vl8mVXt&U0aa;NK6s_Rx^E#I11J{ziln0G8Me>Em zc$e%LuX~1tJkVV15+36T{e@v?$K-3p3OFpF9?GP*HPho*9*ka$~!;4vo!59qg@4pV#YrOxWt1s>@)D65#!crugSnLUurDITLqZ`hKa-neyB5DpOlQV|yXBZ@EF8PjQg;em^{RUOjIo%heS+}H{EC(${yDeJc;R^OJ!tiq zlTbh#82tz>r&+#reL$8~m*tr)EZzuUtC4Fa=F}g;YenR+k%NqJn_} zc49p`hXNXPtDwezPUEq9@g2o~kuxZLNUI^!n`-(oWErC;z&LHCM9$*m+karxwIL&3 z*&+i!C?>cr2;aX-Mt|5k-+Q9z!JuGjOax|sM0 zMBGr+m0v$LI67Mp?;jJ|ReHA+elyNirQrA5<2@MWH)%x8rd2Pw`)-Ym;^)K-O8zob}Wy(Vl zMN>WozENJOfx_n$6KPNQYLvsxWw|Ej`6~+Y7^oypIG2<_H&0sJwQ& z=OMlslEQ29Gff7s@Cw@9#m5RuQedt8^Oab&5?RlN=zoTg8{&H6;@TM#P>o0SBk_}^r~n{ofhDkU5Z z)AHX-+r1kX@CL-YK;P7G!{u0iv=y71?E=0*myUfCnJJgYdbLu&s2>>%;#^^J*8}|3 z1Fy(@?`qPz?2tYg)?P^krky;N$-iW$>!7=3kVkt&czHe%L!PT~#hQyHeowfaM`KA# zs^wIbbpQIzog1V7DtIJdek8!H%3JGYHv|)rr=Lv=j0#LK%VbJ7rr&(tXY_is*>?&S zP0eg}obKc>9V_`1H9XYaTjcf_mPjTm#nMGU?{j8kNhB?h@cDh=1+A^D^8Srw3W2G= zf+4CTpui&Nphhd$(15`Tpws#84~@JD?BIVu;Q> zv^4N!*nURgZ!T%ooIW}5xtMsvJo7b#V7<92?UV`WFnX%4b#Xyi4pQC^Mxfs z((2%R!w;vYHWC+GMz(i)GP_9OKW>S(#q_>VvD<)|d zJ=;s+z>>GBh$|=j>8?F5+o&0T{LnGvi_1jfscy5osT39*qmMgo(u|rsyCnv7m8q73 zE6_Azsw_$-^F9ztH9j-OUYeA%l)emyZ48? z?Ai9%nY*pVqJ>O>y>d@Gh%nX~UsZA{Cdh5EKs*)J&8JzJ(~VF0tF4ep=#q52SXfHypHtfzL#vj(Durh(k?t*L|L z)kL+0vK^tRp>na3YT!+;(*9Ul(t&hLI<8aPh>~~tYws9N_ttgR1xl|p1rsFLq<0X-^Q@rOe6A+qTk+{{&rw2wwQrv zk#fNVBDJQACr-OurQEj&RsQc$5CWRcu}r+oS6LuA?rfJ&<(W5sN7na#$# z3fq~GOJJoS6Hhu+Zd)na_%i|%$ExXRTSz3AY($|4e~fMRLcM*{QH`{<6sr3_tj@YU6!ebacF>ABZoL@TOlkq+?0{{yzy zT*Y!q(WF=w^t>|OILIz_&B&xOSn^bCXvQYCXxlohP;l}O%?<_138yYEmG49CX$uKD zccyL&p~uV3%P&gVBica*SwarQUQ9TtJAvVgxNIv7I)2lP=_l8t65yrC@D&n)@^cmP zwQCzVj1kf{$*!)>%&9rvvzDYe9ee7En<-BZI8I)2l_WNN?;)D$W_I{axV!s$FU`T{ zSc&ZcSP2ohU1`B{ZYlGHC(~L<)jB$YF-M}Dw$=V<;&5G3pS~sKuk#tdp)n%C*LdU( z7)Qsg#n;;bM(|^-WYN=FdgKB;?DEZd$J-c_XaV|G|H1V>u=AqY7oStnjx1^i<8p)6 zHZqBDszRXXWK7nN+3u8@97tE_*5bUIvo?Mz~aWy||S zM7$s1zJ23rB|mAV{wAv_dy4}ff<67@6?)^vM+c$5KlIAq$9TAnFDtjTU1>)R93&%? z#+m`uH3Pw}u*?2-nUAkJ&6EeRKMJ%SqK1k}Ej(yL&g)_oMU(aGVqKQK(hSl$T2Bw@ z%cHj6(+8o}DDl4E#~8`i+ z86~ky#+xt;Bo-aiY1E*SqI49PSJswgJPuBv8&QqxJ(X|9gqmtAqoG3zAuHO;@5oIGMP`!V zs@Zwj%bXQ&YwG4cb2r<9rpv6+rrGWwqFlpqLXEtF!r~-9(b#Nm! zS%G0WM`!lVWGTW~S6JTOzDIw1fW0i2o*7KhBDKm*uzo`Rn5=HkUL^a2;4X($dlI+o}{DrpES#RzqL@9YmeCH*xxD~UN;ATtP$3bAx2(trsr z?6@$CM(d+sY3&FB(<5C~?VFK|USNojwe&sdr0~?q#YpX7mPExcBFV}y=7Ll~K#N{I zOT9|3GwH++_QHI7LcqFmjfi9IV{JW>9}7_s|8Fe-3dVBn4`$U*0rsqd~Z>3aafg{V1EtB9(u zJ)P9PRH{DY*Xy%lqkjvpy&8fSk*J_`*HFA?5n6j;;bWv>Ux*qAsWyf8ud9g}wbR+I zJ_W>Lp7Ch&2y!s5XtBbG2UNb*`Icw0I<)G>XrvY8YJ#rel23tsn|@1RIYi-OLzq$= zBMBzHj^+U=-M_?G3-9PEmxb1Ah{oMuHz=wak}=a>J$shRDE;QcPU+E>EzGY(CpZX0 zI)Q>3AfqXp=Jw!LS={sQmD5a1kRHQquJ}7<4nwm*j^e9N3SD}`AomH9sKvm`)M9iLH-{QX!&*yEi=A<05yHSNR2;Uf1gfo1 z1!3?aONJ0zqq-DDPW5mQiPV*Q>Of0L3kodk3s5Q&$_*!$#6a6bDIZw!3OkN&(`R8a z&y4|r??eW9{sG*D=0yvfKgTXjvBYx{{w$l*mUIX$Ftz&~_j4NlR#{CgJ=;>ErS{jx z^)&yKvXejX<}IBQmTgMQ6-mh&Z@@d_hQ^SI1gtPEZFkSf&k|G`4xxfQQ+jmO&p_Mw&bQZc|+DFm7^U5Ls<^4*z3z zQ#?(60Z<0_MFXRyWhxMwkb8Acgfu8y;YlzgwUcr^RbV7&%raMQLR^{)6GDjfjsNCx^=5zW3!j;^L^cV%T|QkL&Cdn-2xZ8hCfv zDa41D-O_tcN+IC=>0+zE>bFmdDPf+vx_659%3oFsojqAqG}*ZEOR9ubt+eI@c$kEI z6AorhbvD3KeB~XxUB7MvaJ|bYB908Oph#sKD{fsgXv81Oqy`Njb4`fj5(weYkMV%URg47`3?LH87*|6y;U&BSP zz&PW9tttwjI8dz4H>!tPk5g)KpK^nJgI26(iJ3;d_Zb{6utz_|K{@JTcp9C_*5N5M z>iVik9aYQK_qKb3Ya7 z(fJ>>=ePTOW=eYOehuX8-xJ`|WIJ0g$MAo9y*+F>JEkK0KCtJ&nRC?;a)H6QXGETD ze2Xe@r<+j}cf8Jx0Le*Hhe^BJUMjCebwDYalteK@oL!PB%S^G7$kEUN2^ zBWm8gXi;kdF?g&@_(o^td&^1y_uPkFCBqUh12O#zcQ)a^qG+tVug7L1yp`y|FASUq zpJIc+AI5T!zuO85aJhY^lf}0zL@-yR&cRKQbjcv0Y2gNu1dXz>1u&_<-xj_{!N|LR z8>6pxf8`l%!Q%lG{W=t`$`-zVW=dG|>7+W}JQ9pxagbM-PQDJ0rg65C+sr>8k$VZl z7c*7yCezF$?_1OHRp$`0kUH|)xyDH32upejQ49w+ z$3w$J1Cr53Okh}0FNLri1=h+SB0k$lpUkm+E{%qF#Bg|{x9MmP{}Zq>yUfk;huTGH zH~}g|^%LRts)-w~FnM|2JkC+tT}*NA;jOkauA1}W8|h;gB*Y83Sks56Jf)w?Pq z{v^nu4fq5$cjroK3?IYy;HO>FzyM+bL{toWS46Hr8$mIJ%@s#(>Akv288Egw2b_<_S=Xq;@kAtdW#JGY-}&yQgt&}l-kCdXRh5^)3KcD zu_hu(dW<=P?`{iK&S6~^%~~;;z%RAe@sf(`E+bX#HA?VMctA!#2<11DL?MkMBI(3L ze{6i5`gwPcXct26VvqB0&o5A(xi(ItHEW4xQ9CMO!83LJ%pA28mt0&2`ceK&tJ zEFwBYVVZ^@Osx|P$p|fAx5>H=EIcnT1r2E@uevyTFmUR?IKPiNKk79w(1p9Sg|U~K zxhlm*z?Y*`T&lFRh?dFEks}FN7Z(w~s(M4{B}nZxr?|jQ;Yj_%1r3dppO&aa1R07! zmY0x2DYbM2zVPT4SpwC+ffLai!@mKEWe0)HJx59B?TIYzMtk59Ql*e~0Xfs= z;~2`Uzl+icz3CO(w>4+_I7KBfTUuju$H=uEY$M4en4xJsOodIFX*r90&cBY8+ae4Z zgNYd6CC^B}ZzII>En_XGifIj5q%+C3;SJ;jN}>j6Ea#Ni?OpwFX$wpGVhan!Y88M6 zC9*b8A*NRbfb{)9%v>Fzvo^Vlsy{f0w;4}0&iD(jg<5vi--BI6Q#4AvVCf*B%+uUS zKsMMn6S^*q8{6BHJT=gcx1bQ^*~Nmj+!Hs4j#gCUOhiFzVzMV~v#pv1pb+M&{AjRF zB`uN7>TwgZVJkD}C{#esWB-@aMMK@dJuEJ2YS#6{3#&-c>BqiIe+ed~#bb`%4bvGg zLZ2(?o=DNc4QR92w~Bx`qpgNa*)O@$%(Hj!ELdAHzzNAjYHiyzkQ>jHs7<(@qT{aD zKdNK>gt5{~)O#sBRZuR0ekT9Q$FQDKwMJwg9lvQ9UGcKekyYgRopM#5c%Mc!K;*~s zo{t?$MEddOWEBV1yNXS~%x_?Rk$KKKLQC(wg6X4g}z6KF*R!~&r z3gpIf+dWPdchRWNkr2Z8#>t#)qhEx;_YV-^o>i7Cr)_u{%>*&`z~BrZxD1E;*Fg17 zOlS%3v9e_hsg{CvkhCn>*-;opy>obczAs2i&{JASY^$BecsnodT4mvQatOoRXej%q5;Z8XXK$tQAzW*ys&6i@v>bMK!mBFr z9HplspddNs6Y~+ zE?2q9>jB&a`nMsxp$O3yy;q2*{`bQF7hCWDmCNV+3rw@g1w&3jeXchO8GkDMtiet? zHG_^e&cI3$1@g}tfUuSZx5(289rM)k;rB_?S(fz z?~ItNgwn2?d~2lp9|O&yG`8zw>Td%&02}~ZF-=;_v!RhLl?4AkJNkA&&wz>O6bV(4 z4_W6HApGJz7?5$9DOOdrIt5bH5k+1gI$HtTaI_udh|)GXibEC0!LuV0^}q{#s=06LGf+> zj_~;pBV3Oe1l_(zUZ#`n{8YAa4zPV4z~;36(1jbd?1>E2Gtj<&PtRTFUVk~D2SOy! z{Fk}JV1pEoi;a#qOakS)D}-nEACK=^bKaM<$D!Mx6T07-SvA3NBp~Lb z#iwP>N`Gl&SQya$EXpHQMqb|BLsrPN5etyxIS2-1B0S1ajhk3r_(TezUJlkLr-+27 ze5Ouol0WrjOk3W{X=$56*Sk!}}i^ehrH2uAbf zL%gxW>KGfYWg`}x0$R2gMhcF;V=WZn?13Y&`rs@lR`Q$Zz!0TPE98U|;-7|-=X!=| zeOOmO&|b{bTFzjEKoO(A{sYc%{hE~&IONq_Yp^NfCEvR}OMNR#JcD_LPk&u{nH@zW zkoRu)Fv8X#Ek|gzI(bZXU>a5hw_i-mNqp`?C23RRahOgGZJH%=!KVCK&(y;cfphg`KayZ+V*1bZk2~CvMbSX-AhRu2GwWhv=g^a>xH=Stx%J*|}jeBl6cf=5; zaUSpi4QX<7(K{x%?jDs_{w{0@& zSqhF?7bh21$39j)BbPOqqE3uM4PD8|_LN2gA5+@-sj1&F?Bww{Y(qhN%bG~46fFIa zKB-}%UJ!ZRH#q1dmKoqNH?>4F!JU-F9SM!3#LHMOZX<5*Wn|^4^={M|qILghK(Gx3wFpF)Lhg zn_~!jN21d?U_l|h9liM0(3J{#&TPj@JhFT*^S--;v__+ikgGBXP7A$qbFdb;9XL-1 zYWF^d;GmHB(HMD`*uinfjW<>mXU2_iJ}6KOK(r1dnQ^6-9M`$aokjVi2oswBc7&LMW`vphdl*LWEf~7@pGHVA_}=Q zap_vZGK~IO4re@69rwrl_ZXWP0UQ;yW>|Ez7SlN-AUUNFiW2r$S8~nyyJ16AwP>If ze-?3Z`=^#botO4As(Ze0#Lt7QMU1bv{gc^*lDkCxl|Y|PPMY*k8L$1jpX>XF@~%jX z9EuusSJFJ$9G_T~>y&?v5)w{3mnwg8;jx`>OC85hgiMrw>vmt&V+C~ly}^W(4tnkK zxDz|+dN3qYjj*z$r@bAe+F6olMkOGz^j?Nw|c$?i`1(V4cPFQw4@@+I-Ji_Lly9AHBW1yf4s z26<=^Pz;Jwo{GSYel!+smRP)hArcWR9p{9mya+v3gU9}tuxywUMi!`Jd?s3Lb#vXS z@xoG^gYI~j=A`C`ID|^F&dbH&NQ*1m_$aX;U>_nm>mO@>Ggj1(ov6GRp8;~=92rM1 zlZrnWFeEG7zh^2cTo02KR)2vhHusua=-7bvN-vxL@w7RP`N4>17YLT=8|`h2x;)MA=gMDatvd5_ zf&;!5kac5|~#F~kFxG-?8qBIW_E0jG5 zKn}<r$q{GKt%Q<;f9{uJ^R7quu4e=;$? zfp#{2eu^TbbnP#3626vURu^jS;+D$zzIX-mCf&#!Z4Oj|92nU;zvW~$HNP-mmuxfP zcF0l@Pi$xc7gcJ#Th&-$N9{W4Sqqy~-trICqQTO8N%mH4I#gr2Nhj*~vf=9*fhU@I zg1RZC6iCv?)EXEF%XTXa_jxk;u~*!;d2e*ckLNX51G*Gy6N9+7LJc;co2R6QIH+;r zReh~HxqfG%0*6Oh8;$QoIQ7{=olIz0k$F{B0yb0D(SlsCf^Pu!qWlA1T%=DtVn}Ho zD#8*brY5rq7e^6fT@GFPPn{ZblxR9UQzH$?K^Da&wm3kQgT)6{3TMEvTU~xT4mDR= zl{D{{HF0wv}`wLsxqsO6`VmTQJPeq+Pt8k?k>;2Td@7ZU<#W=v9%tWJc5O)he)ojZbkFO7!S`Jd)~*B@hP?t{kgnRTh;OSx-q3WOc6`bJfsw zC#k4a1YS+5yZpS~U7Si1WCtp!C#K$x-ILCZbjveTs{LX@o)DSja>X=?7JxV?b`Ph* zWoydIEEa@0Han&LD1o(!>dMPW-zBq!iWV*X^saC6IzLJm>bDsDj;HnLC{R{9r+fIe zOcR1>-Sf~hmOZV$rWxd}msll85pthQfsy$NK3r9z zGGq~1lVl+y(32YiV+aiuG1mw5B@lckIY*!&eGjL{B7blaf?XklsH!B|FePTKG46v- zC2}A$nQtBEba2F$lm}Ub$MZ{V$Rgk|Ec5Q#{9j-jGq zIu{v8qAaq&ZTQ+8I4d||;#@8~Zn)g{;(v6x`9wTlu+uZfxl$f{BLlgl7=f(}i9T#Q z0G8UuBiZIj$EYHFhmc<9xqn`up@{(01r`l^JR$>4@nGXoyb>8KkL)Wj1>!j4s$fk& zt(?vDhhjQhhHVvVPymVXK>shMvvcz?A>M#-?T1F1c`P)M{WNlIJN=l%Sr1Yv^>K_y z2Q2vJ8^rH?uLYH53uY)77(~R9${-vJxlgLU;q~!$GOM>Q7)Pmq#s%abB5!C{e-S(c zRPkj-*>4lQ!&6%_@^Z?VH2$?;uOPiav-kakJC1W5!mD4JVwjhkDG(Hwr7@R`<{vM} zA(R-p)0lm)Zur@lgwp?*b;&uVXLubYKBP&z0|)L~Z(>sd7?lSK6f`>C&7~U*N%TF& z+-*RqABugI?Et3KQ*1wh1TxWV7EZ_l_6tY=mSa6Nz<;2&lSk?zBO}9s84Xl$Kwf`+ zkWkUg1K}>$;I(0oNK6*W&m$D5gxF*_Gp^O~Qsv1JS{(x&V(@3o$q*)3z`mv+YD(AR zhwly$J?B+*+33czP2Z4L>}IlyPxST^@#ZXW?pX=ecvujIy~ECNg)R{rPp?62MTzUQ zUREXRGHIiHc^`dFmgp1f5ZTAumm8{<*Qy+}vD{BXS;M}>JbRX^qc?(xV^VZOVk6pg z93k8m&v`3*HN&^K(bVz#Go(npA&yz4Eaq(#e(3=kg`;De)Ih_{HxF{RNk0_$OSvG?dqp8(zU3VJD7!i-}EKLTky7;g2$ z)%W5ly@*qaaOj8zpoq(~Ibs&;_`=6by2D(V*^E%@pVNYUq}HF@%h`E7zYf$R4p1*x{fp>z8zqX&aotzBPOU`Bit(gmr-{f6F2 zq(}D95I>!b8-R25@coZ$>MOTTkP%cem$q4=psrhnHqjd@zVN?{cW)a zmr;J5i?vPQ?&D10gH@?~arosW_ES=hVkzLHqTZWCe2(1qeOlSkUFPU}?|rl`&^btJ zDy8?VP(|)yn7b1KlQj5NO>g zHtFn$j|QEw9$+0vkjc{08wb?kC>(Z&y#XkW%0Sk|y!17cPG>pJh8kg3v`1_c88lBz zOUrW0L>ceS6J&m+F_;={Qd(vdy_2CgUq-XElpG5>KPseFuicw9c2i^*=aypnS5?{utr1eC5pbrXK;y*cUo)K6g zt(=C^98N=1O*DC%SXQ1Dn9#Ft`?0WaP<>!^ z-VNzB_wLS1o-VhtBIP1xq7(f%-}7lZL*YYux&%Z@F+^uR{@(mzV$%)bpYCLc*APdI zhKDb-vsWt)_Wx{~0v+}v5&xwJTNAqLB`q9`n;w3y29*-(2aH=&9TNiLTW4!sYrqUg z!7z`Fzm=3ksv++N*7N*Jl9H~v1O;Dp?saZ1`*@311ky-GGIioO=ww&OD36T2dtsE<@oVmi*2r0z=kjqoC zGPT6K@@%BHzq4#3`3_TXPSGKigQ?scPc9G!#e5+ba(H+na&_`BfeBw)50nq0EC~33 zk)N_avAqASy(JlT6`(=``Nz2Fh_sYP%V>d%U(gV0M6g(S(o0oZbK(MZCClFNw?TEm zUOW-EP%b=j?OH@WI$Y}B{W&`Ylyz@oP(JWf_s9-)CI7Kq-jU@IZO)Iyng*KY3Fv4= zZ7B^2k2H?P5oL9COl~`cdB3K2{RIszzV&&Z#|SUXOj6kcWr2e1wglJ$`x{?SgF@d( zBxxfNbF+-{Pt#grb<4C&EYqx{stRecDJYOAWs3437o-f0^)+ju0#OB+V{0n}Hu|Yf zs_Drw2fG3DtA@RBi)*Yd&sRsFgU?UvH~rS#I6NXkT;RM#zYV}uF;(TB zouM1vMI2K1%(eZt^LHN)t5A*~-FYpMpmlfqJA;c87S2)7kuJKa-dj*}Dlmz2BCEbN zX^GxcAL|1VD{8z+OsEu?-y5oq&)}=g*AEh$Zw_u2F1p?Uo@7QX$;+B~Nm`Ui+igRP zP8#fsYaDL!ZZ-%PGy#Z>VZJJ8hXb7Y+Ac&UGL4TbBriY}#TrnY*lW1*V4O-%&ll#%=lelV&YCfWPdr7Z~^HH*LcQ-I|D*Q@#q zWuMFT9jFOhVEyy8HJ(vq1t4xIvec?)@`hTn@2jhFnws%f?M@smP-o2CNsE!+Uy5H9 zc4>}|;CU-p6QWZGUviG1gi+@u|N9!3a(>N6+qw1}XXMN|rpu6V)7BG#X@&w;n-q69 z-^E`WrQmb1-mpIopuPSqF3uuGmm#cR6cS*BQ)XcDyQ(WT8|^tGqdQW*m|N!1leffC5~jiD?I7y#ua=JA`1_C|PA*?+J1t#_HmIB|4bS5!Y{V$vLhC80 zv|7RlK7r`dJ&NAv#mgg8>lfegOEd<$9iy;NY5=V{M<)0{&H>iAt9Fgz>F(DFZ_b3B z2?g>oC13~S^-3BY505U5ULh8HH(b92!D28mGt(c)!?d7fYRooH5jXNE)p5SYHsk@? z@}4Hk0F|N_CG|ebmQ`6=WjJ6!sPFZ@_fe(AUc6kOTTf`|r}#5oU9r@ys48GA2-OGz zeD0(Ww7yK9&WsqNlgql=ai}w+7?rfCxRN z6LGM7YW7GZk~sm`#l&hjo{VVRAi0kkHenld;O*fZ_}UK_2BrP zzPuA&3atUOCyzEB{CX^)Ewx`mliF{_K%Gz^)n*AOTiI8Y@K{%QN_;t3f^Jn??wPn( z3E-VB&d+mc`_j1m6y6;sIK?ssYSg7E6dqNeqy@=rv302+j?#C!5eQ`T;fKYH=6fC2 zh?NK?S&axO+(FeV&6&dCd3A{b{qugBMUW&!DLdQ}ZFJz&o6?5wwgre}6pA*WiUVQy z$%Z>dUZQel5N5J4=`CxSR02rYm7yjD7U^r^#irG$hz4M-u1eu z&*XNgs8Z-sObDiDn6qmFwAyePPVy^eq7gRNP->EKF)ayH%arU7Vo;5cAjAms4-d}K z5mBltGOIR0*eFuCo1PyX#?8tpH#gsN>rIwfV0=@yd|S;yma2rE5L>fR1j3*}@>d!^ zqOut9>rQ&kj;e)iq8rMKKU_tt3Noa;Y&s*ZjlLFmVR?2R#^U$Z)yHu0ytrObDKPG0 zn+7D5bRA(K;Q?b29U8=?+-?KwIF-P1dr_lUOP&BxR<&7A3Q*V=&REeT4xZ#(AxA-x z&d<+Zi^VYvLdr!pXGRlsx{!yE86}wR2#-;T)^b1jteZe?Lm;C-fgrjOAOUDrf@XQ) zX}D$kbw$%wqpjw$g@>nuAMe7BTd}xvgcZ2aCrR>D-sA1-Z99Cm@7>j<1!Hz?!?aSIonxkvs(YDa$^4)0wx6I3tg z6ru=G9qvwvy1FM~5hb?X5179wy*?|Hh=>M)xR-KAIQAirhP{q*52$3XChLj>{V(W+ z2nX^@l$Svx2<(55C_oJe@Y|9zdhVZ=2O$_fCSVz&$9Oo76n_^tMeq%Ct(ZCz==J?8 zj7rLFip~$)_LOq`Pzp|agu?0^mnUEFR`SSB1ffg6E$FgJmvQ~ zA~*k8QTPEIiDmkQnA-%c#Cq_bH}Mmk4bT;!vR({ONQb z=)$j^r{yFX9Jd|85o-nGrw)_kj*1_1Jyvk5ZLAA#^3W@B)6DW zD9Un_uXc~Z&Vuuuk3Y)FxxyG`+!v%8kRJ1GaUx8WZZ0>@TRyiV!s7(V_=)%3-4}eD zSbdfgf8NI$8=HHcO_gl(mXM$FoqHHZwjj;QN~&2bBcPCCAo2Wq%u3`4{F)w|P57%{ zsF#Ht8*fPZRhQ2+?Ttc(34!EA{}}u(-KrUun3FIJ@zO#-fu(TYrXRf$@8F@96pm_4 zh0vxPt#nf$J^2hJ)R#NccGLI7DSCO^B%9tQa|8draT_CKky{h%;S;eYbuP0ixu56& zDG*S1H}z>vH$$FD>%hxlL!*HVr z5mV7hb~+kaB}T2;>75@Ed%9lS99N3Y%T?K?Zg;0P=@)DWOZtyPt-5z`dQDP8KR(If zvMbvuHV@VgALeeV{~J{}SmNQs$aP;EsN+!53~W&Hv&2OeN9@X#;3XWSXeS!oIo@AO zvOgMybv%M0Im7kZ~-Fu4@!5QAV=mAiqefFe675zpY z;eB1kyL8$LGN#oPrFUhKhCBrOvPD)QKtWhSp{X<8v2eRt4Rx!AycH2DxyNmRD?n4h z$8q}d^VovVx<9t%uQdKy=qW$lO!-4NkIGW^ow46MnssuajkeGC=@vpZc9jtE z(uR)8+&~fTopVXGBX^Wy)3^O&Y}n=yoU4NqQW%*)oL*LITcp$`u}6cs^S!5V@Z@}= zj#6Rz@Xj@#QnU$HOwFbhaK1g3YT=?-?i`j}GLE-ex|8qEh3CDq{|8ka0ZjO6wdy)F zj)-q%({6qrgXf40w7eYjycs~BhK`Exd19moQZ`$vd$|)$rh4MA6>mTDxD8mv7|53PebO*Q|WdD&Mn(rPVc51iR*9l`SK0>hEho zEvt6TY53K*pa|H+tw)mYX;1&`nWWJ;TgzYL$G4=PT8+|NtfrxggWbAxCQ)>MK0pc6 z>u(sUn%d~hO{Y}gjZb+#f83-U9VSr;I34jhsYzeML54b;49l@cVxmnTpDu0xUzMFx zaAraK?Zb&}J8x`EtT)NT#v~KlwlT47+cqY)ZQFM8&-b0Gb8gPXIs2wBcI~dN?ylau z_OsS+wRiFRVjOVk6m;?D(Gqcbd9SL?p*EpuKYuzL41QKE!<)~KX6q<+u(=ShDj&xs zpk?>BZOh)DpgMoS)Z>j3j;WsbM*OPYyxxHXH)st!Zq&V@ttmR>b>Cwgc#Tv^C~trM zRWtk!%aDko`+)F*?K3)OW2KjiHE~9t6=Br2lFv@pX4>+Ln-PxxE{=@HECXb)Bal|< zQ7>vP3-PziAGzP!H|r9RCcDJOmRF6JE$6TU5%*zpmK+KK{8{rvc*hp+t*-lF+)V&0 zJg)YsJT;>XT8iA)k(KPPNAue}sW8{Puf^z&Abs%n^YIklWzEoVZFsS68MGfb&^KYn z%1j*Wex+bzNBgiezEFTO&aiT!X!VElgomu_2MxED`;>>6_Atqs%X@EZJ;WhhyWwFCe4>I#KEK?{8L=^|Xd&{qZq@F-o2UA&H1) z#M6@xNl;`h_Y>f_L9q4d-U{VeE7i6_Ae6136a7pjK(m)V?)0$kRBH02zczwbl4v(a~cKe5#fSoD5 zdbY-@&q25JtHc&iitgg>&s8<5de6FAh2b$Ev$k|30og>(VPgu`a$pC*)ccw|A#`A#9$451626Tky zi%hTJS1>~gilj1b+xivSY;HSZyXMfT!M3I<8DhbGJar3@+fkI5Q;eA1!U>Z5dQuc; z82?=I1b}7|yR~iol{t|xYt7zXTGms)Cam%gK4e@PVpUKy5^poubmussIqLG&ejp5^ zJc)ko{$g|PYkd~mQO4ZZQQ-tnn{18pboXj2n>=yUFz++_Vv-U)(Q~_E3o8X3gw-&7 zysQ__=kxg>dCRN)?fEb7`&@y!J5_Dh>$kw9k!TW!#qzi$Bv$0m+mp0AErde%&$ywi zr!pKpHNB2eN5KM(x0b{rzs?n}xp~A7r&>IThjmHwdxOc7!EE+|oe2f?lvb78b}je? zyO|P%?Du>;2h}IN)L2}5WWF<-BtGswz>%ZH$tDKVr=19A)$}h%oOJ?GA^cXWy46lW zr@gXM1ftJ;JRfb&%M9-sguYOBX*FhdY>QhRuS(lT3pa4eL_+e$w%TKXX;^}rtpd-v z)2{P0_+7Z9pZqK7^uJ=xh=oPiOA*m)J1y%GP9MGvFBxe(Dr=|=ylANp^J519*bt2^ z23P$lERWd=Ob=0%MEQ6Q53QSo8rr_zYWOteme=6b^B?(bo61wuB$jLua1KO5aky|* z$$ZU#=AkT2oq0w0jg3vxG7B`GGWdjdt=G%_acVd?hE0-EEsr)N<{20k7(p^Qw?y5G z{rdc1KPIpUfFKuO&U3yXyA+$phntq2K0J z??%;fWomo5;$4-Ws+x2w?g=H>``|aLf|HJk3Y+ddf& zMl=jaCgo4i%4w7@t5tnFr>%$8%J@2{hl#iCf}nE@cWyrBMRG!8dzefWEj1_~8Wl4| z^h>p&BHh&zeC5n%j-yfqtli|L#Mlf95|sI12oO~a`7|U|$m;BcNCA`OU^NV;K59zo z!Qt_6-`@noQbr33!Z-35na{LGh(em$j*r`Nn*7?2*#Qx_R4jG_RKh|hut}p}+Bzbh zFv-c%FzMa2SV&Yjd?vXI%a)I9^BM1t@mD@FW1SAgCC9V1Ixe2CBy_u6z~?D}KR>OO zmFm&>Uv9R!;`Ul~Fy*u|rO-KQeY$6OQ6}U%nQf$z&fj8PdB1ktZ|5ZWQpBk-+SN+D zqstV&Gzb;6aQQ!nVhY(A6Y|t`P+DmOO`d&Lg7RJ0aSC5kSXiuU^N-o}OCnIkN;wE2 zx1S^x0X?ZzeYS+fqpktpX7C(VQR-tEWf-R6fwds`TMt(43O2f_naHs`@fX`9w^RfZ z)`e|%CGf($`NIG1Kquqy0_!oYy4Q~et{F@SiU#iFfvt!zvIM6KteB^DU=M`fLf z4%O!k#ATLF8_VTkt^PWlvzs-|#7fq5uI<1cI=Uz-~er-@3Ylf#XVjh;W|*2nV%OUmD6G6#4f z$&|nkIN|(9>#{hi~pufh_yF#oXaim%q2+5)|oGBIWKr?~PXbE=EgU z=&U=~wf&+D!2+TAe(d=ny(|5r{s!ObtOzxE8b!B8k)O1vfbut5{u*V@ zm`zcGwA>sX6!xvkP_Oc*LuGzRU3CkF@W&65+^tJx(E~YAewC9|UO(4u`&d}Eg;cdB zsqwkOW-{dlX>SpNT*Kf3v^eNW6S^JU+F4BXOa(pIyMUZhHj>Gg(xS_d$SSV|OGKv{ zd@`2t^i8m0Kjt%0j7^hfQuEedqCS8K**q5xGGuHR|K;IyS3*gguUil-C7D`cz&4=3 z-39H+M<;IB@~fA-&Rx~Tjl3Z>9!ipGI7CrWapgopDbbVMKqC4uSvo8yJdyV(rP6b0-X5Ej$Q?kn0fHiuA;j0Yam<>;dEc}1SY9DDrtTn zpFPOSp_p|q!hy&`Dpis#4ACbxBZ>;=0peMiCBi=y zblV(S$o1q;meA^mPg0GS84NQa&ccMUaLeqt7n@5E&bA843WmvSXM zq{fD!t+v&&=y;%S#j=94Z88&4-Yx?0&+EF8Lo`c0rOeGcKQCbsQZh}e`z=}bD)yJZ zg(s*xNz42gc>?=*y%{0W@}O0BMZH7~-$?EypxV}oD}(T$yy|TMoj~i~`}%;zhRmgO z{6J`4%2AMQy3x3;$I+)c3jkf|*LQ4fzwc5lBemsWKa)SD#g?(K8FK(ME1r~G{ovWG z1AF8LL2YkI?i@t~nP_EeC9h~|?GwyGrr42SM7`grP)mQJYl}+H0C)au^m%$5`Fe7X z;1Si*8A?OFg&@AKdq9m}v;+0qEe2bWZDWzo)KH(8sBFsPVqL3JmZ2^#D|yPyj;?D> z1Pegl4}VOdW*~=bkmMQsNA>E*l4iWP#a zw>>Nn7j}Ay8sYvk6@!ida9J}t14ORbe^MJ2`8#`fgDh?Q&EOjuKsoo7&RLoF3E~?l zdOYrez4tO{(Gn69foM)9wd9{f^`I1Ks~mmtvRbvLIjKXNu?*{9?Jpw|EmFRo_?`r> z5%%d!V^5uo{!{1PmY4?&&sI4ct?9u9c=U(bw(ikN9F2w&$Rn1&l5j+NOhE=dHAtH; zULDEqqsHL&(@+eALQAKP7)~VYt?9t&^kE+aXx{JGfS} zpYOw-#s`#D%L&Ok?SlkR|LPh{qe#lpQ94Y+#i;mAy2diY`YTAK z_AzuQDznG(EH}2zz*dqs#fdjhCf~Y8_*^enXY$8F-!c#mGqzeJNDr5^u zj)aAw3W>bVmYv`9EJ*-nVgD;AgVr@mGo$>;LsvRfng_e1i^B(W(c#*9>yuJET>$Qy z%6iERK;<|5YQ|9EsuG_eS`A109B|p##n~s0$^rKQ#a*zJi|~)nx2l@E>2uMKrA%8l zo;_(H1%Gl-2k$ZL%jD~bds=Sy&{CuOYI^D8Vhi4dGVzjgrl}vuo@E7N@ty9}g{0Y% zVj7qq>n@eKeF+hqj^Ck$<(uZzb4gYr{SyALArFQ#Ckg+So?^ixGsB5YyC98NKy9q- zJD|WHXSmaB<`6v4Tk=6xEE>QL`h_dU_FBeRK$&)fb`CO@@wZq7fqQt)9#PSt(H%q+ zsNP8owuw*D03xfWm+z069aPj!i@SsDG(mr077mP#fQk-lEAi`dSad%|&ahX(gv#qi zdcS`H9iL#V`TD2V_x5x`(}!2<{SgFl*%_GpHXkm!kk89Y9QkNHlYLTYO<_l_t3jVk z@{8Tw)W*Mw`|PdQ#6~wL{ZQ~>Dz&O9%_5@Nk<`*xmJZeh3MT>=l_RqvWZ!V{Fz5~b z>cwC=1&KqyHtdIMDCNtlXbUn+IH?y?L_M{6lSPMnw9J z?2$YSq11GXszXt<65BW$)b9kO=f3Q5bge{|zp?fe^$fjFjRC8a zd!oi}#`3>eG^}S+g)KK6Uj=HHQE7(wS+V-t1!f4I6pL-#hJbg1X{N{hdGap*R`VyP@>@5 zq>zgSoFTIbjlA*tbhFMi*o>-r7B5ZmP7&Zll=_lK8ieP0Kprh+9p7|{Oi%uPM-0#V zWVi~iz_;**{TBQMkpYp^53WZ%y~D+hzK5U>Tl%eQo&?pp_(sdmHbn$Hhh;Js_ti)y zg)gm4Fz9?$ImA_Y{)=Z!U$Kp;1>lkvI`%o|RN^qY$R+(HqJ^SHMV3`E;NxumPe!fb zyU$Ymm{<9fcjJPvVU%*If%R0K;F?f|XmovU_ybclEO$r=ff76+Mq$AZ#0&y)Mq{T1 zlgK`~%zsM4hzUXt+cALbW4TGZbkx#=6KTfvTdZ9CeemM1Hu6!RbXsqc)m9d=!QuKM z;$s1#Gb{mT>d0HZ3Zt%8hbr%2cnwmtz|N+#5T)4ePg#T@H=KHE_NxPP&W%8TYgci| zIo7kP-<)BN1~7 zq}&k+A=zFYQP)Y9R>dOCZXI%WC+8lyrxcD5`=TvAp6=#`xnHZWLGF`bE=U|JF!6q) zbXCEXk9C6<`^c4sh9znt)G2R+laD|$5jCx^;E_%*Y2lfFg+H}s)g$mScs!(uS3%94 z++j3@?TL^a;UCfEIBm?iS3Y>A8T<*va;(%8VK?jl9%080P(5u=3eYo;v}%dZ6C)Bv zr>bxzfx*}n53)Y14gE$h0s$c~mH-MVE5K|U@(NEJL%D^@=rsR%N4>iL5r5YJ@Q;## z=6;l(4lQn{xK+lNUKRg0&N`j!256k-VS~08=h7>sl+tN2-6lhaZl3EuVt37;e6UEgWJg<zyM&4r<*N$mTJT-1T= za;MkXBz_^U?sQDaa7hSCE+J|R+$^e+%Ph%ipKW_v($6d&-S_r2p`|aQKR@bfMp%pC zk1bVY;376#ZmO6EA+t|vn%_v_Eg6{)r7jMgFr4{=X>52wm6evK3w0#?_`2}m$eCGPel*+*LDxiqhc~+r@j|=XL*h^UX zP6ox|>tn{kp6*rKxFY!C&fKxX()!9oWT%?ytiCGK(*n{`RUfN4de8K+PoJeO$Jq@cv8#O!i@iOOx$?)aTc@qCKi0bEL{4MW7rAe-XR3(IDYwUj@F9j!r`7m3Q6AxbJ%T|p&kvd&7 z&ojKJ0@+`YO<$*Fq+=UivLR4hTR-l9yJ5akG>PfKWeT!ECy6c;zmBxCa+lg3I}va; zZQVsEL50^$X-8np=q(I-xkS>`QZ4^Rzoa>(4S@UyeJUu1!I^XMI7al5)k(~su;_!) z4bV6h5h`-onI*TWn6)Q-c-@s)262;MN$33Esi+3s+h+zQl zIKO$wj1k6#Jp)tM|2?4HGjvoNsNJ&S4TYIf_9>O=W=uQQQQuD{BgH0fl`ot0T%FLTPp<|>qnvzk_H zf7<4~{A2JgMyZl|Jp2+#1J^Mh2Bd_oz%{IR7l9%*U?crJiKjo5LMPu_s&L;+e^rhS zcS~hF4rue<7AVJg{cFt}z)L6qm;pZTHOM*zW%jF$h3=obG;#&-GSh>db4S}plXOP9 zsa>9PRNvH_%R#;B!)5M(yPz1w_qiGp->GS=EY4X=^xf>9FyfucNi*Vo%t2#7a<Bu84g5Gy~*`?NKbBB zU-3&cGT0&_aMC8T@`O7c@_Z{Oo-7&!$Lujfeh@a4 z%btqS#bN$+|3@^Jyfprd@A}aiW#g6pSzTaCdU3j*FC{Ib!9W2bT3nUjM6?_2_Os;) z9`BbT_NWw6W?|n9QFS3DK!iEqwOk<39`U#@r7HZ?KyleZwr>D#S)?4RixLnHl67D3 z)$yk;3|qJf4dDS3Vc<8i&w82f4rI+)RmqTIqR5K?n2mSI+^Dwq+hh+5_@iDup@EV6 z0aUzoZQ6*-7_G{>Xo@;1AQv{C07LuRDXH41KYS$|LWuNz*ZY44Rnt7@Kuxc+*OI* z+e2ce!CIBMpe{sxGD|0IpdghEDx>?)g`=5VgGW42jcuLsnvJR0pT~I56 zx~IkBJ zf2Z~vYCkJo!rfgOW2EarIdm&1IaYB8oD28-44a2^DiV2-j^!|QXxhkV%p2S%T~=_k)tC=sCUMo_jRjh?&MzD8ndye9&6l8nyT+8)q*ey4LK-6*)CJ(&-fBEa7VYqdBX zV<^7h&Kimg;fG5->-jFmau4wxINuQdTR}8^AZ`xhT@PVI-}zw@0Q@gX?Y)4wdhpuA z!dzx-M*RT=!4~Vm=?5}WBzDWOkSeSls7{(-Xhl zw9$p2U{mIFPt76<8g|pUzbTJ|SFDwQS7)vddK5vOgxXSflVT=}5z_bDmYRoEIOe6a zdStN^*GLB}H^f9YioxG308fm&A)VLN-WBk#!9cr?XgK=Rb4-D-^9&40S5SyXM)j2F zboraY_!vB5Wf*OdS*WhmPsoSbo|#1af2@jM>&|AO4$Qw+Fj-^20SLWuv=& zCAK}@&rV0r!nvO_zA1P(9pAt!L@_XKRu9=W4DXmHQkx89V7A2Dh^Tp04=C#YZLh%x z{W*z*r4G@)3fbymaMKqjOPp|7YS|#3(_yu7u+jR{={ESA&<6Opg=D zy(gwj`j}S8*-+9B;0D1?6x233SS0S=h~h0+Cg!!U(EoM<{XaU#{WyTzdRh!9@6NmL z{8frt8w&_9c(-fFHR4$+NH*P19W^3{G^b?(ZCX#$J1DbXwFjHdECD2My%U9vNLsh@ z{@)lbOt6XbaNL8hWkn+K&KWAqP;08uqfJlwvH}J&GV#ZL#NOMV(1brQFtE_E0YgpL z2deA8ZQHYc5BGkwRb2)W)N82e@KtUz%$4(vXByRY$u6G+c3xx%;+2;4_!YPPB0vz# zQ}FUQrkq+q>(N5Ice*rWlJxz&@9KSi{Dn1e$81wfa#?d=oB+#bxGG7gFg}C#t&~9y z5@dbL%d(B{Kfa<(7wl$e zaztii9dE@sAGseDML9bCnqtoWfXc(^!DE7Tq}F>gr>D+Kfa*TxVF00T67WbfR!%_o zgT+fDS9C~{urVMdghF^bR?t^-s}}77PqUY84VnQl?0#1c(- znUc3kni#}gm>Qh23PIH%d7$T%opCGqRZc9o;Bt1EJ{+6pbCf*HdJwr(_wuTa|N3Us zm?ZurMT!26muf zhsJNs`S~44bpeQUG(m2qgyfEEW}+@rOJed|U0WU}cJ&aCe*O=R;F?C5mYDY%V*`_#c&%uFaCIcjgmj4lKtkqibY>mP-XoMeCK|EK4umx7v@( zqL${Jj~Z4JYA!e%1=~IGBJH&)C6eA;u2Bd2#<}FN*b&?Txn*LB-g}qP>u&a`bLcL~ z@~NH0zz88@wuI7!;wx1`>x+$D#lpAk4w!dOKXSWs9KRGw2r2;YGpWKqLyV%Us|T1ODLio%>GeD&sk>G_tRyi26q{yIwcc#(sD>J>4c4aFzTYSqYx{F*1{l7cZK> zRxbfikq1S-G&-y84&x&HKj4dhe1iYN!t4pi$!MVZbTCGTFS9nUF|EZ{&_NWX?L{YL z)FUb-b$LH}#l;w>dAMS$NJz3>>U4NL`m!lelOg4ty!#NUPtC-2j$r((+vP9;woc%- zZk6RWjLWI4C0Z9+#m`)<*0YZI$23=0>fBG5rR?HzZZ;$PS!{CSIa6u`o+rd(BZhVk zI(+LcVc`UD5H?4(e4Ut^6`mCFZL=P#(K%{bIL(;5@ULw@`3^3aJBv;m^Jvh95RGv8 zo`wp)PEUG9vq;DW2Z2|aU#qZpDp4GHJ=wt2r|8a(He@gR{36+wFn>$dtM}a{D_m!? zvi%XzuD)os4ClMm70B*haNi)!MB{Su^^WedLmYDENYTEWnqRy}zuz_=c%%uqj>6}c z#2pWQZ8CZeKabc|7kIJL>+uZ1)#DnHfTnguX*VRd@A-~Qq7=jJj+z4gi?&?F0UZPP z+GGF?EY_~qQTUzHH}nRa&Gp{z03k_Pb-c!PE2eS;+@o0$G1-+#*tAf}p1(Fp2;k_| zr+eZX)y9IBQ>UNE^uwRy>lmE?Xc9tVAtF~CrQ@S!Mp$kFDT%H!4R~Z&PXGq-SshAf zgmUKx=3D7S&Phz>Zutr#6U8EJ#4cAvV7#WI9=g*r!iur%*XulR{{oH7vZpvs0A6Tb z0d;cS$5uRB#lrD6Yctyr{S^%S)Sc8HhNiE(`ZL;uq<9&)$=Wtlfa8vhtvgT>y(}{5 zaAp%D`q}1$={=uX+Cx5Y4=)Li^j{};64LH4g?YehlE&Z&R39%Q~mxkkvnH1=6uv{TFNN}+1)X=i#T z`(5ZP;N6P|iRe*}LGS69n) z^Ya0#tZZ|t^G0^_;;J0ioQYHk!Rx*L;EF*T-e>O6J44?k5Z|n>~Y#D`B*1!7nf#JG_&?} zT^%DIb-6>ENX90q&=2^}*G^NG>@@4EH~X6yJ+fe=tTrm04b9A0|2!KrmFn@X`@h%Uk*WSue}~Ikpy~dZw&o!>lV>jjF0{Li zePH8<&GlbKR}_dvM0n2zb#E&EDosTn|77N9(eJ8d$AtFyIVuoYmS4;US~sAUY!^$t zkb7@>WOh!;PhVg5QQ;57FcXM7LCU$7W0t6o#>B^lw7-Ml0$E%HFXM_tEVJ}@%h5kGmr zlQUMTJY9VyVmy?G{kSC7+Dm*Y*Qtj$D3qJ_R&A*Yko+^xQmn7RS<7*>d ztiZQRgj-@P&ST~BdMU*84o%}#??U5Q=xA@In$DCz6uA{288kHHQ?@==Om)O&&Du2U z65O0#DvtSV#MfF#%dn__J=}c5cmk)6h!~_Nc#`GfcB&n^>9We6clwV=YFffR-Xec= z9pM;O?ScYW@?x06<7nT=+HceliLQ`n>u`Vs(M79$ z2d(mq?buc!k0sq2SHukj0D~?TcdTkp>6*bXr>HKxWg|3+3#@~ z5G@e-T7>654X(&|zm_4jZ@BPB%NZQM>XjA-vHc=_v)T0{Kxkw$hCJx4Fhmv}t11@;d3jpHVNDG1-^aCS2Am7tQjygA+EiLHaYn@xdt?^JxwX3L?J@r(e zXLD+$Vy);9tjDc_c0pv8W5d=i(zyT%9Ns)pY)=o#DWS7-Zw@4eCjNU+Py%?1V;i6) z>GM&xA0mJAs3Eq3#sRh>ZtV5g`{fA#V8VykE{CvSTS>k@1FS+p3PqNAvmYHv(@xVU z7i4G4593yg+u_gH1KT`6Ah~`CyDM4_XV$q3Mm^i{o49XEa61E=YtMgDrz;G=0Nt=B zX|MhGMmNJ;BI*-L_Hbz|n$~&&m$g;QgtFfHO*F(JxG<2GaM_DLmQOL-D=TNADFvu!7fzsjW3*Ujjn8ms=) zcHDk7yU;UPX_-9x69`lhK`>#%Ly8>*w)Df5@)+T0O%Dgq;i{x^BhX8sHOkZ%Mm81A zEt*L+8kuXDDX^l-TyTdfQ&cuISmv4^1LwG8nq&v0mI}&$xdvibqGHwD?CoMbUY`AV z)7CLCuq{dZg6(m8k9OeK$^LpjdOwO;2Q9#gFU@8q^-=$YDMC;{ketQ4bxU*Az_vW2hNsIM2yD5nl{^loiB=n`n0ilqtP3^5fl?Kg^9 z(zny%O!g^d*RDTSHich-@Ah#fmdI#hxa6Qvv4?bXD+w6vtJYcGYGVHDMT!#`qsXG) zyGAk03e#YD0!y;($Q-046i>T_bs&q@WN;0Itj-V7-<2V$)fqwHOaVKwxxb-T>KTlC zwmrejdJ2k{9<0ZjwdK7}i1k$_K7=}<@yD9Y(`*NK?|h{Q7yfm^RL~JB#HGk98EpRf z1WB}8OQ}c2h?XDV3A!(e(CKx5tV2LE6Y96+?QJ(YVu1%R0ayI%-!{Xb^O)aOmj&v4 zWn$+qVcifVj*Gy*?_})rD6v2EY zVWWE0!TpZ<%{_xjfz`~R((I8v15S^RbNITnHe=E^@yhiCzB^Rg$BDpHY<)Mknd;dQ z1LO0Vr%c|rKx(N=;jW^Tz@p^M50~!953aXaQ0BCZWR=Rb6u&6QT$E(2)ci;7AcE|! zsLim|-C4j2RmacYvPy}&gn5F1J!Mp^cGpK3Rzh`6hEpGyWfC}O5U{Zz!MaeIcUX-j zTt}JAEJr6Ut>RK5mJ9w}V>xh%{jf|pn>%r9Jl0Jqj7q$4PI8zM)p$4x8*T}(28q7WrV1VW-Tx9^GZB=;o@gZNEi8D)U6 zrl0a<AtDlj0#p#mv80q5!Myz&jy1=N6)wN}|1U{Q;R zO)ZWA>@)I%@zZFpm370U8m&bya>V|L?`&LWQL;v%;%onvg0M*7)xW3M zS4hw_ugQGn`k+-lM+$;`2_U4!eqp>2^Tj_(f(s{F3)A&s=}R2+G4^Tcu)wG`dq!*S z>A@#UI4N-lou1f~ePbH<{%-3rdQ5NKGHQuuRZ~DQay01h17YIM zdLAVI;nWHjoV$2*_b{**FYRO!zdABEodY?|3_c;A9^=U|_C90-Y!tSv^jl`Di z`5yUZ8Lgtovj0GjwAdW-OX?k>wN$(ei%~Sb#8+Suc!N|GdK^Idp92UU^zv;uPL1S9 zcb$cm?nV7v~PG z=V_=@7%L2JYZnDz^xm~nz@q2JSgX|4*Qu6W19dJ;Itp_pXF90-Hhd3_6%kT$q3sf# zd{VjGTGHfk84_*S^CbI$cw_X!IbIPH=Q|WwY}3N?T0&)eiR1YIwdL8+?!z{MLP<6m zf+zBErT!Z$>|huj;XCdr1Q@y*zKi}C!CfKLWOW#~D^^7s4oneE>ewMU(98e5)R#Qu z-qEl`Cyx@onL$y}04KWi?SHvGAW23Jz4_#9drSQg-E5_L6cnbTw$Bjd6pa^FxSxy% zJ?kL*?Y}65`JcC^ILHOSaI)4g0WYGB-rOt%8p;TD9P9bYX^Lgwd8E05VcGX+EPuZe zCH96|r?nu3@0{K?|nrGYDh=fFkV&uSq{pUZKyi9~qip4_a#s}J`PUCkO|skg48 zw7ltl;II6i^8oOT&czo)!=OP=RBI=KPr=qU4cvB=Ff;NLKIG$6F`n4>Bun!(lhQ&C zND=;_1BdE5HKQ9dVyN%aFPj!3X$I(3WvjkB$oqB(HDTF+eRJ63;p5;PdJypQdv!q| ztf3$R;k=qfvK_XD_*`;LjrDV|&Xq1fp%8pQh_45LAkxZ+{AyCnVVF1f_#Tu{u!7{o zAm4pALxR;zC#OfRnAXZ4*&ACn^{i8Ylzu<+pPT<*O$' + s + ''; +} + +var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow']; +var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']); + +colors.mode = 'console'; +assert.equal(s.bold, '\x1B[1m' + s + '\x1B[22m'); +assert.equal(s.italic, '\x1B[3m' + s + '\x1B[23m'); +assert.equal(s.underline, '\x1B[4m' + s + '\x1B[24m'); +assert.equal(s.strikethrough, '\x1B[9m' + s + '\x1B[29m'); +assert.equal(s.inverse, '\x1B[7m' + s + '\x1B[27m'); + +assert.ok(s.rainbow); + +aE(s, 'white', 37); +aE(s, 'grey', 90); +aE(s, 'black', 30); +aE(s, 'blue', 34); +aE(s, 'cyan', 36); +aE(s, 'green', 32); +aE(s, 'magenta', 35); +aE(s, 'red', 31); +aE(s, 'yellow', 33); + +assert.equal(s, 'string'); + +colors.setTheme({error:'red'}); + +assert.equal(typeof("astring".red),'string'); +assert.equal(typeof("astring".error),'string'); + diff --git a/node_modules/colors/tests/safe-test.js b/node_modules/colors/tests/safe-test.js new file mode 100644 index 0000000..daad4f9 --- /dev/null +++ b/node_modules/colors/tests/safe-test.js @@ -0,0 +1,45 @@ +var assert = require('assert'), + colors = require('../safe'); + +var s = 'string'; + +function a(s, code) { + return '\x1B[' + code.toString() + 'm' + s + '\x1B[39m'; +} + +function aE(s, color, code) { + assert.equal(colors[color](s), a(s, code)); + assert.equal(colors.strip(s), s); +} + +function h(s, color) { + return '' + s + ''; +} + +var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow']; +var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']); + +colors.mode = 'console'; +assert.equal(colors.bold(s), '\x1B[1m' + s + '\x1B[22m'); +assert.equal(colors.italic(s), '\x1B[3m' + s + '\x1B[23m'); +assert.equal(colors.underline(s), '\x1B[4m' + s + '\x1B[24m'); +assert.equal(colors.strikethrough(s), '\x1B[9m' + s + '\x1B[29m'); +assert.equal(colors.inverse(s), '\x1B[7m' + s + '\x1B[27m'); + +assert.ok(colors.rainbow); + +aE(s, 'white', 37); +aE(s, 'grey', 90); +aE(s, 'black', 30); +aE(s, 'blue', 34); +aE(s, 'cyan', 36); +aE(s, 'green', 32); +aE(s, 'magenta', 35); +aE(s, 'red', 31); +aE(s, 'yellow', 33); + +assert.equal(s, 'string'); +colors.setTheme({error:'red'}); + +assert.equal(typeof(colors.red("astring")), 'string'); +assert.equal(typeof(colors.error("astring")), 'string'); \ No newline at end of file diff --git a/node_modules/colors/themes/generic-logging.js b/node_modules/colors/themes/generic-logging.js new file mode 100644 index 0000000..571972c --- /dev/null +++ b/node_modules/colors/themes/generic-logging.js @@ -0,0 +1,12 @@ +module['exports'] = { + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}; \ No newline at end of file diff --git a/node_modules/cycle/README.md b/node_modules/cycle/README.md new file mode 100644 index 0000000..de9a06d --- /dev/null +++ b/node_modules/cycle/README.md @@ -0,0 +1,49 @@ +Fork of https://github.com/douglascrockford/JSON-js, maintained in npm as `cycle`. + +# Contributors + +* Douglas Crockford +* Nuno Job +* Justin Warkentin + +# JSON in JavaScript + +Douglas Crockford +douglas@crockford.com + +2010-11-18 + + +JSON is a light-weight, language independent, data interchange format. +See http://www.JSON.org/ + +The files in this collection implement JSON encoders/decoders in JavaScript. + +JSON became a built-in feature of JavaScript when the ECMAScript Programming +Language Standard - Fifth Edition was adopted by the ECMA General Assembly +in December 2009. Most of the files in this collection are for applications +that are expected to run in obsolete web browsers. For most purposes, json2.js +is the best choice. + + +json2.js: This file creates a JSON property in the global object, if there +isn't already one, setting its value to an object containing a stringify +method and a parse method. The parse method uses the eval method to do the +parsing, guarding it with several regular expressions to defend against +accidental code execution hazards. On current browsers, this file does nothing, +prefering the built-in JSON object. + +json.js: This file does everything that json2.js does. It also adds a +toJSONString method and a parseJSON method to Object.prototype. Use of this +file is not recommended. + +json_parse.js: This file contains an alternative JSON parse function that +uses recursive descent instead of eval. + +json_parse_state.js: This files contains an alternative JSON parse function that +uses a state machine instead of eval. + +cycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle, +which make it possible to encode cyclical structures and dags in JSON, and to +then recover them. JSONPath is used to represent the links. +http://GOESSNER.net/articles/JsonPath/ diff --git a/node_modules/cycle/cycle.js b/node_modules/cycle/cycle.js new file mode 100644 index 0000000..2e776ad --- /dev/null +++ b/node_modules/cycle/cycle.js @@ -0,0 +1,170 @@ +/* + cycle.js + 2013-02-19 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. +*/ + +/*jslint evil: true, regexp: true */ + +/*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push, + retrocycle, stringify, test, toString +*/ + +var cycle = exports; + +cycle.decycle = function decycle(object) { + 'use strict'; + +// Make a deep copy of an object or array, assuring that there is at most +// one instance of each object or array in the resulting structure. The +// duplicate references (which might be forming cycles) are replaced with +// an object of the form +// {$ref: PATH} +// where the PATH is a JSONPath string that locates the first occurance. +// So, +// var a = []; +// a[0] = a; +// return JSON.stringify(JSON.decycle(a)); +// produces the string '[{"$ref":"$"}]'. + +// JSONPath is used to locate the unique object. $ indicates the top level of +// the object or array. [NUMBER] or [STRING] indicates a child member or +// property. + + var objects = [], // Keep a reference to each unique object or array + paths = []; // Keep the path to each unique object or array + + return (function derez(value, path) { + +// The derez recurses through the object, producing the deep copy. + + var i, // The loop counter + name, // Property name + nu; // The new object or array + +// typeof null === 'object', so go on if this value is really an object but not +// one of the weird builtin objects. + + if (typeof value === 'object' && value !== null && + !(value instanceof Boolean) && + !(value instanceof Date) && + !(value instanceof Number) && + !(value instanceof RegExp) && + !(value instanceof String)) { + +// If the value is an object or array, look to see if we have already +// encountered it. If so, return a $ref/path object. This is a hard way, +// linear search that will get slower as the number of unique objects grows. + + for (i = 0; i < objects.length; i += 1) { + if (objects[i] === value) { + return {$ref: paths[i]}; + } + } + +// Otherwise, accumulate the unique value and its path. + + objects.push(value); + paths.push(path); + +// If it is an array, replicate the array. + + if (Object.prototype.toString.apply(value) === '[object Array]') { + nu = []; + for (i = 0; i < value.length; i += 1) { + nu[i] = derez(value[i], path + '[' + i + ']'); + } + } else { + +// If it is an object, replicate the object. + + nu = {}; + for (name in value) { + if (Object.prototype.hasOwnProperty.call(value, name)) { + nu[name] = derez(value[name], + path + '[' + JSON.stringify(name) + ']'); + } + } + } + return nu; + } + return value; + }(object, '$')); +}; + + +cycle.retrocycle = function retrocycle($) { + 'use strict'; + +// Restore an object that was reduced by decycle. Members whose values are +// objects of the form +// {$ref: PATH} +// are replaced with references to the value found by the PATH. This will +// restore cycles. The object will be mutated. + +// The eval function is used to locate the values described by a PATH. The +// root object is kept in a $ variable. A regular expression is used to +// assure that the PATH is extremely well formed. The regexp contains nested +// * quantifiers. That has been known to have extremely bad performance +// problems on some browsers for very long strings. A PATH is expected to be +// reasonably short. A PATH is allowed to belong to a very restricted subset of +// Goessner's JSONPath. + +// So, +// var s = '[{"$ref":"$"}]'; +// return JSON.retrocycle(JSON.parse(s)); +// produces an array containing a single element which is the array itself. + + var px = + /^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/; + + (function rez(value) { + +// The rez function walks recursively through the object looking for $ref +// properties. When it finds one that has a value that is a path, then it +// replaces the $ref object with a reference to the value that is found by +// the path. + + var i, item, name, path; + + if (value && typeof value === 'object') { + if (Object.prototype.toString.apply(value) === '[object Array]') { + for (i = 0; i < value.length; i += 1) { + item = value[i]; + if (item && typeof item === 'object') { + path = item.$ref; + if (typeof path === 'string' && px.test(path)) { + value[i] = eval(path); + } else { + rez(item); + } + } + } + } else { + for (name in value) { + if (typeof value[name] === 'object') { + item = value[name]; + if (item) { + path = item.$ref; + if (typeof path === 'string' && px.test(path)) { + value[name] = eval(path); + } else { + rez(item); + } + } + } + } + } + } + }($)); + return $; +}; diff --git a/node_modules/cycle/package.json b/node_modules/cycle/package.json new file mode 100644 index 0000000..6750f45 --- /dev/null +++ b/node_modules/cycle/package.json @@ -0,0 +1,73 @@ +{ + "_args": [ + [ + "cycle@1.0.x", + "/Users/akira/src/biomedjs/node_modules/winston" + ] + ], + "_from": "cycle@>=1.0.0 <1.1.0", + "_id": "cycle@1.0.3", + "_inCache": true, + "_installable": true, + "_location": "/cycle", + "_npmUser": { + "email": "nunojobpinto@gmail.com", + "name": "dscape" + }, + "_npmVersion": "1.2.32", + "_phantomChildren": {}, + "_requested": { + "name": "cycle", + "raw": "cycle@1.0.x", + "rawSpec": "1.0.x", + "scope": null, + "spec": ">=1.0.0 <1.1.0", + "type": "range" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "_shasum": "21e80b2be8580f98b468f379430662b046c34ad2", + "_shrinkwrap": null, + "_spec": "cycle@1.0.x", + "_where": "/Users/akira/src/biomedjs/node_modules/winston", + "author": "", + "bugs": { + "url": "http://github.com/douglascrockford/JSON-js/issues" + }, + "dependencies": {}, + "description": "decycle your json", + "devDependencies": {}, + "directories": {}, + "dist": { + "shasum": "21e80b2be8580f98b468f379430662b046c34ad2", + "tarball": "http://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz" + }, + "engines": { + "node": ">=0.4.0" + }, + "homepage": "https://github.com/douglascrockford/JSON-js", + "keywords": [ + "cycle", + "json", + "parse", + "stringify" + ], + "main": "./cycle.js", + "maintainers": [ + { + "name": "dscape", + "email": "nunojobpinto@gmail.com" + } + ], + "name": "cycle", + "optionalDependencies": {}, + "readme": "Fork of https://github.com/douglascrockford/JSON-js, maintained in npm as `cycle`.\n\n# Contributors\n\n* Douglas Crockford\n* Nuno Job\n* Justin Warkentin\n\n# JSON in JavaScript\n\nDouglas Crockford\ndouglas@crockford.com\n\n2010-11-18\n\n\nJSON is a light-weight, language independent, data interchange format.\nSee http://www.JSON.org/\n\nThe files in this collection implement JSON encoders/decoders in JavaScript.\n\nJSON became a built-in feature of JavaScript when the ECMAScript Programming\nLanguage Standard - Fifth Edition was adopted by the ECMA General Assembly\nin December 2009. Most of the files in this collection are for applications\nthat are expected to run in obsolete web browsers. For most purposes, json2.js\nis the best choice.\n\n\njson2.js: This file creates a JSON property in the global object, if there\nisn't already one, setting its value to an object containing a stringify\nmethod and a parse method. The parse method uses the eval method to do the\nparsing, guarding it with several regular expressions to defend against\naccidental code execution hazards. On current browsers, this file does nothing,\nprefering the built-in JSON object.\n\njson.js: This file does everything that json2.js does. It also adds a\ntoJSONString method and a parseJSON method to Object.prototype. Use of this\nfile is not recommended.\n\njson_parse.js: This file contains an alternative JSON parse function that\nuses recursive descent instead of eval.\n\njson_parse_state.js: This files contains an alternative JSON parse function that\nuses a state machine instead of eval.\n\ncycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle,\nwhich make it possible to encode cyclical structures and dags in JSON, and to\nthen recover them. JSONPath is used to represent the links.\nhttp://GOESSNER.net/articles/JsonPath/\n", + "readmeFilename": "README.md", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/dscape/cycle.git" + }, + "version": "1.0.3" +} diff --git a/node_modules/express-validator/.editorconfig b/node_modules/express-validator/.editorconfig new file mode 100644 index 0000000..fc236eb --- /dev/null +++ b/node_modules/express-validator/.editorconfig @@ -0,0 +1,11 @@ +# This file is for unifying the coding style for different editors and IDEs. +# More information at http://EditorConfig.org + +# No .editorconfig files above the root directory +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true \ No newline at end of file diff --git a/node_modules/express-validator/.jscsrc b/node_modules/express-validator/.jscsrc new file mode 100644 index 0000000..71dafbb --- /dev/null +++ b/node_modules/express-validator/.jscsrc @@ -0,0 +1,56 @@ +{ + "excludeFiles": ["node_modules/**"], + "disallowEmptyBlocks": true, + "disallowKeywordsOnNewLine": ["else"], + "disallowKeywords": ["with"], + "disallowMixedSpacesAndTabs": true, + "disallowNewlineBeforeBlockStatements": true, + "disallowSpaceAfterObjectKeys": true, + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "disallowSpaceBeforeBinaryOperators": [","], + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "disallowSpacesInAnonymousFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowSpacesInCallExpression": true, + "disallowSpacesInFunctionDeclaration": { + "beforeOpeningRoundBrace": true + }, + "disallowSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true + }, + "disallowTrailingComma": true, + "disallowTrailingWhitespace": true, + "requireCommaBeforeLineBreak": true, + "requireCurlyBraces": [ + "if", + "else", + "for", + "while", + "do", + "try", + "catch" + ], + "requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"], + "requireSpaceBeforeKeywords": [ + "else", + "while", + "catch" + ], + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"], + "requireSpaceBeforeObjectValues": true, + "requireSpaceBetweenArguments": true, + "requireSpacesInConditionalExpression": { + "afterTest": true, + "beforeConsequent": true, + "afterConsequent": true, + "beforeAlternate": true + }, + "requireSpacesInForStatement": true, + "requireSpacesInFunction": { + "beforeOpeningCurlyBrace": true + }, + "requireSpacesInsideObjectBrackets": "all", + "validateParameterSeparator": ", " +} \ No newline at end of file diff --git a/node_modules/express-validator/.jshintrc b/node_modules/express-validator/.jshintrc new file mode 100644 index 0000000..d67238e --- /dev/null +++ b/node_modules/express-validator/.jshintrc @@ -0,0 +1,18 @@ +{ + "regexdash": true, + "browser": true, + "trailing": true, + "sub": true, + "curly": true, + "eqeqeq": true, + "indent": 4, + "latedef": "nofunc", + "newcap": true, + "unused": true, + "eqnull": true, + "bitwise": true, + "noarg": true, + "noempty": true, + "nonew": true, + "node": true +} \ No newline at end of file diff --git a/node_modules/express-validator/.npmignore b/node_modules/express-validator/.npmignore new file mode 100644 index 0000000..b083d11 --- /dev/null +++ b/node_modules/express-validator/.npmignore @@ -0,0 +1,3 @@ +node_modules +.idea +npm-debug.log \ No newline at end of file diff --git a/node_modules/express-validator/.travis.yml b/node_modules/express-validator/.travis.yml new file mode 100644 index 0000000..771ce3a --- /dev/null +++ b/node_modules/express-validator/.travis.yml @@ -0,0 +1,11 @@ +sudo: false +language: node_js +node_js: + - "0.10" + - "0.12" + - "4.0" + - "4.1" +install: + - npm install +script: + - npm run travis-build diff --git a/node_modules/express-validator/CHANGELOG.md b/node_modules/express-validator/CHANGELOG.md new file mode 100644 index 0000000..0f249c1 --- /dev/null +++ b/node_modules/express-validator/CHANGELOG.md @@ -0,0 +1,227 @@ +## Change Log + +### upcoming 2015/05/04 +- [ea00f9d](https://github.com/ctavan/express-validator/commit/ea00f9d6cfe0859f6f00ceb45d66f4d9270064b0) Update changelog. (@rustybailey) + +### v2.10.0 2015/05/04 +- [0f48735](https://github.com/ctavan/express-validator/commit/0f48735dc77ec561ad014a721375b561ce3889fe) 2.10.0 (@rustybailey) +- [bc2ef59](https://github.com/ctavan/express-validator/commit/bc2ef59b5a5c45be12f6efb27199a29d8689ac2f) Use the same node versions as node-validator. (@rustybailey) +- [0c3aaec](https://github.com/ctavan/express-validator/commit/0c3aaecb0f7d4a75a1bc20e94290cfe72e98a49c) Bump validator version to 3.39.0 (@rustybailey) +- [dfb757b](https://github.com/ctavan/express-validator/commit/dfb757b8eafe3149c552be4b92eb259fb6bdd5e5) Add changelog to devDependencies and add npm script to generate changelog. (@rustybailey) +- [bf044b5](https://github.com/ctavan/express-validator/commit/bf044b577f6999a7f1e92cb9f74ddf4a44bd78d3) Add node 0.12 to travis.yml, remove dead gist link in README, add license in package.json. (@rustybailey) +- [f42077f](https://github.com/ctavan/express-validator/commit/f42077fabfc9b8ef6100069b17e83f5fab2eb395) Add editorconfig. (@rustybailey) +- [73daa44](https://github.com/ctavan/express-validator/commit/73daa44dee192049da4fff732dec629a6630af73) Add jshint to devDependencies, add .jshintrc, fix semicolon issues. (@rustybailey) +- [fb8d049](https://github.com/ctavan/express-validator/commit/fb8d049dd1f0a0da6c0070cf160316f9b732a732) Add comment to explain before() function busting require's cache in each test file. (@rustybailey) +- [7fc7b1c](https://github.com/ctavan/express-validator/commit/7fc7b1c54c22f19dfc650cba06b47e6e05d0c653) Remove async from devDependencies (@rustybailey) +- [a74de1e](https://github.com/ctavan/express-validator/commit/a74de1eb3ef2bdf67beb5be4fd3a8e51e4d190b5) Remove old tests and change npm test to use Mocha. (@rustybailey) +- [39f1b55](https://github.com/ctavan/express-validator/commit/39f1b55f817a7ca1f0fc802247ba8dd0d24ff21f) Add Mocha tests for validating regex routes (@rustybailey) +- [68adc6e](https://github.com/ctavan/express-validator/commit/68adc6e76b6abb3f0c1946c3c51ca16c1cebe9b6) Add Mocha tests for nested input (@rustybailey) +- [a029176](https://github.com/ctavan/express-validator/commit/a029176a7c7ac0666f0b93adca0d2ea0a57ff98b) Add Mocha tests for mapped output using validationErrors(true) (@rustybailey) +- [5a2f7ef](https://github.com/ctavan/express-validator/commit/5a2f7ef3a5a0f59fb9f6692e2e5d93f81b5e497b) Add Mocha tests for check() (@rustybailey) +- [9cd6f62](https://github.com/ctavan/express-validator/commit/9cd6f626cb287f1a877e0f645690b528938f3dc4) Add Mocha tests for checkQuery() (@rustybailey) +- [c91e022](https://github.com/ctavan/express-validator/commit/c91e0220312097548abaf21d91e076e18726f3ab) Add Mocha tests for checkBody() (@rustybailey) +- [bbcb462](https://github.com/ctavan/express-validator/commit/bbcb4620ada424a2352a148975eba2072d8badf3) Add tests for checkParams() (@rustybailey) +- [d2eb638](https://github.com/ctavan/express-validator/commit/d2eb638611a015dd04d4aa59c4c790ca324bcc66) Add mocha/chai as dependencies, simplify app.js helper, create mocha tests for optional(). (@rustybailey) + +### v2.9.1 2015/04/28 +- [9c87684](https://github.com/ctavan/express-validator/commit/9c87684a02eff71f40fc98ce3da37992fee464cd) Bump version to 2.9.1. (@rustybailey) +- [37ede78](https://github.com/ctavan/express-validator/commit/37ede786203d5b9aa87acf96bd568c26fcc6de3a) Fix checkHeader so that it works with optional(). (@rustybailey) +- [136307f](https://github.com/ctavan/express-validator/commit/136307f94aebaf4dcc7e83dee62bfd5cae9a1333) Move change log into its own file and expand it using github-changes. Fixes #130 (@rustybailey) + +### v2.9.0 2015/03/20 +- [c2e5124](https://github.com/ctavan/express-validator/commit/c2e512490667cc1cbc22e2de762c79cbf425354a) Bump version to 2.9.0 (@ctavan) +- [9624cca](https://github.com/ctavan/express-validator/commit/9624cca38836a7299bba570e3addd07913ded174) Update node validator dependency. (@ctavan) +- [9247648](https://github.com/ctavan/express-validator/commit/9247648f7d8fc1c8aa017ad19e1f24e90aff311a) Fix deprecated use of req.param(), closes #117. (@ctavan) +- [d8ba047](https://github.com/ctavan/express-validator/commit/d8ba0470d85e283e38870db5f9a0cde964561171) replaced req.param call to remove deprecation msg (@janza) +- [b2f727b](https://github.com/ctavan/express-validator/commit/b2f727b4d948cd7a94c6c3570fba5de5f626dc34) Add LICENSE (@becausehama) + +### v2.8.0 2014/12/23 +- [e49ee9d](https://github.com/ctavan/express-validator/commit/e49ee9ddb7cf3ebf804874f1ba5281f890693799) Bump version to 2.8.0 (@ctavan) +- [d48d248](https://github.com/ctavan/express-validator/commit/d48d2480f992ffbe7cac5fe00e3d75f146e5290a) Updating to validator 3.26.0 (@aredo) + +### v2.7.0 2014/11/13 +- [84937cf](https://github.com/ctavan/express-validator/commit/84937cf4dee304914f763d109a657bf24c61914c) Bump version 2.7.0 (@ctavan) +- [51e39b3](https://github.com/ctavan/express-validator/commit/51e39b3526a0386ab1003b6485a8351567959388) Updating to validator 3.22.1 (@nfrasser) + +### v2.6.0 2014/09/24 +- [8b67263](https://github.com/ctavan/express-validator/commit/8b67263c1fcf31b920e369fcb1e7a47a0eef07c6) Upgraded to validator 3.19.0 (@fiznool) + +### v2.5.0 2014/09/16 +- [1dc8679](https://github.com/ctavan/express-validator/commit/1dc8679ef2207e1ac886bf3eeac7f63955c042c5) Bump version to 2.5.0 (@ctavan) +- [2205323](https://github.com/ctavan/express-validator/commit/220532338d20abc57ba2510b1f51c86c31705757) adds tests for optional() method (@BAKFR) +- [7402642](https://github.com/ctavan/express-validator/commit/7402642a9a7917f16bba42c1d06503047821052b) add curly braces to respect the coding style (@BAKFR) +- [b90f482](https://github.com/ctavan/express-validator/commit/b90f482d13d446f4e5d22b9ba038be0740e9d20d) add documentation for customValidators option + +### v2.4.0 2014/09/04 +- [9d18380](https://github.com/ctavan/express-validator/commit/9d18380884562b9d8e366f1b180f9eee11658f66) Bump version to 2.4.0 (@ctavan) +- [9a167b7](https://github.com/ctavan/express-validator/commit/9a167b7e524113a78ef04e77bf946d9a8832ddc9) whitespace cleanup +- [668e5c5](https://github.com/ctavan/express-validator/commit/668e5c547c22c78e9b10b525d6357cf9b2e8a969) Add support for custom validators +- [58d2142](https://github.com/ctavan/express-validator/commit/58d2142798898cc6b6bec71a1c333324ec6d6a5a) add documentation on README (@BAKFR) +- [e42f650](https://github.com/ctavan/express-validator/commit/e42f650bb165bcaa18d36a2168a6c43968cf9c90) add the method optional() who disables the checks if value is undefined (@BAKFR) + +### v2.3.0 2014/06/06 +- [a922832](https://github.com/ctavan/express-validator/commit/a9228327c8969b9640646774115012c29e2f13d2) Bump version to 2.3.0 (@ctavan) +- [85348f5](https://github.com/ctavan/express-validator/commit/85348f59ed65fc657bccb9f63a91954b602855b2) Add a check if req.files array is not undefined before accessing it + +### v2.2.0 2014/06/03 +- [d2ea7b1](https://github.com/ctavan/express-validator/commit/d2ea7b1315cf7403776b7473798f6219ba26ade6) Bump version to 2.2.0 (@ctavan) + +### v2.1.2 2014/04/28 +- [6dcddc8](https://github.com/ctavan/express-validator/commit/6dcddc83d71e540d20ec2e0da3dbb717c78acd7f) Bump version to 2.1.2 (@ctavan) +- [bffe0d9](https://github.com/ctavan/express-validator/commit/bffe0d9a2ea9a29505eb2264e04badc4d68e221b) Fixed function call order (@killroy42) +- [129be78](https://github.com/ctavan/express-validator/commit/129be780252c9bb88bd281861561077d4bf96241) Fixed arguments usage for strict compliance (@killroy42) +- [defffe1](https://github.com/ctavan/express-validator/commit/defffe1b4493b7e21122fbe4f5ac877543f8a702) Update express_validator.js (@r3mus) +- [01bdbf4](https://github.com/ctavan/express-validator/commit/01bdbf47486136364635edc73725c92f8690a90c) Return sanitized value from req.sanitize() (@dpolivy) + +### v2.1.1 2014/03/17 +- [151f5a4](https://github.com/ctavan/express-validator/commit/151f5a45775926a07b01366ac4846823d680871b) Bump version to 2.1.1 (@ctavan) +- [75a8359](https://github.com/ctavan/express-validator/commit/75a8359e5703c1e9476c6244bd9a2dcf98b96add) fix: use strict equality/inequality +- [010cb51](https://github.com/ctavan/express-validator/commit/010cb51f75737a347e69d5118b18789e89f28560) fix docs Extending (@bars3s) +- [7388983](https://github.com/ctavan/express-validator/commit/7388983641ac6243ba5cd24d832fad77e884b455) fix sanitaze trim,ltrim... methods (@bars3s) +- [02930ff](https://github.com/ctavan/express-validator/commit/02930ff915e319b57a5a258893aaaa0d38589c7f) add .idea to .gitignore (@bars3s) + +### v2.1.0 2014/03/10 +- [aaff5d9](https://github.com/ctavan/express-validator/commit/aaff5d92e006ef6ee55ee3758ccfd17fe92c22ac) Update validator to 3.5.0 and bump version to 2.1.0 (@ctavan) +- [7f3b8a9](https://github.com/ctavan/express-validator/commit/7f3b8a9119b2eb17826015cf59a36e0b3925c55a) Update README. (@ctavan) +- [079c6da](https://github.com/ctavan/express-validator/commit/079c6da0bfe14f95a0b94721488e06081e5b89ed) Update package.json (@gkorland) +- [a91664b](https://github.com/ctavan/express-validator/commit/a91664be05bd3ce37811b0c1e24a75aa8d6e5bff) Update node-validator repository url (@marcbachmann) +- [6fe2aa6](https://github.com/ctavan/express-validator/commit/6fe2aa67a7f9fd0110085e67a8066bc46cdbe605) - fixed typo (@theorm) +- [816437a](https://github.com/ctavan/express-validator/commit/816437a7df0299172d9e78ad6c3d0f29e07ebff9) - and quoting node versions to make travis linter happy (@theorm) +- [aa7d749](https://github.com/ctavan/express-validator/commit/aa7d7496b307394a0c55a7dcfbe55c45d2332d62) - removed node 0.6 from .travis.yml. 0.8+ is required now as it is the minimum version for validator.js (@theorm) +- [36e9025](https://github.com/ctavan/express-validator/commit/36e90250ed322b3aefe220dc2afb5bca40de0a5e) - setting node version to >= 0.8 (@theorm) +- [af9abb5](https://github.com/ctavan/express-validator/commit/af9abb54898438092ecba0dfff5c30eb15b32087) - camelCasing variables (@theorm) + +### v2.0.0 2014/01/21 +- [22fce51](https://github.com/ctavan/express-validator/commit/22fce515cf2fdf9e1064150773be96bcbae37fad) - major version bump & fixing local vars. (@theorm) + +### v1.0.2 2014/01/21 +- [94a3c13](https://github.com/ctavan/express-validator/commit/94a3c1360a460d6e32d1142ad412a50e4e74eb0c) - version bump and new contributor (@theorm) +- [a219e29](https://github.com/ctavan/express-validator/commit/a219e29db6d01b9c4c5f86ab91b4e23083e958ca) - modified to work with validator 3.1.0 (@theorm) +- [dc0ee77](https://github.com/ctavan/express-validator/commit/dc0ee7783a98c4922121bffe09fc6e40715cc1a0) added documentation for checkParams and checkQuery (@smitp) +- [a8604f8](https://github.com/ctavan/express-validator/commit/a8604f84e09cadceb7ce14d1118b36e11a31235c) As .xss() is removed from node-validator 2.0.0, changed example in comments (@manV) + +### v1.0.1 2013/11/25 +- [cd65d4c](https://github.com/ctavan/express-validator/commit/cd65d4c71e0f11ded917c20b6e98d9874ee9add6) Bump version to 1.0.1 (@ctavan) +- [63f1248](https://github.com/ctavan/express-validator/commit/63f124886cd693c70d962cdba99e92c38c4dfa18) add information from #21 as I'm not only one who was stuck at this (@kamilbiela) + +### v1.0.0 2013/11/11 +- [b63f224](https://github.com/ctavan/express-validator/commit/b63f224f6b5a0394e4213dfc5c399b8565ba0bcd) bumped to 1.0.0 (@petecoop) +- [5e5c0a1](https://github.com/ctavan/express-validator/commit/5e5c0a1f571c48e32f196edb461e494fa432ee0b) updated to v2 (@petecoop) +- [406014e](https://github.com/ctavan/express-validator/commit/406014e3a83fa0ead0b2bcdb012f91b93eeded94) Added support for checkQuery and checkParams + tests (@kornifex) +- [7f33f03](https://github.com/ctavan/express-validator/commit/7f33f031617554b3f5386c48de68e7de831d4ab0) Ensure req.body is defined (@cjihrig) + +### v0.8.0 2013/08/22 +- [57d62fe](https://github.com/ctavan/express-validator/commit/57d62fe815bd8077eac8b7b6d7686c037d9969b5) Bump version to 0.8.0 (@ctavan) +- [feec643](https://github.com/ctavan/express-validator/commit/feec64356e88e4b1cda4e13db503f6389382a469) Bump validator dependency to 1.5.0, closes #47. (@ctavan) +- [7c181e5](https://github.com/ctavan/express-validator/commit/7c181e51cb74bdfef84a4345ddd0c86d80845ebf) Update README.md (@JedWatson) + +### v0.7.0 2013/07/10 +- [5f59b15](https://github.com/ctavan/express-validator/commit/5f59b15751adf8f2abe615f33afce9f18e83da1a) Bump version to 0.7.0 (@ctavan) +- [69e9203](https://github.com/ctavan/express-validator/commit/69e92030324b194b372ff6dc106b40c167c2f79e) Bump validator dependency to 1.2.1 (@ctavan) +- [f726037](https://github.com/ctavan/express-validator/commit/f72603764e82e9afb7103c4b1e3090a4e4daadce) Fix two typos (@Michael-Stanford) +- [2f52adb](https://github.com/ctavan/express-validator/commit/2f52adbe46ca9f09da58fa98c33dd197bf57cfe3) Check parsed attached Files (@gkorland) +- [9dde887](https://github.com/ctavan/express-validator/commit/9dde8870ba97be360e12bfae50a39751443b22a0) replace 500 code with 400 (@gkorland) +- [09f5c43](https://github.com/ctavan/express-validator/commit/09f5c435e9918270876b53218e8b6c4ab5b91c1c) Also run tests under node v0.10 in travis. (@ctavan) + +### v0.6.0 2013/06/14 +- [d493673](https://github.com/ctavan/express-validator/commit/d493673956ee0a1c89e2729366dc636fc3c2b1fd) Bump version to 0.6.0. (@ctavan) +- [5aecec5](https://github.com/ctavan/express-validator/commit/5aecec55b476c586332fc4336b2f5997ed6d034c) Bump validator dependency to 1.2.0 (@ctavan) +- [8fe0862](https://github.com/ctavan/express-validator/commit/8fe086282661c10b1765b557423144adb90d2e17) Bumped version to 5 because this is a breaking change. (@arb) +- [066807b](https://github.com/ctavan/express-validator/commit/066807bd25352e06ab6ad9e58088ebd22ab66d3b) Fixed to work with new structure. (@arb) +- [15216ae](https://github.com/ctavan/express-validator/commit/15216ae24ffceff4f04cb28df4ad001d857c2249) Added method to pass options. (@arb) +- [3a341f5](https://github.com/ctavan/express-validator/commit/3a341f5fc03ab75ba2b653ab208f7801422e1665) Added options section (@arb) + +### v0.4.1 2013/06/06 +- [e739e2b](https://github.com/ctavan/express-validator/commit/e739e2b6877d58707bdad598f9f634d88f417081) Bump version to 0.4.1 (@ctavan) +- [3f03a68](https://github.com/ctavan/express-validator/commit/3f03a683f7732ac39f53324ed6842120e78b8262) Update readme. (@ctavan) + +### v0.4.0 2013/06/06 +- [1fe9c03](https://github.com/ctavan/express-validator/commit/1fe9c03f1f4416c5c921429ae775c8bfa4773d2d) Bump version to 0.4.0 (@ctavan) +- [0139626](https://github.com/ctavan/express-validator/commit/0139626b09f9072e2f7739fa2a7c7bd10ab74bb0) Upgrade validator dependency. (@ctavan) +- [5ac347c](https://github.com/ctavan/express-validator/commit/5ac347c8aa3b5abfb085bcf740a8ecae6befc51f) Added ignore file to modules stop being marked as changed. (@arb) +- [96e759e](https://github.com/ctavan/express-validator/commit/96e759e0df154352bef835013fb0a71b5416e5ca) Added test for req.checkBody (@arb) +- [a37b8d7](https://github.com/ctavan/express-validator/commit/a37b8d7d1db41673ef76755178be3fa4335aac56) Added myself to the contributers. (@arb) +- [7bf7729](https://github.com/ctavan/express-validator/commit/7bf77296a00469e9d4de7941cb8968e955da13fd) Style change. (@arb) +- [7cb9113](https://github.com/ctavan/express-validator/commit/7cb9113bec43e28c3ec1f78a2a3e20d763da6f3b) Added check body function to validate only the request body. (@arb) +- [69fdeed](https://github.com/ctavan/express-validator/commit/69fdeed8e82681ee03d9ba347a9b180ee17dade5) Sorry, was moving this around without updating. (@Prinzhorn) +- [9ae9e6b](https://github.com/ctavan/express-validator/commit/9ae9e6be816f8550667ed6a4f3e595d1204f4a43) Updated the documentation about extending. (@Prinzhorn) + +### v0.3.2 2013/02/27 +- [3c1c52c](https://github.com/ctavan/express-validator/commit/3c1c52c7a10fd79b42814c3c6c28ecece9f6dd71) Bump version to 0.3.2 (@ctavan) +- [4ff8a48](https://github.com/ctavan/express-validator/commit/4ff8a4879aa303ea9ef5f98760eb730a48a184f3) Upgrade validator dependency to 0.4.25. Fixes #25. (@ctavan) + +### v0.3.1 2013/01/03 +- [48f90b7](https://github.com/ctavan/express-validator/commit/48f90b7922a12fbfbef8bc10bcf98a913dd043ad) Bump version to 0.3.1 (@ctavan) +- [c4463f7](https://github.com/ctavan/express-validator/commit/c4463f767ba75ec61f75e8f13455a003b1076c36) Update package.json + +### v0.3.0 2012/10/08 +- [fa23c0f](https://github.com/ctavan/express-validator/commit/fa23c0f952e781cdf25d2167b870638440cb5eb5) Bump version to 0.3.0 (@ctavan) +- [62bb9dd](https://github.com/ctavan/express-validator/commit/62bb9dd27f1519e3eebaad2647a51cdf7c82675f) Update validator dependency. (@ctavan) +- [e241d9f](https://github.com/ctavan/express-validator/commit/e241d9fa0accab8fc550c5d5aa398c80a0d38b79) Return `null` for validation errors instead of array. (@ctavan) +- [b60e434](https://github.com/ctavan/express-validator/commit/b60e434e03de9e1e37928381beb71031b86cd446) Fix docs. (@ctavan) + +### v0.2.4 2012/08/20 +- [1fb5b56](https://github.com/ctavan/express-validator/commit/1fb5b560813b3bd1f0d4a9f556b62804b231d94d) Bump version to v0.2.4 (@ctavan) +- [521e50b](https://github.com/ctavan/express-validator/commit/521e50babe0f40c87cc861d835954ce58c3f2ba6) Fix code style / line lengths. (@ctavan) +- [31d51d2](https://github.com/ctavan/express-validator/commit/31d51d245bb9c8f654e62f0ebdd6c9388d80bbf1) Tests for RegExp-defined routes (@cecchi) +- [f73af12](https://github.com/ctavan/express-validator/commit/f73af126290035577cec014630cb478f08d383bb) Using strict comparison (@cecchi) +- [3ba4e3f](https://github.com/ctavan/express-validator/commit/3ba4e3f2340e9e5000b2dd7dd2e83050ecfb236c) Support for routes defined by RegExp (@cecchi) + +### v0.2.3 2012/08/03 +- [1590b47](https://github.com/ctavan/express-validator/commit/1590b471943e72535be883d3d718b08eeb8034ad) Bump version to 0.2.3 (@ctavan) +- [fda5c03](https://github.com/ctavan/express-validator/commit/fda5c0374298b8d14e6695143db27c6fd3129f2e) Remove node 0.4 from travis and add 0.8 (@ctavan) + +### v0.2.2 2012/08/03 +- [9537060](https://github.com/ctavan/express-validator/commit/95370604bfde8ff8326c65e64c6a7cb5cc91b386) Update dependencies and bump version to v0.2.2 (@ctavan) +- [c73802c](https://github.com/ctavan/express-validator/commit/c73802c95a5831415c10f8f8de9616f2fa133705) Add documentation (@ctavan) +- [672d48b](https://github.com/ctavan/express-validator/commit/672d48bc3549734edebcbabe9bc6067393f8dd18) Fix coding style (@ctavan) +- [dfccb6d](https://github.com/ctavan/express-validator/commit/dfccb6d68636b53cb7d78d2cdac4433b40f8a014) Restore removed test case (@ctavan) +- [de62248](https://github.com/ctavan/express-validator/commit/de6224811f666f5945267d2439da20b173efb4b5) Updated test for testing nested dot notation (@sharonjl) +- [2ff7983](https://github.com/ctavan/express-validator/commit/2ff7983a7579f303716f4c176277cbd05935481e) Updated method for parsing nested notation (@sharonjl) +- [c54720f](https://github.com/ctavan/express-validator/commit/c54720f74a517f1bd9bcbbb37364ff5107316565) Added validate() alias for check() (@sharonjl) +- [1b94da6](https://github.com/ctavan/express-validator/commit/1b94da675a86921b73450997c10aa52a5e0c0cf2) Update lib/express_validator.js (@pimguilherme) + +### v0.2.1 2012/04/25 +- [2a5903d](https://github.com/ctavan/express-validator/commit/2a5903dd629f183c278ff0279637ea44ee517eb5) Bump version to 0.2.1 (@ctavan) +- [861806d](https://github.com/ctavan/express-validator/commit/861806d375dce1d8533435219047e742b4d7bf36) Fix chaining validators (@rapee) +- [5436c0f](https://github.com/ctavan/express-validator/commit/5436c0f5020e97f0a74a09a79e40f88fb532ad89) Add travis.ci (@ctavan) +- [65506ba](https://github.com/ctavan/express-validator/commit/65506bac7a62bc7b50c7213e761a81b536fd1578) Code style fixes (@ctavan) +- [94062f0](https://github.com/ctavan/express-validator/commit/94062f051b8ce10cc87cb20079ee7f553f9e449f) Add Makefile (@ctavan) +- [07f4f06](https://github.com/ctavan/express-validator/commit/07f4f060d5cadbfb2465efe93373a8a7d4fc949e) Add @orfaust to contributors (@ctavan) +- [c4b83d0](https://github.com/ctavan/express-validator/commit/c4b83d0db478e22e557de96649a77b7ab264c168) Add more tests, document additions (@ctavan) +- [c3f3a3e](https://github.com/ctavan/express-validator/commit/c3f3a3e704f95ec14f0e8a12375313ff2c177468) Remove unused variable (@ctavan) +- [dc0d92b](https://github.com/ctavan/express-validator/commit/dc0d92b4430547971c9934b663b3c985a30f6bcf) Refactor tests (@ctavan) +- [cae328a](https://github.com/ctavan/express-validator/commit/cae328a6692130df0335582ab26138f09393210e) Add basic test cases and upgrade versions (@ctavan) +- [0c33221](https://github.com/ctavan/express-validator/commit/0c332216cacf70857cbaa7bbb1ce16aeab7bd471) 1: solution for nested inputs. 2: more complete errors response (@orfaust) +- [0d63f04](https://github.com/ctavan/express-validator/commit/0d63f0442e795ec0371e73050076ea3dd60c0725) Fix for undefined req.onErrorCallback (@orfaust) +- [efba5e8](https://github.com/ctavan/express-validator/commit/efba5e82b81cd14b1ec953a56ec531d8169c1fbd) get complete error objects (@orfaust) + +### v0.1.3 2012/01/02 +- [4e8f245](https://github.com/ctavan/express-validator/commit/4e8f2451266e6a3a7b20180c723e5760fdef89b9) Version bump v0.1.3 (@ctavan) +- [1041b4c](https://github.com/ctavan/express-validator/commit/1041b4c44c7819fc44aa572fcbf2135bc2518b07) Add another example to the readme (@ctavan) +- [cb7d906](https://github.com/ctavan/express-validator/commit/cb7d906718d6023cce485b2b033647928510b8ef) Update readme (@ctavan) + +### v0.1.2 2012/01/02 +- [3d323c6](https://github.com/ctavan/express-validator/commit/3d323c6daabc6b106a24aca645e527c204370078) Version bump (@ctavan) +- [de0773c](https://github.com/ctavan/express-validator/commit/de0773ce497aed71bee576b0378635e5c51d494c) exposed Validator & Filter to module so that end-users can easily hang their own validations/sanitizers onto them (@troygoode) +- [bed2d78](https://github.com/ctavan/express-validator/commit/bed2d78417ae3e71ef198b48f005da7af98c1710) Also update readme, see #2 (@ctavan) +- [fffa37f](https://github.com/ctavan/express-validator/commit/fffa37f51d9ba769b562ad7170e29ab391b0588c) Return this in error callback to allow for assert-method-chaining, fixes #2 (@ctavan) + +### v0.1.1 2011/10/20 +- [d8a7658](https://github.com/ctavan/express-validator/commit/d8a7658ddd34e72c445a5827034481a1e91605b4) Add some keywords (@ctavan) +- [9fd2261](https://github.com/ctavan/express-validator/commit/9fd2261817c3fbe32de26670747c020cf6eb0b71) Update version to v0.1.1 (@ctavan) +- [722d9a7](https://github.com/ctavan/express-validator/commit/722d9a7c98fe9e00968eea5b9660f51c073afd1a) Remove now unneeded mixinParams() method, see #1 (@ctavan) +- [fbd6461](https://github.com/ctavan/express-validator/commit/fbd64617e354c06aac5bbd30d338bb4aa303beca) Update example and documentation for changes of #1, fixes #1 (@ctavan) +- [ce69619](https://github.com/ctavan/express-validator/commit/ce69619266357cada2efa3508ae036b9e483a726) Use req.param() instead of req.params + req.mixinParams() for filter() as well. (@ctavan) +- [0e77df0](https://github.com/ctavan/express-validator/commit/0e77df06d688e69d801976264d23d8bc8bd662bb) Use express's req.param() to get params from req.params, req.query and req.body. req.check now no longer relies on req.mixinParams(), see #1 (@ctavan) +- [779660f](https://github.com/ctavan/express-validator/commit/779660f47565bf6cfc66c447f75448d585831821) Typo (@ctavan) +- [7f398b2](https://github.com/ctavan/express-validator/commit/7f398b29404a93c5222ec339f7aaecf4c143f28b) Installation note (@ctavan) + +### v0.1.0 2011/10/05 +- [764b5dc](https://github.com/ctavan/express-validator/commit/764b5dc4b63df8f1b2ae23602b75e3d4281b793c) Formatting (@ctavan) +- [d0090e7](https://github.com/ctavan/express-validator/commit/d0090e750ad99ce1d1d0bece930da90c1a2c1743) Add me as a contributor + fix some typos (@ctavan) +- [3537462](https://github.com/ctavan/express-validator/commit/3537462d697f520c18e362e0bad3f453dc26847f) Add original author credits to the packag.json (@ctavan) +- [671ad61](https://github.com/ctavan/express-validator/commit/671ad613c85d546328f05e238a8a1ee27ec6ac2c) Add an example server (@ctavan) +- [ae10270](https://github.com/ctavan/express-validator/commit/ae102704accf206ca617a12014a26c03251a365d) Typos (@ctavan) +- [0dfb1ba](https://github.com/ctavan/express-validator/commit/0dfb1ba5d38039a53f139bacff74e1fb920faec8) Improve example in readme, add credits for original author (@ctavan) +- [df36372](https://github.com/ctavan/express-validator/commit/df36372d05928c8f46c69cf056705f977334a167) Initial commit (@ctavan) \ No newline at end of file diff --git a/node_modules/express-validator/LICENSE b/node_modules/express-validator/LICENSE new file mode 100644 index 0000000..801112c --- /dev/null +++ b/node_modules/express-validator/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 Chris O'Hara + +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. diff --git a/node_modules/express-validator/README.md b/node_modules/express-validator/README.md new file mode 100644 index 0000000..079023a --- /dev/null +++ b/node_modules/express-validator/README.md @@ -0,0 +1,380 @@ +# express-validator + +[![Build Status](https://secure.travis-ci.org/ctavan/express-validator.png)](http://travis-ci.org/ctavan/express-validator) + +An [express.js]( https://github.com/visionmedia/express ) middleware for +[node-validator]( https://github.com/chriso/validator.js ). + +## Installation + +``` +npm install express-validator +``` + +## Usage + +```javascript +var util = require('util'), + express = require('express'), + expressValidator = require('express-validator'), + app = express.createServer(); + +app.use(express.bodyParser()); +app.use(expressValidator([options])); // this line must be immediately after express.bodyParser()! + +app.post('/:urlparam', function(req, res) { + + // VALIDATION + // checkBody only checks req.body; none of the other req parameters + // Similarly checkParams only checks in req.params (URL params) and + // checkQuery only checks req.query (GET params). + req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt(); + req.checkParams('urlparam', 'Invalid urlparam').isAlpha(); + req.checkQuery('getparam', 'Invalid getparam').isInt(); + + // OR assert can be used to check on all 3 types of params. + // req.assert('postparam', 'Invalid postparam').notEmpty().isInt(); + // req.assert('urlparam', 'Invalid urlparam').isAlpha(); + // req.assert('getparam', 'Invalid getparam').isInt(); + + // SANITIZATION + // as with validation these will only validate the corresponding + // request object + req.sanitizeBody('postparam').toBoolean(); + req.sanitizeParams('urlparam').toBoolean(); + req.sanitizeQuery('getparam').toBoolean(); + + // OR find the relevent param in all areas + req.sanitize('postparam').toBoolean(); + + var errors = req.validationErrors(); + if (errors) { + res.send('There have been validation errors: ' + util.inspect(errors), 400); + return; + } + res.json({ + urlparam: req.params.urlparam, + getparam: req.params.getparam, + postparam: req.params.postparam + }); +}); + +app.listen(8888); +``` + +Which will result in: + +``` +$ curl -d 'postparam=1' http://localhost:8888/test?getparam=1 +{"urlparam":"test","getparam":"1","postparam":true} + +$ curl -d 'postparam=1' http://localhost:8888/t1est?getparam=1 +There have been validation errors: [ + { param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ] + +$ curl -d 'postparam=1' http://localhost:8888/t1est?getparam=1ab +There have been validation errors: [ + { param: 'getparam', msg: 'Invalid getparam', value: '1ab' }, + { param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ] + +$ curl http://localhost:8888/test?getparam=1&postparam=1 +There have been validation errors: [ + { param: 'postparam', msg: 'Invalid postparam', value: undefined} ] +``` + +### Middleware Options +####`errorFormatter` +_function(param,msg,value)_ + +The `errorFormatter` option can be used to specify a function that can be used to format the objects that populate the error array that is returned in `req.validationErrors()`. It should return an `Object` that has `param`, `msg`, and `value` keys defined. + +```javascript +// In this example, the formParam value is going to get morphed into form body format useful for printing. +app.use(expressValidator({ + errorFormatter: function(param, msg, value) { + var namespace = param.split('.') + , root = namespace.shift() + , formParam = root; + + while(namespace.length) { + formParam += '[' + namespace.shift() + ']'; + } + return { + param : formParam, + msg : msg, + value : value + }; + } +})); +``` + +####`customValidators` +_{ "validatorName": function(value, [additional arguments]), ... }_ + + +The `customValidators` option can be used to add additional validation methods as needed. This option should be an `Object` defining the validator names and associated validation functions. + +Define your custom validators: + +```javascript +app.use(expressValidator({ + customValidators: { + isArray: function(value) { + return Array.isArray(value); + }, + gte: function(param, num) { + return param >= num; + } + } +})); +``` +Use them with their validator name: +```javascript +req.checkBody('users', 'Users must be an array').isArray(); +req.checkQuery('time', 'Time must be an integer great than or equal to 5').isInt().gte(5) +``` +####`customSanitizers` +_{ "sanitizerName": function(value, [additional arguments]), ... }_ + +The `customSanitizers` option can be used to add additional sanitizers methods as needed. This option should be an `Object` defining the sanitizer names and associated functions. + +Define your custom sanitizers: + +```javascript +app.use(expressValidator({ + customSanitizers: { + toSanitizeSomehow: function(value) { + var newValue = value;//some operations + return newValue; + }, + } +})); +``` +Use them with their sanitizer name: +```javascript +req.sanitize('address').toSanitizeSomehow(); +``` + +## Validation + +#### req.check(); +```javascript + req.check('testparam', 'Error Message').notEmpty().isInt(); + req.check('testparam.child', 'Error Message').isInt(); // find nested params + req.check(['testparam', 'child'], 'Error Message').isInt(); // find nested params +``` + +Starts the validation of the specifed parameter, will look for the parameter in `req` in the order `params`, `query`, `body`, then validate, you can use 'dot-notation' or an array to access nested values. + +If a validator takes in params, you would call it like `req.assert('reqParam').contains('thisString');`. + +Validators are appended and can be chained. See [chriso/validator.js](https://github.com/chriso/validator.js) for available validators, or [add your own](#customvalidators). + +#### req.assert(); +Alias for [req.check()](#reqcheck). + +#### req.validate(); +Alias for [req.check()](#reqcheck). + +#### req.checkBody(); +Same as [req.check()](#reqcheck), but only looks in `req.body`. + +#### req.checkQuery(); +Same as [req.check()](#reqcheck), but only looks in `req.query`. + +#### req.checkParams(); +Same as [req.check()](#reqcheck), but only looks in `req.params`. + +#### req.checkHeaders(); +Only checks `req.headers`. This method is not covered by the general `req.check()`. + +## Asynchronous Validation + +If you need to perform asynchronous validation, for example checking a database if a username has been taken already, your custom validator can return a promise. + +You **MUST** use `asyncValidationErrors` which returns a promise to check for errors, otherwise the validator promises won't be resolved. + + *`asyncValidationErrors` will also return any regular synchronous validation errors.* + + ```javascript +app.use(expressValidator({ + customValidators: { + isUsernameAvailable: function(username) { + return new Promise(function(resolve, reject) { + ... + }); + } + } +})); + +req.check('username', 'Username Taken').isUsernameAvailable(); + +req.asyncValidationErrors().catch(function(errors) { + res.send(errors); +}); + +``` +## Validation by Schema + +Alternatively you can define all your validations at once using a simple schema. This also enables per-validator error messages. +Schema validation will be used if you pass an object to any of the validator methods. + +```javascript +req.checkBody({ + 'email': { + notEmpty: true, + isEmail: { + errorMessage: 'Invalid Email' + } + }, + 'password': { + notEmpty: true, + isLength: { + options: [2, 10] // pass options to the validator with the options property as an array + }, + errorMessage: 'Invalid Password' // Error message for the parameter + }, + 'name.first': { // + optional: true, // won't validate if field is empty + isLength: { + options: [2, 10], + errorMessage: 'Must be between 2 and 10 chars long' // Error message for the validator, takes precedent over parameter message + }, + errorMessage: 'Invalid First Name' + } +}); +``` + +## Validation errors + +You have two choices on how to get the validation errors: + +```javascript +req.assert('email', 'required').notEmpty(); +req.assert('email', 'valid email required').isEmail(); +req.assert('password', '6 to 20 characters required').len(6, 20); + +var errors = req.validationErrors(); // Or req.asyncValidationErrors(); +var mappedErrors = req.validationErrors(true); // Or req.asyncValidationErrors(true); +``` + +errors: + +```javascript +[ + {param: "email", msg: "required", value: ""}, + {param: "email", msg: "valid email required", value: ""}, + {param: "password", msg: "6 to 20 characters required", value: ""} +] +``` + +mappedErrors: + +```javascript +{ + email: { + param: "email", + msg: "valid email required", + value: "" + }, + password: { + param: "password", + msg: "6 to 20 characters required", + value: "" + } +} +``` +*Note: Using mappedErrors will only provide the last error per param in the chain of validation errors.* + +### Per-validation messages + +You can provide an error message for a single validation with `.withMessage()`. This can be chained with the rest of your validation, and if you don't use it for one of the validations then it will fall back to the default. + +```javascript +req.assert('email', 'Invalid email') + .notEmpty().withMessage('Email is required') + .isEmail(); +var errors = req.validationErrors(); +``` +errors: + +```javascript +[ + {param: 'email', msg: 'Email is required', value: ''} + {param: 'email', msg: 'Invalid Email', value: ''} +] +``` + +## Optional input + +You can use the `optional()` method to skip validation. By default, it only skips validation if the key does not exist on the request object. If you want to skip validation based on the property being falsy (null, undefined, etc), you can pass in `{ checkFalsy: true }`. + +```javascript +req.checkBody('email').optional().isEmail(); +//if there is no error, req.body.email is either undefined or a valid mail. +``` + +## Sanitizer + +#### req.sanitize(); +```javascript + +req.body.comment = 'a comment'; +req.body.username = ' a user '; + +req.sanitize('comment').escape(); // returns 'a <span>comment</span>' +req.sanitize('username').trim(); // returns 'a user' + +console.log(req.body.comment); // 'a <span>comment</span>' +console.log(req.body.username); // 'a user' + +``` + +Sanitizes the specified parameter (using 'dot-notation' or array), the parameter will be updated to the sanitized result. Cannot be chained, and will return the result. See [chriso/validator.js](https://github.com/chriso/validator.js) for available sanitizers, or [add your own](#customsanitizers). + +If a sanitizer takes in params, you would call it like `req.sanitize('reqParam').whitelist(['a', 'b', 'c']);`. + +If the parameter is present in multiple places with the same name e.g. `req.params.comment` & `req.query.comment`, they will all be sanitized. + +#### req.filter(); +Alias for [req.sanitize()](#reqsanitize). + +#### req.sanitizeBody(); +Same as [req.sanitize()](#reqsanitize), but only looks in `req.body`. + +#### req.sanitizeQuery(); +Same as [req.sanitize()](#reqsanitize), but only looks in `req.query`. + +#### req.sanitizeParams(); +Same as [req.sanitize()](#reqsanitize), but only looks in `req.params`. + +#### req.sanitizeHeaders(); +Only sanitizes `req.headers`. This method is not covered by the general `req.sanitize()`. + +### Regex routes + +Express allows you to define regex routes like: + +```javascript +app.get(/\/test(\d+)/, function() {}); +``` + +You can validate the extracted matches like this: + +```javascript +req.assert(0, 'Not a three-digit integer.').len(3, 3).isInt(); +``` + +## Changelog + +See [CHANGELOG.md](CHANGELOG.md) + +## Contributors + +- Christoph Tavan - Wrap the gist in an npm package +- @orfaust - Add `validationErrors()` and nested field support +- @zero21xxx - Added `checkBody` function + +## License + +Copyright (c) 2010 Chris O'Hara , MIT License diff --git a/node_modules/express-validator/index.js b/node_modules/express-validator/index.js new file mode 100644 index 0000000..5250160 --- /dev/null +++ b/node_modules/express-validator/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/express_validator.js'); diff --git a/node_modules/express-validator/lib/express_validator.js b/node_modules/express-validator/lib/express_validator.js new file mode 100644 index 0000000..504805b --- /dev/null +++ b/node_modules/express-validator/lib/express_validator.js @@ -0,0 +1,408 @@ +var validator = require('validator'); +var _ = require('lodash'); +var Promise = require('bluebird'); + +// validators and sanitizers not prefixed with is/to +var additionalValidators = ['contains', 'equals', 'matches']; +var additionalSanitizers = ['trim', 'ltrim', 'rtrim', 'escape', 'stripLow', 'whitelist', 'blacklist', 'normalizeEmail']; + +/** + * Initializes a chain of validators + * + * @class + * @param {(string|string[])} param path to property to validate + * @param {string} failMsg validation failure message + * @param {Request} req request to attach validation errors + * @param {string} location request property to find value (body, params, query, etc.) + * @param {object} options options containing error formatter + */ + +function ValidatorChain(param, failMsg, req, location, options) { + this.errorFormatter = options.errorFormatter; + this.param = param; + this.value = location ? _.get(req[location], param) : undefined; + this.validationErrors = []; + this.failMsg = failMsg; + this.req = req; + this.lastError = null; // used by withMessage to get the values of the last error + return this; +} + + +/** + * Initializes a sanitizer + * + * @class + * @param {(string|string[])} param path to property to sanitize + * @param {[type]} req request to sanitize + * @param {[type]} location request property to find value + */ + +function Sanitizer(param, req, locations) { + this.values = locations.map(function(location) { + return _.get(req[location], param); + }); + + this.req = req; + this.param = param; + this.locations = locations; + return this; +} + +/** + * Adds validation methods to request object via express middleware + * + * @method expressValidator + * @param {object} options + * @return {function} middleware + */ + +var expressValidator = function(options) { + options = options || {}; + var defaults = { + customValidators: {}, + customSanitizers: {}, + errorFormatter: function(param, msg, value) { + return { + param: param, + msg: msg, + value: value + }; + } + }; + + _.defaults(options, defaults); + + // _.set validators and sanitizers as prototype methods on corresponding chains + _.forEach(validator, function(method, methodName) { + if (methodName.match(/^is/) || _.contains(additionalValidators, methodName)) { + ValidatorChain.prototype[methodName] = makeValidator(methodName, validator); + } + + if (methodName.match(/^to/) || _.contains(additionalSanitizers, methodName)) { + Sanitizer.prototype[methodName] = makeSanitizer(methodName, validator); + } + }); + + ValidatorChain.prototype.notEmpty = function() { + return this.isLength(1); + }; + + ValidatorChain.prototype.len = function() { + return this.isLength.apply(this, arguments); + }; + + ValidatorChain.prototype.optional = function(opts) { + opts = opts || {}; + // By default, optional checks if the key exists, but the user can pass in + // checkFalsy: true to skip validation if the property is falsy + var defaults = { + checkFalsy: false + }; + + var options = _.assign(defaults, opts); + + if (options.checkFalsy) { + if (!this.value) { + this.skipValidating = true; + } + } else { + if (this.value === undefined) { + this.skipValidating = true; + } + } + + return this; + }; + + ValidatorChain.prototype.withMessage = function(message) { + if (this.lastError) { + this.validationErrors.pop(); + this.req._validationErrors.pop(); + var error = formatErrors.call(this, this.lastError.param, message, this.lastError.value); + this.validationErrors.push(error); + this.req._validationErrors.push(error); + this.lastError = null; + } + + return this; + }; + + _.forEach(options.customValidators, function(method, customValidatorName) { + ValidatorChain.prototype[customValidatorName] = makeValidator(customValidatorName, options.customValidators); + }); + + _.forEach(options.customSanitizers, function(method, customSanitizerName) { + Sanitizer.prototype[customSanitizerName] = makeSanitizer(customSanitizerName, options.customSanitizers); + }); + + return function(req, res, next) { + var locations = ['body', 'params', 'query']; + + req._validationErrors = []; + req._asyncValidationErrors = []; + req.validationErrors = function(mapped, promisesResolved) { + if (!promisesResolved && req._asyncValidationErrors.length > 0) { + console.warn('WARNING: You have asynchronous validators but you have not used asyncValidateErrors to check for errors.'); + } + + if (mapped && req._validationErrors.length > 0) { + var errors = {}; + req._validationErrors.forEach(function(err) { + errors[err.param] = err; + }); + + return errors; + } + + return req._validationErrors.length > 0 ? req._validationErrors : false; + }; + + req.asyncValidationErrors = function(mapped) { + return new Promise(function(resolve, reject) { + var promises = req._asyncValidationErrors; + Promise.settle(promises).then(function(results) { + + results.forEach(function(result) { + if (result.isRejected()) { req._validationErrors.push(result.reason()); } + }); + + if (req._validationErrors.length > 0) { + return reject(req.validationErrors(mapped, true)); + } + resolve(); + }); + }); + }; + + locations.forEach(function(location) { + req['sanitize' + _.capitalize(location)] = function(param) { + return new Sanitizer(param, req, [location]); + }; + }); + + req.sanitizeHeaders = function(param) { + if (param === 'referrer') { + param = 'referer'; + } + + return new Sanitizer(param, req, ['headers']); + }; + + req.sanitize = function(param) { + return new Sanitizer(param, req, locations); + }; + + locations.forEach(function(location) { + req['check' + _.capitalize(location)] = function(param, failMsg) { + if (_.isPlainObject(param)) { + return validateSchema(param, req, location, options); + } + return new ValidatorChain(param, failMsg, req, location, options); + }; + }); + + req.checkFiles = function(param, failMsg) { + return new ValidatorChain(param, failMsg, req, 'files', options); + }; + + req.checkHeaders = function(param, failMsg) { + if (param === 'referrer') { + param = 'referer'; + } + + return new ValidatorChain(param, failMsg, req, 'headers', options); + }; + + req.check = function(param, failMsg) { + if (_.isPlainObject(param)) { + return validateSchema(param, req, 'any', options); + } + return new ValidatorChain(param, failMsg, req, locate(req, param), options); + }; + + req.filter = req.sanitize; + req.assert = req.check; + req.validate = req.check; + + next(); + }; +}; + +/** + * validate an object using a schema, using following format: + * + * { + * paramName: { + * validatorName: true, + * validator2Name: true + * } + * } + * + * Pass options or a custom error message: + * + * { + * paramName: { + * validatorName: { + * options: ['', ''], + * errorMessage: 'An Error Message' + * } + * } + * } + * + * @method validateSchema + * @param {Object} schema schema of validations + * @param {Request} req request to attach validation errors + * @param {string} location request property to find value (body, params, query, etc.) + * @param {Object} options options containing custom validators & errorFormatter + * @return {object[]} array of errors + */ + +function validateSchema(schema, req, loc, options) { + for (var param in schema) { + loc = loc === 'any' ? locate(req, param) : loc; + var validator = new ValidatorChain(param, null, req, loc, options); + var paramErrorMessage = schema[param].errorMessage; + delete schema[param].errorMessage; + + for (var methodName in schema[param]) { + validator.failMsg = schema[param][methodName].errorMessage || paramErrorMessage || 'Invalid param'; + validator[methodName].apply(validator, schema[param][methodName].options); + } + } +} + +/** + * Validates and handles errors, return instance of itself to allow for chaining + * + * @method makeValidator + * @param {string} methodName + * @param {object} container + * @return {function} + */ + +function makeValidator(methodName, container) { + return function() { + if (this.skipValidating) { + return this; + } + + var args = []; + args.push(this.value); + args = args.concat(Array.prototype.slice.call(arguments)); + + var isValid = container[methodName].apply(container, args); + var error = formatErrors.call(this, this.param, this.failMsg || 'Invalid value', this.value); + + if (isValid.then) { + var promise = isValid.catch(function() { + return Promise.reject(error); + }); + this.req._asyncValidationErrors.push(promise); + } + + if (!isValid) { + this.validationErrors.push(error); + this.req._validationErrors.push(error); + this.lastError = { param: this.param, value: this.value }; + } else { + this.lastError = null; + } + + return this; + }; +} + +/** + * Sanitizes and sets sanitized value on the request, then return instance of itself to allow for chaining + * + * @method makeSanitizer + * @param {string} methodName + * @param {object} container + * @return {function} + */ + +function makeSanitizer(methodName, container) { + return function() { + var _arguments = arguments; + var result; + this.values.forEach(function(value, i) { + if (value != null) { + var args = [value]; + args = args.concat(Array.prototype.slice.call(_arguments)); + result = container[methodName].apply(container, args); + + _.set(this.req[this.locations[i]], this.param, result); + this.values[i] = result; + } + }.bind(this)); + + return result; + }; +} + +/** + * find location of param + * + * @method param + * @param {Request} req express request object + * @param {(string|string[])} name [description] + * @return {string} + */ + +function locate(req, name) { + if (_.get(req.params, name)) { + return 'params'; + } else if (_.has(req.query, name)) { + return 'query'; + } else if (_.has(req.body, name)) { + return 'body'; + } + + return undefined; +} + +/** + * format param output if passed in as array (for nested) + * before calling errorFormatter + * + * @method param + * @param {(string|string[])} param parameter as a string or array + * @param {string} msg + * @param {string} value + * @return {function} + */ +function formatErrors(param, msg, value) { + var formattedParam = formatParamOutput(param); + + return this.errorFormatter(formattedParam, msg, value); +} + +// Convert nested params as array into string for output +// Ex: ['users', '0', 'fields', 'email'] to 'users[0].fields.email' +function formatParamOutput(param) { + if (Array.isArray(param)) { + param = param.reduce(function(prev, curr) { + var part = ''; + if (validator.isInt(curr)) { + part = '[' + curr + ']'; + } else { + if (prev) { + part = '.' + curr; + } else { + part = curr; + } + } + + return prev + part; + }); + } + + return param; +} + +module.exports = expressValidator; +module.exports.validator = validator; +module.exports.utils = { + formatParamOutput: formatParamOutput +}; diff --git a/node_modules/express-validator/node_modules/bluebird/LICENSE b/node_modules/express-validator/node_modules/bluebird/LICENSE new file mode 100644 index 0000000..4182a1e --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2015 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. diff --git a/node_modules/express-validator/node_modules/bluebird/README.md b/node_modules/express-validator/node_modules/bluebird/README.md new file mode 100644 index 0000000..e1447bf --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/README.md @@ -0,0 +1,679 @@ + + Promises/A+ logo + +[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) +[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) + +**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) + +# Introduction + +Bluebird is a fully featured [promise](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance + + + +# Topics + +- [Features](#features) +- [Quick start](#quick-start) +- [API Reference and examples](API.md) +- [Support](#support) +- [What are promises and why should I use them?](#what-are-promises-and-why-should-i-use-them) +- [Questions and issues](#questions-and-issues) +- [Error handling](#error-handling) +- [Development](#development) + - [Testing](#testing) + - [Benchmarking](#benchmarks) + - [Custom builds](#custom-builds) + - [For library authors](#for-library-authors) +- [What is the sync build?](#what-is-the-sync-build) +- [License](#license) +- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets) +- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) +- [Changelog](changelog.md) +- [Optimization guide](#optimization-guide) + +# Features +bluebird logo + +- [Promises A+](http://promisesaplus.com) +- [Synchronous inspection](API.md#synchronous-inspection) +- [Concurrency coordination](API.md#collections) +- [Promisification on steroids](API.md#promisification) +- [Resource management through a parallel of python `with`/C# `using`](API.md#resource-management) +- [Cancellation and timeouts](API.md#cancellation) +- [Parallel for C# `async` and `await`](API.md#generators) +- Mind blowing utilities such as + - [`.bind()`](API.md#binddynamic-thisarg---promise) + - [`.call()`](API.md#callstring-propertyname--dynamic-arg---promise) + - [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) + - [And](API.md#core) [much](API.md#timers) [more](API.md#utility)! +- [Practical debugging solutions and sane defaults](#error-handling) +- [Sick performance](benchmark/) + +
+ +# Quick start + +## Node.js + + npm install bluebird + +Then: + +```js +var Promise = require("bluebird"); +``` + +## Browsers + +There are many ways to use bluebird in browsers: + +- Direct downloads + - Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js) + - Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js) + - Core build [bluebird.core.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.js) + - Core build minified [bluebird.core.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.min.js) +- You may use browserify on the main export +- You may use the [bower](http://bower.io) package. + +When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available. + +A [minimal bluebird browser build](#custom-builds) is ≈38.92KB minified*, 11.65KB gzipped and has no external dependencies. + +*Google Closure Compiler using Simple. + +#### Browser support + +Browsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported. + +[![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov) + +**Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`. + +Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+. + +After quick start, see [API Reference and examples](API.md) + +
+ +# Support + +- Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js) +- IRC: #promises @freenode +- StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird) +- Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open) + +
+ +# What are promises and why should I use them? + +You should use promises to turn this: + +```js +fs.readFile("file.json", function(err, val) { + if( err ) { + console.error("unable to read file"); + } + else { + try { + val = JSON.parse(val); + console.log(val.success); + } + catch( e ) { + console.error("invalid json in file"); + } + } +}); +``` + +Into this: + +```js +fs.readFileAsync("file.json").then(JSON.parse).then(function(val) { + console.log(val.success); +}) +.catch(SyntaxError, function(e) { + console.error("invalid json in file"); +}) +.catch(function(e) { + console.error("unable to read file"); +}); +``` + +*If you are wondering "there is no `readFileAsync` method on `fs` that returns a promise", see [promisification](API.md#promisification)* + +Actually you might notice the latter has a lot in common with code that would do the same using synchronous I/O: + +```js +try { + var val = JSON.parse(fs.readFileSync("file.json")); + console.log(val.success); +} +//Syntax actually not supported in JS but drives the point +catch(SyntaxError e) { + console.error("invalid json in file"); +} +catch(Error e) { + console.error("unable to read file"); +} +``` + +And that is the point - being able to have something that is a lot like `return` and `throw` in synchronous code. + +You can also use promises to improve code that was written with callback helpers: + + +```js +//Copyright Plato http://stackoverflow.com/a/19385911/995876 +//CC BY-SA 2.5 +mapSeries(URLs, function (URL, done) { + var options = {}; + needle.get(URL, options, function (error, response, body) { + if (error) { + return done(error); + } + try { + var ret = JSON.parse(body); + return done(null, ret); + } + catch (e) { + done(e); + } + }); +}, function (err, results) { + if (err) { + console.log(err); + } else { + console.log('All Needle requests successful'); + // results is a 1 to 1 mapping in order of URLs > needle.body + processAndSaveAllInDB(results, function (err) { + if (err) { + return done(err); + } + console.log('All Needle requests saved'); + done(null); + }); + } +}); +``` + +Is more pleasing to the eye when done with promises: + +```js +Promise.promisifyAll(needle); +var options = {}; + +var current = Promise.resolve(); +Promise.map(URLs, function(URL) { + current = current.then(function () { + return needle.getAsync(URL, options); + }); + return current; +}).map(function(responseAndBody){ + return JSON.parse(responseAndBody[1]); +}).then(function (results) { + return processAndSaveAllInDB(results); +}).then(function(){ + console.log('All Needle requests saved'); +}).catch(function (e) { + console.log(e); +}); +``` + +Also promises don't just give you correspondences for synchronous features but can also be used as limited event emitters or callback aggregators. + +More reading: + + - [Promise nuggets](https://promise-nuggets.github.io/) + - [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html) + - [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1) + - [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets) + - [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns) + +# Questions and issues + +The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. + +# Error handling + +This is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled. + +There are two common pragmatic attempts at solving the problem that promise libraries do. + +The more popular one is to have the user explicitly communicate that they are done and any unhandled rejections should be thrown, like so: + +```js +download().then(...).then(...).done(); +``` + +For handling this problem, in my opinion, this is completely unacceptable and pointless. The user must remember to explicitly call `.done` and that cannot be justified when the problem is forgetting to create an error handler in the first place. + +The second approach, which is what bluebird by default takes, is to call a registered handler if a rejection is unhandled by the start of a second turn. The default handler is to write the stack trace to `stderr` or `console.error` in browsers. This is close to what happens with synchronous code - your code doesn't work as expected and you open console and see a stack trace. Nice. + +Of course this is not perfect, if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages. In that case you can use the `.done()` method to signal that any hanging exceptions should be thrown. + +If you want to override the default handler for these possibly unhandled rejections, you can pass yours like so: + +```js +Promise.onPossiblyUnhandledRejection(function(error){ + throw error; +}); +``` + +If you want to also enable long stack traces, call: + +```js +Promise.longStackTraces(); +``` + +right after the library is loaded. + +In node.js use the environment flag `BLUEBIRD_DEBUG`: + +``` +BLUEBIRD_DEBUG=1 node server.js +``` + +to enable long stack traces in all instances of bluebird. + +Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, even after using every trick to optimize them. + +Long stack traces are enabled by default in the debug build. + +#### Expected and unexpected errors + +A practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about. + +Now, Javascript does have a perfectly fine and working way of creating error type hierarchies. It is still quite awkward to use them with the built-in `try-catch` however: + +```js +try { + //code +} +catch(e) { + if( e instanceof WhatIWantError) { + //handle + } + else { + throw e; + } +} +``` + +Without such checking, unexpected errors would be silently swallowed. However, with promises, bluebird brings the future (hopefully) here now and extends the `.catch` to [accept potential error type eligibility](API.md#catchfunction-errorclass-function-handler---promise). + +For instance here it is expected that some evil or incompetent entity will try to crash our server from `SyntaxError` by providing syntactically invalid JSON: + +```js +getJSONFromSomewhere().then(function(jsonString) { + return JSON.parse(jsonString); +}).then(function(object) { + console.log("it was valid json: ", object); +}).catch(SyntaxError, function(e){ + console.log("don't be evil"); +}); +``` + +Here any kind of unexpected error will be automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`. + +Ok, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors? + +Bluebird defines a special error type `OperationalError` (you can get a reference from `Promise.OperationalError`). This type of error is given as rejection reason by promisified methods when +their underlying library gives an untyped, but expected error. Primitives such as strings, and error objects that are directly created like `new Error("database didn't respond")` are considered untyped. + +Example of such library is the node core library `fs`. So if we promisify it, we can catch just the errors we want pretty easily and have programmer errors be redirected to unhandled rejection handler so that we notice them: + +```js +//Read more about promisification in the API Reference: +//API.md +var fs = Promise.promisifyAll(require("fs")); + +fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) { + console.log("Successful json"); +}).catch(SyntaxError, function (e) { + console.error("file contains invalid json"); +}).catch(Promise.OperationalError, function (e) { + console.error("unable to read file, because: ", e.message); +}); +``` + +The last `catch` handler is only invoked when the `fs` module explicitly used the `err` argument convention of async callbacks to inform of an expected error. The `OperationalError` instance will contain the original error in its `.cause` property but it does have a direct copy of the `.message` and `.stack` too. In this code any unexpected error - be it in our code or the `fs` module - would not be caught by these handlers and therefore not swallowed. + +Since a `catch` handler typed to `Promise.OperationalError` is expected to be used very often, it has a neat shorthand: + +```js +.error(function (e) { + console.error("unable to read file, because: ", e.message); +}); +``` + +See [API documentation for `.error()`](API.md#error-rejectedhandler----promise) + +Finally, Bluebird also supports predicate-based filters. If you pass a +predicate function instead of an error type, the predicate will receive +the error as an argument. The return result will be used to determine whether +the error handler should be called. + +Predicates should allow for very fine grained control over caught errors: +pattern matching, error typesets with set operations and many other techniques +can be implemented on top of them. + +Example of using a predicate-based filter: + +```js +var Promise = require("bluebird"); +var request = Promise.promisify(require("request")); + +function clientError(e) { + return e.code >= 400 && e.code < 500; +} + +request("http://www.google.com").then(function(contents){ + console.log(contents); +}).catch(clientError, function(e){ + //A client error like 400 Bad Request happened +}); +``` + +**Danger:** The JavaScript language allows throwing primitive values like strings. Throwing primitives can lead to worse or no stack traces. Primitives [are not exceptions](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/). You should consider always throwing Error objects when handling exceptions. + +
+ +#### How do long stack traces differ from e.g. Q? + +Bluebird attempts to have more elaborate traces. Consider: + +```js +Error.stackTraceLimit = 25; +Q.longStackSupport = true; +Q().then(function outer() { + return Q().then(function inner() { + return Q().then(function evenMoreInner() { + a.b.c.d(); + }).catch(function catcher(e){ + console.error(e.stack); + }); + }) +}); +``` + +You will see + + ReferenceError: a is not defined + at evenMoreInner (:7:13) + From previous event: + at inner (:6:20) + +Compare to: + +```js +Error.stackTraceLimit = 25; +Promise.longStackTraces(); +Promise.resolve().then(function outer() { + return Promise.resolve().then(function inner() { + return Promise.resolve().then(function evenMoreInner() { + a.b.c.d(); + }).catch(function catcher(e){ + console.error(e.stack); + }); + }); +}); +``` + + ReferenceError: a is not defined + at evenMoreInner (:7:13) + From previous event: + at inner (:6:36) + From previous event: + at outer (:5:32) + From previous event: + at :4:21 + at Object.InjectedScript._evaluateOn (:572:39) + at Object.InjectedScript._evaluateAndWrap (:531:52) + at Object.InjectedScript.evaluate (:450:21) + + +A better and more practical example of the differences can be seen in gorgikosev's [debuggability competition](https://github.com/spion/async-compare#debuggability). + +
+ +# Development + +For development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies. + +Install [node](http://nodejs.org/) and [npm](https://npmjs.org/) + + git clone git@github.com:petkaantonov/bluebird.git + cd bluebird + npm install + +## Testing + +To run all tests, run + + node tools/test + +If you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+: + + node-dev --harmony tools/test + +You may specify an individual test file to run with the `--run` script flag: + + node tools/test --run=cancel.js + + +This enables output from the test and may give a better idea where the test is failing. The parameter to `--run` can be any file name located in `test/mocha` folder. + +#### Testing in browsers + +To run the test in a browser instead of node, pass the flag `--browser` to the test tool + + node tools/test --run=cancel.js --browser + +This will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled. + +Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active. + +#### Supported options by the test tool + +The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`. + + - `--run=String` - Which tests to run (or compile when testing in browser). Default `"all"`. Can also be a glob string (relative to ./test/mocha folder). + - `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `"html"` (use `--cover` to use default reporter). + - `--browser` - Whether to compile tests for browsers. Default `false`. + - `--port=Number` - Port where local server is hosted when testing in browser. Default `9999` + - `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`. + - `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`. + - `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`. + - `--js-hint` - Whether to run JSHint on source files. Default `true`. + - `--saucelabs` - Whether to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser. Default `false`. + +## Benchmarks + +To run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too). + +Node 0.11.2+ is required to run the generator examples. + +### 1\. DoxBee sequential + +Currently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections. + +Command: `bench doxbee` + +### 2\. Made-up parallel + +This made-up scenario runs 15 shimmed queries in parallel. + +Command: `bench parallel` + +## Custom builds + +Custom builds for browsers are supported through a command-line utility. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
The following features can be disabled
Feature(s)Command line identifier
.any and Promise.anyany
.race and Promise.racerace
.call and .getcall_get
.filter and Promise.filterfilter
.map and Promise.mapmap
.reduce and Promise.reducereduce
.props and Promise.propsprops
.settle and Promise.settlesettle
.some and Promise.somesome
.nodeifynodeify
Promise.coroutine and Promise.spawngenerators
Progressionprogress
Promisificationpromisify
Cancellationcancel
Timerstimers
Resource managementusing
+ + +Make sure you have cloned the repo somewhere and did `npm install` successfully. + +After that you can run: + + node tools/build --features="core" + + +The above builds the most minimal build you can get. You can add more features separated by spaces from the above list: + + node tools/build --features="core filter map reduce" + +The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features. + +Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build +a full version afterwards (after having taken a copy of the bluebird.js somewhere): + + node tools/build --debug --main --zalgo --browser --minify + +#### Supported options by the build tool + +The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`. + + - `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`. + - `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`. + - `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`. + - `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`. + - `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`. + - `--features=String` - See [custom builds](#custom-builds) + +
+ +## For library authors + +Building a library that depends on bluebird? You should know about a few features. + +If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file +that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains: + +```js + //NOTE the function call right after +module.exports = require("bluebird/js/main/promise")(); +``` + +Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic. + +You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API. + +
+ +## What is the sync build? + +You may now use sync build by: + + var Promise = require("bluebird/zalgo"); + +The sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards. + +The normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility +of stack overflow errors and non-deterministic behavior. + +The sync build skips the async call trampoline completely, e.g code like: + + async.invoke( this.fn, this, val ); + +Appears as this in the sync build: + + this.fn(val); + +This should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism. + +Note that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads. + + +```js +var cache = new Map(); //ES6 Map or DataStructures/Map or whatever... +function getResult(url) { + var resolver = Promise.pending(); + if (cache.has(url)) { + resolver.resolve(cache.get(url)); + } + else { + http.get(url, function(err, content) { + if (err) resolver.reject(err); + else { + cache.set(url, content); + resolver.resolve(content); + } + }); + } + return resolver.promise; +} + + + +//The result of console.log is truly random without async guarantees +function guessWhatItPrints( url ) { + var i = 3; + getResult(url).then(function(){ + i = 4; + }); + console.log(i); +} +``` + +# Optimization guide + +Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome. + +A single cohesive guide compiled from the articles will probably be done eventually. + +# License + +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. diff --git a/node_modules/express-validator/node_modules/bluebird/changelog.md b/node_modules/express-validator/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..5f6e348 --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/changelog.md @@ -0,0 +1,1723 @@ +## 2.10.2 (2015-10-01) + +Features: + + - `.timeout()` now takes a custom error object as second argument + +## 2.10.1 (2015-09-21) + + - Fix error "Cannot promisify an API that has normal methods with 'Async'-suffix" when promisifying certain objects with a custom promisifier + +## 2.10.0 (2015-09-08) + +Features: + + - `Promise.using` can now take the promises-for-resources as an array ([#733](.)). + - Browser builds for minimal core are now hosted on CDN ([#724](.)). + +Bugfixes: + + - Disabling debug mode with `BLUEBIRD_DEBUG=0` environment variable now works ([#719](.)). + - Fix unhandled rejection reporting when passing rejected promise to `.return()` ([#721](.)). + - Fix unbound promise's then handlers being called with wrong `this` value ([#738](.)). + +## 2.9.34 (2015-07-15) + +Bugfixes: + +- Correct domain for .map, .each, .filter, .reduce callbacks ([#701](.)). + - Preserve bound-with-promise promises across the entire chain ([#702](.)). + +## 2.9.33 (2015-07-09) + +Bugfixes: + + - Methods on `Function.prototype` are no longer promisified ([#680](.)). + +## 2.9.32 (2015-07-03) + +Bugfixes: + + - Fix `.return(primitiveValue)` returning a wrapped version of the primitive value when a Node.js domain is active ([#689](.)). + +## 2.9.31 (2015-07-03) + +Bugfixes: + + - Fix Promises/A+ compliance issue regarding circular thenables: the correct behavior is to go into an infinite loop instead of warning with an error (Fixes [#682](.)). + - Fix "(node) warning: possible EventEmitter memory leak detected" ([#661](.)). + - Fix callbacks sometimes being called with a wrong node.js domain ([#664](.)). + - Fix callbacks sometimes not being called at all in iOS 8.1 WebApp mode ([#666](.), [#687](.)). + +## 2.9.30 (2015-06-14) + +Bugfixes: + + - Fix regression with `promisifyAll` not promisifying certain methods + +## 2.9.29 (2015-06-14) + +Bugfixes: + + - Improve `promisifyAll` detection of functions that are class constructors. Fixes mongodb 2.x promisification. + +## 2.9.28 (2015-06-14) + +Bugfixes: + + - Fix handled rejection being reported as unhandled in certain scenarios when using [.all](.) or [Promise.join](.) ([#645](.)) + - Fix custom scheduler not being called in Google Chrome when long stack traces are enabled ([#650](.)) + +## 2.9.27 (2015-05-30) + +Bugfixes: + + - Fix `sinon.useFakeTimers()` breaking scheduler ([#631](.)) + +Misc: + + - Add nw testing facilities (`node tools/test --nw`) + +## 2.9.26 (2015-05-25) + +Bugfixes: + + - Fix crash in NW [#624](.) + - Fix [`.return()`](.) not supporting `undefined` as return value [#627](.) + +## 2.9.25 (2015-04-28) + +Bugfixes: + + - Fix crash in node 0.8 + +## 2.9.24 (2015-04-02) + +Bugfixes: + + - Fix not being able to load multiple bluebird copies introduced in 2.9.22 ([#559](.), [#561](.), [#560](.)). + +## 2.9.23 (2015-04-02) + +Bugfixes: + + - Fix node.js domain propagation ([#521](.)). + +## 2.9.22 (2015-04-02) + + - Fix `.promisify` crashing in phantom JS ([#556](.)) + +## 2.9.21 (2015-03-30) + + - Fix error object's `'stack'`' overwriting causing an error when its defined to be a setter that throws an error ([#552](.)). + +## 2.9.20 (2015-03-29) + +Bugfixes: + + - Fix regression where there is a long delay between calling `.cancel()` and promise actually getting cancelled in Chrome when long stack traces are enabled + +## 2.9.19 (2015-03-29) + +Bugfixes: + + - Fix crashing in Chrome when long stack traces are disabled + +## 2.9.18 (2015-03-29) + +Bugfixes: + + - Fix settlePromises using trampoline + +## 2.9.17 (2015-03-29) + + +Bugfixes: + + - Fix Chrome DevTools async stack traceability ([#542](.)). + +## 2.9.16 (2015-03-28) + +Features: + + - Use setImmediate if available + +## 2.9.15 (2015-03-26) + +Features: + + - Added `.asCallback` alias for `.nodeify`. + +Bugfixes: + + - Don't always use nextTick, but try to pick up setImmediate or setTimeout in NW. Fixes [#534](.), [#525](.) + - Make progress a core feature. Fixes [#535](.) Note that progress has been removed in 3.x - this is only a fix necessary for 2.x custom builds. + +## 2.9.14 (2015-03-12) + +Bugfixes: + + - Always use process.nextTick. Fixes [#525](.) + +## 2.9.13 (2015-02-27) + +Bugfixes: + + - Fix .each, .filter, .reduce and .map callbacks being called synchornously if the input is immediate. ([#513](.)) + +## 2.9.12 (2015-02-19) + +Bugfixes: + + - Fix memory leak introduced in 2.9.0 ([#502](.)) + +## 2.9.11 (2015-02-19) + +Bugfixes: + + - Fix [#503](.) + +## 2.9.10 (2015-02-18) + +Bugfixes: + + - Fix [#501](.) + +## 2.9.9 (2015-02-12) + +Bugfixes: + + - Fix `TypeError: Cannot assign to read only property 'length'` when jsdom has declared a read-only length for all objects to inherit. + +## 2.9.8 (2015-02-10) + +Bugfixes: + + - Fix regression introduced in 2.9.7 where promisify didn't properly dynamically look up methods on `this` + +## 2.9.7 (2015-02-08) + +Bugfixes: + + - Fix `promisify` not retaining custom properties of the function. This enables promisifying the `"request"` module's export function and its methods at the same time. + - Fix `promisifyAll` methods being dependent on `this` when they are not originally dependent on `this`. This enables e.g. passing promisified `fs` functions directly as callbacks without having to bind them to `fs`. + - Fix `process.nextTick` being used over `setImmediate` in node. + +## 2.9.6 (2015-02-02) + +Bugfixes: + + - Node environment detection can no longer be fooled + +## 2.9.5 (2015-02-02) + +Misc: + + - Warn when [`.then()`](.) is passed non-functions + +## 2.9.4 (2015-01-30) + +Bugfixes: + + - Fix [.timeout()](.) not calling `clearTimeout` with the proper handle in node causing the process to wait for unneeded timeout. This was a regression introduced in 2.9.1. + +## 2.9.3 (2015-01-27) + +Bugfixes: + + - Fix node-webkit compatibility issue ([#467](https://github.com/petkaantonov/bluebird/pull/467)) + - Fix long stack trace support in recent firefox versions + +## 2.9.2 (2015-01-26) + +Bugfixes: + + - Fix critical bug regarding to using promisifyAll in browser that was introduced in 2.9.0 ([#466](https://github.com/petkaantonov/bluebird/issues/466)). + +Misc: + + - Add `"browser"` entry point to package.json + +## 2.9.1 (2015-01-24) + +Features: + + - If a bound promise is returned by the callback to [`Promise.method`](#promisemethodfunction-fn---function) and [`Promise.try`](#promisetryfunction-fn--arraydynamicdynamic-arguments--dynamic-ctx----promise), the returned promise will be bound to the same value + +## 2.9.0 (2015-01-24) + +Features: + + - Add [`Promise.fromNode`](API.md#promisefromnodefunction-resolver---promise) + - Add new paramter `value` for [`Promise.bind`](API.md#promisebinddynamic-thisarg--dynamic-value---promise) + +Bugfixes: + + - Fix several issues with [`cancellation`](API.md#cancellation) and [`.bind()`](API.md#binddynamic-thisarg---promise) interoperation when `thisArg` is a promise or thenable + - Fix promises created in [`disposers`](API#disposerfunction-disposer---disposer) not having proper long stack trace context + - Fix [`Promise.join`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) sometimes passing the passed in callback function as the last argument to itself. + +Misc: + + - Reduce minified full browser build file size by not including unused code generation functionality. + - Major internal refactoring related to testing code and source code file layout + +## 2.8.2 (2015-01-20) + +Features: + + - [Global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) are now fired both as DOM3 events and as legacy events in browsers + +## 2.8.1 (2015-01-20) + +Bugfixes: + + - Fix long stack trace stiching consistency when rejected from thenables + +## 2.8.0 (2015-01-19) + +Features: + + - Major debuggability improvements: + - Long stack traces have been re-designed. They are now much more readable, + succint, relevant and consistent across bluebird features. + - Long stack traces are supported now in IE10+ + +## 2.7.1 (2015-01-15) + +Bugfixes: + + - Fix [#447](https://github.com/petkaantonov/bluebird/issues/447) + +## 2.7.0 (2015-01-15) + +Features: + + - Added more context to stack traces originating from coroutines ([#421](https://github.com/petkaantonov/bluebird/issues/421)) + - Implemented [global rejection events](https://github.com/petkaantonov/bluebird/blob/master/API.md#global-rejection-events) ([#428](https://github.com/petkaantonov/bluebird/issues/428), [#357](https://github.com/petkaantonov/bluebird/issues/357)) + - [Custom promisifiers](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-promisifier) are now passed the default promisifier which can be used to add enhancements on top of normal node promisification + - [Promisification filters](https://github.com/petkaantonov/bluebird/blob/master/API.md#option-filter) are now passed `passesDefaultFilter` boolean + +Bugfixes: + + - Fix `.noConflict()` call signature ([#446]()) + - Fix `Promise.method`ified functions being called with `undefined` when they were called with no arguments + +## 2.6.4 (2015-01-12) + +Bugfixes: + + - `OperationalErrors` thrown by promisified functions retain custom properties, such as `.code` and `.path`. + +## 2.6.3 (2015-01-12) + +Bugfixes: + + - Fix [#429](https://github.com/petkaantonov/bluebird/issues/429) + - Fix [#432](https://github.com/petkaantonov/bluebird/issues/432) + - Fix [#433](https://github.com/petkaantonov/bluebird/issues/433) + +## 2.6.2 (2015-01-07) + +Bugfixes: + + - Fix [#426](https://github.com/petkaantonov/bluebird/issues/426) + +## 2.6.1 (2015-01-07) + +Bugfixes: + + - Fixed built browser files not being included in the git tag release for bower + +## 2.6.0 (2015-01-06) + +Features: + + - Significantly improve parallel promise performance and memory usage (+50% faster, -50% less memory) + + +## 2.5.3 (2014-12-30) + +## 2.5.2 (2014-12-29) + +Bugfixes: + + - Fix bug where already resolved promise gets attached more handlers while calling its handlers resulting in some handlers not being called + - Fix bug where then handlers are not called in the same order as they would run if Promises/A+ 2.3.2 was implemented as adoption + - Fix bug where using `Object.create(null)` as a rejection reason would crash bluebird + +## 2.5.1 (2014-12-29) + +Bugfixes: + + - Fix `.finally` throwing null error when it is derived from a promise that is resolved with a promise that is resolved with a promise + +## 2.5.0 (2014-12-28) + +Features: + + - [`.get`](#API.md#https://github.com/petkaantonov/bluebird/blob/master/API.md#getstring-propertyname---promise) now supports negative indexing. + +Bugfixes: + + - Fix bug with `Promise.method` wrapped function returning a promise that never resolves if the function returns a promise that is resolved with another promise + - Fix bug with `Promise.delay` never resolving if the value is a promise that is resolved with another promise + +## 2.4.3 (2014-12-28) + +Bugfixes: + + - Fix memory leak as described in [this Promises/A+ spec issue](https://github.com/promises-aplus/promises-spec/issues/179). + +## 2.4.2 (2014-12-21) + +Bugfixes: + + - Fix bug where spread rejected handler is ignored in case of rejection + - Fix synchronous scheduler passed to `setScheduler` causing infinite loop + +## 2.4.1 (2014-12-20) + +Features: + + - Error messages now have links to wiki pages for additional information + - Promises now clean up all references (to handlers, child promises etc) as soon as possible. + +## 2.4.0 (2014-12-18) + +Features: + + - Better filtering of bluebird internal calls in long stack traces, especially when using minified file in browsers + - Small performance improvements for all collection methods + - Promises now delete references to handlers attached to them as soon as possible + - Additional stack traces are now output on stderr/`console.warn` for errors that are thrown in the process/window from rejected `.done()` promises. See [#411](https://github.com/petkaantonov/bluebird/issues/411) + +## 2.3.11 (2014-10-31) + +Bugfixes: + + - Fix [#371](https://github.com/petkaantonov/bluebird/issues/371), [#373](https://github.com/petkaantonov/bluebird/issues/373) + + +## 2.3.10 (2014-10-28) + +Features: + + - `Promise.method` no longer wraps primitive errors + - `Promise.try` no longer wraps primitive errors + +## 2.3.7 (2014-10-25) + +Bugfixes: + + - Fix [#359](https://github.com/petkaantonov/bluebird/issues/359), [#362](https://github.com/petkaantonov/bluebird/issues/362) and [#364](https://github.com/petkaantonov/bluebird/issues/364) + +## 2.3.6 (2014-10-15) + +Features: + + - Implement [`.reflect()`](API.md#reflect---promisepromiseinspection) + +## 2.3.5 (2014-10-06) + +Bugfixes: + + - Fix issue when promisifying methods whose names contain the string 'args' + +## 2.3.4 (2014-09-27) + + - `P` alias was not declared inside WebWorkers + +## 2.3.3 (2014-09-27) + +Bugfixes: + + - Fix [#318](https://github.com/petkaantonov/bluebird/issues/318), [#314](https://github.com/petkaantonov/bluebird/issues/#314) + +## 2.3.2 (2014-08-25) + +Bugfixes: + + - `P` alias for `Promise` now exists in global scope when using browser builds without a module loader, fixing an issue with firefox extensions + +## 2.3.1 (2014-08-23) + +Features: + + - `.using` can now be used with disposers created from different bluebird copy + +## 2.3.0 (2014-08-13) + +Features: + + - [`.bind()`](API.md#binddynamic-thisarg---promise) and [`Promise.bind()`](API.md#promisebinddynamic-thisarg---promise) now await for the resolution of the `thisArg` if it's a promise or a thenable + +Bugfixes: + + - Fix [#276](https://github.com/petkaantonov/bluebird/issues/276) + +## 2.2.2 (2014-07-14) + + - Fix [#259](https://github.com/petkaantonov/bluebird/issues/259) + +## 2.2.1 (2014-07-07) + + - Fix multiline error messages only showing the first line + +## 2.2.0 (2014-07-07) + +Bugfixes: + + - `.any` and `.some` now consistently reject with RangeError when input array contains too few promises + - Fix iteration bug with `.reduce` when input array contains already fulfilled promises + +## 2.1.3 (2014-06-18) + +Bugfixes: + + - Fix [#235](https://github.com/petkaantonov/bluebird/issues/235) + +## 2.1.2 (2014-06-15) + +Bugfixes: + + - Fix [#232](https://github.com/petkaantonov/bluebird/issues/232) + +## 2.1.1 (2014-06-11) + +## 2.1.0 (2014-06-11) + +Features: + + - Add [`promisifier`](API.md#option-promisifier) option to `Promise.promisifyAll()` + - Improve performance of `.props()` and collection methods when used with immediate values + + +Bugfixes: + + - Fix a bug where .reduce calls the callback for an already visited item + - Fix a bug where stack trace limit is calculated to be too small, which resulted in too short stack traces + +Add undocumented experimental `yieldHandler` option to `Promise.coroutine` + +## 2.0.7 (2014-06-08) +## 2.0.6 (2014-06-07) +## 2.0.5 (2014-06-05) +## 2.0.4 (2014-06-05) +## 2.0.3 (2014-06-05) +## 2.0.2 (2014-06-04) +## 2.0.1 (2014-06-04) + +## 2.0.0 (2014-06-04) + +#What's new in 2.0 + +- [Resource management](API.md#resource-management) - never leak resources again +- [Promisification](API.md#promisification) on steroids - entire modules can now be promisified with one line of code +- [`.map()`](API.md#mapfunction-mapper--object-options---promise), [`.each()`](API.md#eachfunction-iterator---promise), [`.filter()`](API.md#filterfunction-filterer--object-options---promise), [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) reimagined from simple sugar to powerful concurrency coordination tools +- [API Documentation](API.md) has been reorganized and more elaborate examples added +- Deprecated [progression](#progression-migration) and [deferreds](#deferred-migration) +- Improved performance and readability + +Features: + +- Added [`using()`](API.md#promiseusingpromisedisposer-promise-promisedisposer-promise--function-handler---promise) and [`disposer()`](API.md#disposerfunction-disposer---disposer) +- [`.map()`](API.md#mapfunction-mapper--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.map()`](API.md#mapfunction-mapper--object-options---promise) +- [`.filter()`](API.md#filterfunction-filterer--object-options---promise) now calls the handler as soon as items in the input array become fulfilled +- Added a concurrency option to [`.filter()`](API.md#filterfunction-filterer--object-options---promise) +- [`.reduce()`](API.md#reducefunction-reducer--dynamic-initialvalue---promise) now calls the handler as soon as items in the input array become fulfilled, but in-order +- Added [`.each()`](API.md#eachfunction-iterator---promise) +- [`Promise.resolve()`](API.md#promiseresolvedynamic-value---promise) behaves like `Promise.cast`. `Promise.cast` deprecated. +- [Synchronous inspection](API.md#synchronous-inspection): Removed `.inspect()`, added [`.value()`](API.md#value---dynamic) and [`.reason()`](API.md#reason---dynamic) +- [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise) now takes a function as the last argument +- Added [`Promise.setScheduler()`](API.md#promisesetschedulerfunction-scheduler---void) +- [`.cancel()`](API.md#cancelerror-reason---promise) supports a custom cancellation reason +- [`.timeout()`](API.md#timeoutint-ms--string-message---promise) now cancels the promise instead of rejecting it +- [`.nodeify()`](API.md#nodeifyfunction-callback--object-options---promise) now supports passing multiple success results when mapping promises to nodebacks +- Added `suffix` and `filter` options to [`Promise.promisifyAll()`](API.md#promisepromisifyallobject-target--object-options---object) + +Breaking changes: + +- Sparse array holes are not skipped by collection methods but treated as existing elements with `undefined` value +- `.map()` and `.filter()` do not call the given mapper or filterer function in any specific order +- Removed the `.inspect()` method +- Yielding an array from a coroutine is not supported by default. You can use [`coroutine.addYieldHandler()`](API.md#promisecoroutineaddyieldhandlerfunction-handler---void) to configure the old behavior (or any behavior you want). +- [`.any()`](API.md#any---promise) and [`.some()`](API.md#someint-count---promise) no longer use an array as the rejection reason. [`AggregateError`](API.md#aggregateerror) is used instead. + + +## 1.2.4 (2014-04-27) + +Bugfixes: + + - Fix promisifyAll causing a syntax error when a method name is not a valid identifier + - Fix syntax error when es5.js is used in strict mode + +## 1.2.3 (2014-04-17) + +Bugfixes: + + - Fix [#179](https://github.com/petkaantonov/bluebird/issues/179) + +## 1.2.2 (2014-04-09) + +Bugfixes: + + - Promisified methods from promisifyAll no longer call the original method when it is overriden + - Nodeify doesn't pass second argument to the callback if the promise is fulfilled with `undefined` + +## 1.2.1 (2014-03-31) + +Bugfixes: + + - Fix [#168](https://github.com/petkaantonov/bluebird/issues/168) + +## 1.2.0 (2014-03-29) + +Features: + + - New method: [`.value()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#value---dynamic) + - New method: [`.reason()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#reason---dynamic) + - New method: [`Promise.onUnhandledRejectionHandled()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promiseonunhandledrejectionhandledfunction-handler---undefined) + - `Promise.map()`, `.map()`, `Promise.filter()` and `.filter()` start calling their callbacks as soon as possible while retaining a correct order. See [`8085922f`](https://github.com/petkaantonov/bluebird/commit/8085922fb95a9987fda0cf2337598ab4a98dc315). + +Bugfixes: + + - Fix [#165](https://github.com/petkaantonov/bluebird/issues/165) + - Fix [#166](https://github.com/petkaantonov/bluebird/issues/166) + +## 1.1.1 (2014-03-18) + +Bugfixes: + + - [#138](https://github.com/petkaantonov/bluebird/issues/138) + - [#144](https://github.com/petkaantonov/bluebird/issues/144) + - [#148](https://github.com/petkaantonov/bluebird/issues/148) + - [#151](https://github.com/petkaantonov/bluebird/issues/151) + +## 1.1.0 (2014-03-08) + +Features: + + - Implement [`Promise.prototype.tap()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#tapfunction-handler---promise) + - Implement [`Promise.coroutine.addYieldHandler()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisecoroutineaddyieldhandlerfunction-handler---void) + - Deprecate `Promise.prototype.spawn` + +Bugfixes: + + - Fix already rejected promises being reported as unhandled when handled through collection methods + - Fix browserisfy crashing from checking `process.version.indexOf` + +## 1.0.8 (2014-03-03) + +Bugfixes: + + - Fix active domain being lost across asynchronous boundaries in Node.JS 10.xx + +## 1.0.7 (2014-02-25) + +Bugfixes: + + - Fix handled errors being reported + +## 1.0.6 (2014-02-17) + +Bugfixes: + + - Fix bug with unhandled rejections not being reported + when using `Promise.try` or `Promise.method` without + attaching further handlers + +## 1.0.5 (2014-02-15) + +Features: + + - Node.js performance: promisified functions try to check amount of passed arguments in most optimal order + - Node.js promisified functions will have same `.length` as the original function minus one (for the callback parameter) + +## 1.0.4 (2014-02-09) + +Features: + + - Possibly unhandled rejection handler will always get a stack trace, even if the rejection or thrown error was not an error + - Unhandled rejections are tracked per promise, not per error. So if you create multiple branches from a single ancestor and that ancestor gets rejected, each branch with no error handler with the end will cause a possibly unhandled rejection handler invocation + +Bugfixes: + + - Fix unhandled non-writable objects or primitives not reported by possibly unhandled rejection handler + +## 1.0.3 (2014-02-05) + +Bugfixes: + + - [#93](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.2 (2014-02-04) + +Features: + + - Significantly improve performance of foreign bluebird thenables + +Bugfixes: + + - [#88](https://github.com/petkaantonov/bluebird/issues/88) + +## 1.0.1 (2014-01-28) + +Features: + + - Error objects that have property `.isAsync = true` will now be caught by `.error()` + +Bugfixes: + + - Fix TypeError and RangeError shims not working without `new` operator + +## 1.0.0 (2014-01-12) + +Features: + + - `.filter`, `.map`, and `.reduce` no longer skip sparse array holes. This is a backwards incompatible change. + - Like `.map` and `.filter`, `.reduce` now allows returning promises and thenables from the iteration function. + +Bugfixes: + + - [#58](https://github.com/petkaantonov/bluebird/issues/58) + - [#61](https://github.com/petkaantonov/bluebird/issues/61) + - [#64](https://github.com/petkaantonov/bluebird/issues/64) + - [#60](https://github.com/petkaantonov/bluebird/issues/60) + +## 0.11.6-1 (2013-12-29) + +## 0.11.6-0 (2013-12-29) + +Features: + + - You may now return promises and thenables from the filterer function used in `Promise.filter` and `Promise.prototype.filter`. + + - `.error()` now catches additional sources of rejections: + + - Rejections originating from `Promise.reject` + + - Rejections originating from thenables using + the `reject` callback + + - Rejections originating from promisified callbacks + which use the `errback` argument + + - Rejections originating from `new Promise` constructor + where the `reject` callback is called explicitly + + - Rejections originating from `PromiseResolver` where + `.reject()` method is called explicitly + +Bugfixes: + + - Fix `captureStackTrace` being called when it was `null` + - Fix `Promise.map` not unwrapping thenables + +## 0.11.5-1 (2013-12-15) + +## 0.11.5-0 (2013-12-03) + +Features: + + - Improve performance of collection methods + - Improve performance of promise chains + +## 0.11.4-1 (2013-12-02) + +## 0.11.4-0 (2013-12-02) + +Bugfixes: + + - Fix `Promise.some` behavior with arguments like negative integers, 0... + - Fix stack traces of synchronously throwing promisified functions' + +## 0.11.3-0 (2013-12-02) + +Features: + + - Improve performance of generators + +Bugfixes: + + - Fix critical bug with collection methods. + +## 0.11.2-0 (2013-12-02) + +Features: + + - Improve performance of all collection methods + +## 0.11.1-0 (2013-12-02) + +Features: + +- Improve overall performance. +- Improve performance of promisified functions. +- Improve performance of catch filters. +- Improve performance of .finally. + +Bugfixes: + +- Fix `.finally()` rejecting if passed non-function. It will now ignore non-functions like `.then`. +- Fix `.finally()` not converting thenables returned from the handler to promises. +- `.spread()` now rejects if the ultimate value given to it is not spreadable. + +## 0.11.0-0 (2013-12-02) + +Features: + + - Improve overall performance when not using `.bind()` or cancellation. + - Promises are now not cancellable by default. This is backwards incompatible change - see [`.cancellable()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#cancellable---promise) + - [`Promise.delay`](https://github.com/petkaantonov/bluebird/blob/master/API.md#promisedelaydynamic-value-int-ms---promise) + - [`.delay()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#delayint-ms---promise) + - [`.timeout()`](https://github.com/petkaantonov/bluebird/blob/master/API.md#timeoutint-ms--string-message---promise) + +## 0.10.14-0 (2013-12-01) + +Bugfixes: + + - Fix race condition when mixing 3rd party asynchrony. + +## 0.10.13-1 (2013-11-30) + +## 0.10.13-0 (2013-11-30) + +Bugfixes: + + - Fix another bug with progression. + +## 0.10.12-0 (2013-11-30) + +Bugfixes: + + - Fix bug with progression. + +## 0.10.11-4 (2013-11-29) + +## 0.10.11-2 (2013-11-29) + +Bugfixes: + + - Fix `.race()` not propagating bound values. + +## 0.10.11-1 (2013-11-29) + +Features: + + - Improve performance of `Promise.race` + +## 0.10.11-0 (2013-11-29) + +Bugfixes: + + - Fixed `Promise.promisifyAll` invoking property accessors. Only data properties with function values are considered. + +## 0.10.10-0 (2013-11-28) + +Features: + + - Disable long stack traces in browsers by default. Call `Promise.longStackTraces()` to enable them. + +## 0.10.9-1 (2013-11-27) + +Bugfixes: + + - Fail early when `new Promise` is constructed incorrectly + +## 0.10.9-0 (2013-11-27) + +Bugfixes: + + - Promise.props now takes a [thenable-for-collection](https://github.com/petkaantonov/bluebird/blob/f41edac61b7c421608ff439bb5a09b7cffeadcf9/test/mocha/props.js#L197-L217) + - All promise collection methods now reject when a promise-or-thenable-for-collection turns out not to give a collection + +## 0.10.8-0 (2013-11-25) + +Features: + + - All static collection methods take thenable-for-collection + +## 0.10.7-0 (2013-11-25) + +Features: + + - throw TypeError when thenable resolves with itself + - Make .race() and Promise.race() forever pending on empty collections + +## 0.10.6-0 (2013-11-25) + +Bugfixes: + + - Promise.resolve and PromiseResolver.resolve follow thenables too. + +## 0.10.5-0 (2013-11-24) + +Bugfixes: + + - Fix infinite loop when thenable resolves with itself + +## 0.10.4-1 (2013-11-24) + +Bugfixes: + + - Fix a file missing from build. (Critical fix) + +## 0.10.4-0 (2013-11-24) + +Features: + + - Remove dependency of es5-shim and es5-sham when using ES3. + +## 0.10.3-0 (2013-11-24) + +Features: + + - Improve performance of `Promise.method` + +## 0.10.2-1 (2013-11-24) + +Features: + + - Rename PromiseResolver#asCallback to PromiseResolver#callback + +## 0.10.2-0 (2013-11-24) + +Features: + + - Remove memoization of thenables + +## 0.10.1-0 (2013-11-21) + +Features: + + - Add methods `Promise.resolve()`, `Promise.reject()`, `Promise.defer()` and `.resolve()`. + +## 0.10.0-1 (2013-11-17) + +## 0.10.0-0 (2013-11-17) + +Features: + + - Implement `Promise.method()` + - Implement `.return()` + - Implement `.throw()` + +Bugfixes: + + - Fix promises being able to use themselves as resolution or follower value + +## 0.9.11-1 (2013-11-14) + +Features: + + - Implicit `Promise.all()` when yielding an array from generators + +## 0.9.11-0 (2013-11-13) + +Bugfixes: + + - Fix `.spread` not unwrapping thenables + +## 0.9.10-2 (2013-11-13) + +Features: + + - Improve performance of promisified functions on V8 + +Bugfixes: + + - Report unhandled rejections even when long stack traces are disabled + - Fix `.error()` showing up in stack traces + +## 0.9.10-1 (2013-11-05) + +Bugfixes: + + - Catch filter method calls showing in stack traces + +## 0.9.10-0 (2013-11-05) + +Bugfixes: + + - Support primitives in catch filters + +## 0.9.9-0 (2013-11-05) + +Features: + + - Add `Promise.race()` and `.race()` + +## 0.9.8-0 (2013-11-01) + +Bugfixes: + + - Fix bug with `Promise.try` not unwrapping returned promises and thenables + +## 0.9.7-0 (2013-10-29) + +Bugfixes: + + - Fix bug with build files containing duplicated code for promise.js + +## 0.9.6-0 (2013-10-28) + +Features: + + - Improve output of reporting unhandled non-errors + - Implement RejectionError wrapping and `.error()` method + +## 0.9.5-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + +## 0.9.4-1 (2013-10-27) + +## 0.9.4-0 (2013-10-27) + +Bugfixes: + + - Rollback non-working multiple fresh copies feature + +## 0.9.3-0 (2013-10-27) + +Features: + + - Allow fresh copies of the library to be made + - Add more components to customized builds + +## 0.9.2-1 (2013-10-25) + +## 0.9.2-0 (2013-10-25) + +Features: + + - Allow custom builds + +## 0.9.1-1 (2013-10-22) + +Bugfixes: + + - Fix unhandled rethrown exceptions not reported + +## 0.9.1-0 (2013-10-22) + +Features: + + - Improve performance of `Promise.try` + - Extend `Promise.try` to accept arguments and ctx to make it more usable in promisification of synchronous functions. + +## 0.9.0-0 (2013-10-18) + +Features: + + - Implement `.bind` and `Promise.bind` + +Bugfixes: + + - Fix `.some()` when argument is a pending promise that later resolves to an array + +## 0.8.5-1 (2013-10-17) + +Features: + + - Enable process wide long stack traces through BLUEBIRD_DEBUG environment variable + +## 0.8.5-0 (2013-10-16) + +Features: + + - Improve performance of all collection methods + +Bugfixes: + + - Fix .finally passing the value to handlers + - Remove kew from benchmarks due to bugs in the library breaking the benchmark + - Fix some bluebird library calls potentially appearing in stack traces + +## 0.8.4-1 (2013-10-15) + +Bugfixes: + + - Fix .pending() call showing in long stack traces + +## 0.8.4-0 (2013-10-15) + +Bugfixes: + + - Fix PromiseArray and its sub-classes swallowing possibly unhandled rejections + +## 0.8.3-3 (2013-10-14) + +Bugfixes: + + - Fix AMD-declaration using named module. + +## 0.8.3-2 (2013-10-14) + +Features: + + - The mortals that can handle it may now release Zalgo by `require("bluebird/zalgo");` + +## 0.8.3-1 (2013-10-14) + +Bugfixes: + + - Fix memory leak when using the same promise to attach handlers over and over again + +## 0.8.3-0 (2013-10-13) + +Features: + + - Add `Promise.props()` and `Promise.prototype.props()`. They work like `.all()` for object properties. + +Bugfixes: + + - Fix bug with .some returning garbage when sparse arrays have rejections + +## 0.8.2-2 (2013-10-13) + +Features: + + - Improve performance of `.reduce()` when `initialValue` can be synchronously cast to a value + +## 0.8.2-1 (2013-10-12) + +Bugfixes: + + - Fix .npmignore having irrelevant files + +## 0.8.2-0 (2013-10-12) + +Features: + + - Improve performance of `.some()` + +## 0.8.1-0 (2013-10-11) + +Bugfixes: + + - Remove uses of dynamic evaluation (`new Function`, `eval` etc) when strictly not necessary. Use feature detection to use static evaluation to avoid errors when dynamic evaluation is prohibited. + +## 0.8.0-3 (2013-10-10) + +Features: + + - Add `.asCallback` property to `PromiseResolver`s + +## 0.8.0-2 (2013-10-10) + +## 0.8.0-1 (2013-10-09) + +Features: + + - Improve overall performance. Be able to sustain infinite recursion when using promises. + +## 0.8.0-0 (2013-10-09) + +Bugfixes: + + - Fix stackoverflow error when function calls itself "synchronously" from a promise handler + +## 0.7.12-2 (2013-10-09) + +Bugfixes: + + - Fix safari 6 not using `MutationObserver` as a scheduler + - Fix process exceptions interfering with internal queue flushing + +## 0.7.12-1 (2013-10-09) + +Bugfixes: + + - Don't try to detect if generators are available to allow shims to be used + +## 0.7.12-0 (2013-10-08) + +Features: + + - Promisification now consider all functions on the object and its prototype chain + - Individual promisifcation uses current `this` if no explicit receiver is given + - Give better stack traces when promisified callbacks throw or errback primitives such as strings by wrapping them in an `Error` object. + +Bugfixes: + + - Fix runtime APIs throwing synchronous errors + +## 0.7.11-0 (2013-10-08) + +Features: + + - Deprecate `Promise.promisify(Object target)` in favor of `Promise.promisifyAll(Object target)` to avoid confusion with function objects + - Coroutines now throw error when a non-promise is `yielded` + +## 0.7.10-1 (2013-10-05) + +Features: + + - Make tests pass Internet Explorer 8 + +## 0.7.10-0 (2013-10-05) + +Features: + + - Create browser tests + +## 0.7.9-1 (2013-10-03) + +Bugfixes: + + - Fix promise cast bug when thenable fulfills using itself as the fulfillment value + +## 0.7.9-0 (2013-10-03) + +Features: + + - More performance improvements when long stack traces are enabled + +## 0.7.8-1 (2013-10-02) + +Features: + + - Performance improvements when long stack traces are enabled + +## 0.7.8-0 (2013-10-02) + +Bugfixes: + + - Fix promisified methods not turning synchronous exceptions into rejections + +## 0.7.7-1 (2013-10-02) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.7-0 (2013-10-01) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.6-0 (2013-09-29) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.5-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.4-0 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-1 (2013-09-28) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.3-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.2-0 (2013-09-27) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-5 (2013-09-26) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-4 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-3 (2013-09-25) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-2 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-1 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.1-0 (2013-09-24) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-1 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.7.0-0 (2013-09-23) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-2 (2013-09-20) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.5-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-1 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.4-0 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-4 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-3 (2013-09-18) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-2 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-1 (2013-09-16) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.3-0 (2013-09-15) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-1 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.2-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.1-0 (2013-09-14) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.6.0-0 (2013-09-13) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-6 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-5 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-4 (2013-09-12) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-3 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-2 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.9-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-1 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.8-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.7-0 (2013-09-11) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.6-0 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-1 (2013-09-10) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.5-0 (2013-09-09) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-1 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.4-0 (2013-09-08) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.3-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.2-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.1-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.5.0-0 (2013-09-07) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.4.0-0 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0-1 (2013-09-06) + +Features: + + - feature + +Bugfixes: + + - bugfix + +## 0.3.0 (2013-09-06) diff --git a/node_modules/express-validator/node_modules/bluebird/js/browser/bluebird.js b/node_modules/express-validator/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..58a08a3 --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,4887 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2015 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. + * + */ +/** + * bluebird build version 2.10.2 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0; +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); + } +}; + +function AsyncInvokeLater(fn, receiver, arg) { + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + this._normalQueue._pushOne(promise); + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + if (schedule.isStatic) { + schedule = function(fn) { setTimeout(fn, 0); }; + } + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + }); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + fn.call(receiver, arg); + }); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + this._schedule(function() { + promise._settlePromises(); + }); + } + }; +} + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); + fn.call(receiver, arg); + } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); + this._reset(); + this._drainQueue(this._lateQueue); +}; + +Async.prototype._queueTick = function () { + if (!this._isTickUsed) { + this._isTickUsed = true; + this._schedule(this.drainQueues); + } +}; + +Async.prototype._reset = function () { + this._isTickUsed = false; +}; + +module.exports = new Async(); +module.exports.firstLineError = firstLineError; + +},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; + +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; + +var bindingResolved = function(thisArg, context) { + if (this._isPending()) { + this._resolveCallback(context.target); + } +}; + +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; + +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._resolveCallback(target); + } + return ret; +}; + +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; + +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; + +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + + ret._setBoundTo(maybePromise); + if (maybePromise instanceof Promise) { + maybePromise._then(function() { + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._resolveCallback(value); + } + return ret; +}; +}; + +},{}],4:[function(_dereq_,module,exports){ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = _dereq_("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; + +},{"./promise.js":23}],5:[function(_dereq_,module,exports){ +"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 = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!true) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \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: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(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; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; +} + +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); + } + return fn; +} + +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.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 (!true) { + 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) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +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":38}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var errors = _dereq_("./errors.js"); +var async = _dereq_("./async.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; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); +}; + +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + async.enableTrampoline(); + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + 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; +}; +}; + +},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; + } + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; + } + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + 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 warn === "function") { + 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.isSupported = function () { + return typeof captureStackTrace === "function"; +}; + +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } + } + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); + } + } + + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; + +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) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; +}; + +var captureStackTrace = (function stackDetection() { + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; + + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); + }; + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + var err = new Error(); + + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } + + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } + + 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.toString(); + } + return formatNonError(error); + }; + + return null; + +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); + } + }; + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; + } + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); + } + return true; + }; + } +})(); + +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; + } +} + +return CapturedTrace; +}; + +},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = _dereq_("./util.js"); +var errors = _dereq_("./errors.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var keys = _dereq_("./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 = tryCatch(predicate).call(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._boundValue(); + 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 = tryCatch(cb).call(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) { + e = errorObj.e; + break; + } else if (shouldHandle) { + var ret = tryCatch(cb).call(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":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; + +},{}],10:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var getDomain = Promise._getDomain; +var async = _dereq_("./async.js"); +var Warning = _dereq_("./errors.js").Warning; +var util = _dereq_("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +if (util.isNode && process.env["BLUEBIRD_DEBUG"] == 0) debugging = false; + +if (debugging) { + async.disableTrampolineIfNecessary(); +} + +Promise.prototype._ignoreRejections = function() { + this._unsetRejectionIsUnhandled(); + this._bitField = this._bitField | 16777216; +}; + +Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 16777216) !== 0) return; + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +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._setRejectionIsUnhandled = function () { + 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._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + util.notEnumerableProp(error, "stack", + parsed.message + "\n" + parsed.stack.join("\n")); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + var domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? fn : domain.bind(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(); + if (debugging) { + async.disableTrampolineIfNecessary(); + } +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; + +},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var isPrimitive = util.isPrimitive; + +module.exports = function(Promise) { +var returner = function () { + return this; +}; +var thrower = function () { + throw this; +}; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; + +var wrapper = function (value, action) { + if (action === 1) { + return function () { + throw value; + }; + } else if (action === 2) { + return function () { + return value; + }; + } +}; + + +Promise.prototype["return"] = +Promise.prototype.thenReturn = function (value) { + if (value === undefined) return this.then(returnUndefined); + + if (isPrimitive(value)) { + return this._then( + wrapper(value, 2), + undefined, + undefined, + undefined, + undefined + ); + } else if (value instanceof Promise) { + value._ignoreRejections(); + } + return this._then(returner, undefined, undefined, value, undefined); +}; + +Promise.prototype["throw"] = +Promise.prototype.thenThrow = function (reason) { + if (reason === undefined) return this.then(throwUndefined); + + if (isPrimitive(reason)) { + return this._then( + wrapper(reason, 1), + undefined, + undefined, + undefined, + undefined + ); + } + return this._then(thrower, undefined, undefined, reason, undefined); +}; +}; + +},{"./util.js":38}],12:[function(_dereq_,module,exports){ +"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); +}; +}; + +},{}],13:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util.js"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; + +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); + } else { + Error.call(this); + } + } + inherits(SubError, Error); + return SubError; +} + +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); +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]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +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) { + if (!(this instanceof OperationalError)) + return new 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 errorTypes = Error["__BluebirdErrorTypes__"]; +if (!errorTypes) { + errorTypes = Objectfreeze({ + CancellationError: CancellationError, + TimeoutError: TimeoutError, + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError + }); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); +} + +module.exports = { + Error: Error, + TypeError: _TypeError, + RangeError: _RangeError, + CancellationError: errorTypes.CancellationError, + OperationalError: errorTypes.OperationalError, + TimeoutError: errorTypes.TimeoutError, + AggregateError: errorTypes.AggregateError, + Warning: Warning +}; + +},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + 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 ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + 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, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} + +},{}],15:[function(_dereq_,module,exports){ +"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); +}; +}; + +},{}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = _dereq_("./util.js"); +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 (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._boundValue()) + : handler(); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + 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._boundValue(), value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + 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":38}],17:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = _dereq_("./errors.js"); +var TypeError = errors.TypeError; +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; + +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; + } + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; + } + return null; +} + +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + 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) { + return this._promise._rejectCallback(result.e, false, true); + } + + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } +}; + +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; + +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; + +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; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + 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) { + 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; +}; +}; + +},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!true) { +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]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; + } + }; + + var reject = function (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 (!true) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); + } + } 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];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; + +},{"./util.js":38}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var getDomain = Promise._getDomain; +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var PENDING = {}; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(fn); + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + async.invoke(init, this, undefined); +} +util.inherits(MappingPromiseArray, PromiseArray); +function init() {this._init$(undefined, -2);} + +MappingPromiseArray.prototype._init = function () {}; + +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + 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._boundValue(); + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); + if (ret === errorObj) return this._reject(ret.e); + + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + if (limit >= 1) this._inFlight++; + values[index] = PENDING; + return maybePromise._proxyPromiseArray(this, index); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); + } else { + return this._reject(maybePromise._reason()); + } + } + 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(); +}; + + +}; + +},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; + +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + 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 ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; + +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; + +},{"./util.js":38}],21:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; + +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = + tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundValue(); + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundValue(), reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.asCallback = +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, + this, + nodeback + ); + } + return this; +}; +}; + +},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, PromiseArray) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +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._target()._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; + + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(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) { + 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 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); + } + } +}; +}; + +},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){ +"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._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; + +var util = _dereq_("./util.js"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var UNDEFINED_BINDING = {}; +var async = _dereq_("./async.js"); +var errors = _dereq_("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = _dereq_("./captured_trace.js")(); +var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + _dereq_("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = _dereq_("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +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; + if (resolver !== INTERNAL) this._resolveFromResolver(resolver); +} + +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 { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); + } + } + catchInstances.length = j; + fn = arguments[i]; + 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) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + 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.value(); + ret.isFulfilled = true; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); + ret.isRejected = true; + } + return ret; +}; + +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); +}; + +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); +}; + +Promise.is = function (val) { + return val instanceof Promise; +}; + +Promise.fromNode = function(fn) { + var ret = new Promise(INTERNAL); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); + } + return ret; +}; + +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); +}; + +Promise.defer = Promise.pending = function () { + var promise = new Promise(INTERNAL); + return new PromiseResolver(promise); +}; + +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); + if (!(ret instanceof Promise)) { + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); + } + return ret; +}; + +Promise.resolve = Promise.fulfilled = Promise.cast; + +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; +}; + +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; +}; + +Promise.prototype._then = function ( + didFulfill, + didReject, + didProgress, + receiver, + internalData +) { + var haveInternalData = internalData !== undefined; + var ret = haveInternalData ? internalData : new Promise(INTERNAL); + + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); + } + + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); + } + + var callbackIndex = target._addCallbacks(didFulfill, + didReject, + didProgress, + ret, + receiver, + getDomain()); + + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); + } + + return ret; +}; + +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; +}; + +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 & -131072) | + (len & 131071); +}; + +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._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; +}; + +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); +}; + +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; +}; + +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); + } + return ret; +}; + +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; +}; + +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; +}; + +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; +}; + +Promise.prototype._boundValue = function() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +}; + +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, progress, promise, receiver, null); +}; + +Promise.prototype._addCallbacks = function ( + fulfill, + reject, + progress, + promise, + receiver, + domain +) { + var index = this._length(); + + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); + } + + if (index === 0) { + this._promise0 = promise; + if (receiver !== undefined) this._receiver0 = receiver; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : domain.bind(reject); + } + if (typeof progress === "function") { + this._progressHandler0 = + domain === null ? progress : domain.bind(progress); + } + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : domain.bind(reject); + } + if (typeof progress === "function") { + this[base + 2] = + domain === null ? progress : domain.bind(progress); + } + } + this._setLength(index + 1); + return index; +}; + +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); + + if (index >= 131071 - 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) { + this._setProxyHandlers(promiseArray, index); +}; + +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); + } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); + } +}; + +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); + } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); +}; + +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); + + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; + } +}; + +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundValue(), value); + } else { + x = tryCatch(handler).call(receiver, value); + } + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); + } +}; + +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; +}; + +Promise.prototype._followee = function() { + return this._rejectionHandler0; +}; + +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; + +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 && parent._isBound()) { + this._setBoundTo(parent._boundTo); + } +}; + +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 promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() + ? this._fulfillmentHandlerAt(index) + : this._rejectionHandlerAt(index); + + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; + var value = this._settledValue; + var receiver = this._receiverAt(index); + this._clearCallbackDataAtIndex(index); + + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); + } + } + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); + } + } + + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); +}; + +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._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() { + async.settlePromises(this); + this._setSettlePromisesQueued(); +}; + +Promise.prototype._fulfillUnchecked = function (value) { + 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 = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); +}; + +Promise.prototype._rejectUnchecked = function (reason, trace) { + if (reason === this) { + var err = makeSelfResolutionError(); + this._attachExtraTrace(err); + return this._rejectUnchecked(err); + } + this._setRejected(); + this._settledValue = reason; + this._cleanValues(); + + if (this._isFinal()) { + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); + return; + } + + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); + } + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { + this._ensurePossibleRejectionHandled(); + } +}; + +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); + var len = this._length(); + for (var i = 0; i < len; i++) { + this._settlePromiseAt(i); + } +}; + +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + +_dereq_("./progress.js")(Promise, PromiseArray); +_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +_dereq_("./direct_resolve.js")(Promise); +_dereq_("./synchronous_inspection.js")(Promise); +_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./cancel.js')(Promise); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +_dereq_('./nodeify.js')(Promise); +_dereq_('./call_get.js')(Promise); +_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./settle.js')(Promise, PromiseArray); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./promisify.js')(Promise, INTERNAL); +_dereq_('./any.js')(Promise); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./timers.js')(Promise, INTERNAL); +_dereq_('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = _dereq_("./util.js"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + } +} + +function PromiseArray(values) { + var promise = this._promise = new Promise(INTERNAL); + var parent; + if (values instanceof Promise) { + parent = values; + promise._propagateFrom(parent, 1 | 4); + } + 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, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); + 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()) { + values._then( + init, + this._reject, + undefined, + this, + resolveValueIfEmpty + ); + return; + } else { + this._reject(values._reason()); + return; + } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + 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) { + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._ignoreRejections(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); + } + } +}; + +PromiseArray.prototype._isResolved = function () { + return this._values === null; +}; + +PromiseArray.prototype._resolve = function (value) { + this._values = null; + this._promise._fulfill(value); +}; + +PromiseArray.prototype.__hardReject__ = +PromiseArray.prototype._reject = function (reason) { + this._values = null; + this._promise._rejectCallback(reason, false, true); +}; + +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { + this._promise._progress({ + index: index, + value: progressValue + }); +}; + + +PromiseArray.prototype._promiseFulfilled = function (value, index) { + this._values[index] = value; + var totalResolved = ++this._totalResolved; + if (totalResolved >= this._length) { + this._resolve(this._values); + } +}; + +PromiseArray.prototype._promiseRejected = function (reason, index) { + this._totalResolved++; + this._reject(reason); +}; + +PromiseArray.prototype.shouldCopyValues = function () { + return true; +}; + +PromiseArray.prototype.getActualLength = function (len) { + return len; +}; + +return PromiseArray; +}; + +},{"./util.js":38}],25:[function(_dereq_,module,exports){ +"use strict"; +var util = _dereq_("./util.js"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = _dereq_("./errors.js"); +var TimeoutError = errors.TimeoutError; +var OperationalError = errors.OperationalError; +var haveGetters = util.haveGetters; +var es5 = _dereq_("./es5.js"); + +function isUntypedError(obj) { + return obj instanceof Error && + es5.getPrototypeOf(obj) === Error.prototype; +} + +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { + var ret; + if (isUntypedError(obj)) { + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; + } + util.markAsOriginatingFromRejection(obj); + return obj; +} + +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"); + } + this.promise._resolveCallback(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"); + } + this.promise._rejectCallback(reason); +}; + +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"); + } + this.promise._progress(value); +}; + +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); +}; + +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(); +}; + +module.exports = PromiseResolver; + +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = _dereq_("./util.js"); +var nodebackForPromise = _dereq_("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = _dereq_("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyProps = [ + "arity", "length", + "name", + "arguments", + "caller", + "callee", + "prototype", + "__isPromisified__" +]; +var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); + +var defaultFilter = function(name) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + name !== "constructor"; +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} + +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]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} + +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); +}; + +var makeNodePromisifiedEval; +if (!true) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { + var ret = [likelyArgumentCount]; + var min = Math.max(0, likelyArgumentCount - 1 - 3); + for(var i = likelyArgumentCount - 1; i >= min; --i) { + ret.push(i); + } + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { + ret.push(i); + } + return ret; +}; + +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; + +var parameterCount = function(fn) { + if (typeof fn.length === "number") { + return Math.max(Math.min(fn.length, 1023 + 1), 0); + } + return 0; +}; + +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { + var newParameterCount = Math.max(0, parameterCount(fn) - 1); + var argumentOrder = switchCaseArgumentOrder(newParameterCount); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; + + function generateCallForArgumentCount(count) { + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); 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]); + } + + 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] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); + return ret; + } + + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "notEnumerableProp", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + return promise; \n\ + }; \n\ + notEnumerableProp(ret, '__isPromisified__', true); \n\ + return ret; \n\ + " + .replace("Parameters", parameterDeclaration(newParameterCount)) + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + util.notEnumerableProp, + INTERNAL + ); +}; +} + +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } + function promisified() { + var _receiver = receiver; + if (receiver === THIS) _receiver = this; + var promise = new Promise(INTERNAL); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; + var fn = nodebackForPromise(promise); + try { + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); + } + return promise; + } + util.notEnumerableProp(promisified, "__isPromisified__", true); + return promisified; +} + +var makeNodePromisified = canEvaluate + ? makeNodePromisifiedEval + : makeNodePromisifiedClosure; + +function promisifyAll(obj, suffix, filter, promisifier) { + 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; + if (promisifier === makeNodePromisified) { + obj[promisifiedKey] = + makeNodePromisified(key, THIS, key, fn, suffix); + } else { + var promisified = promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + util.notEnumerableProp(promisified, "__isPromisified__", true); + obj[promisifiedKey] = promisified; + } + } + 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; + } + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; +}; + +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); + 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); +}; +}; + + +},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var isObject = util.isObject; +var es5 = _dereq_("./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) { + 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) { + 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); + + 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); +}; +}; + +},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +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) { + 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 () { + 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._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; + +},{}],29:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = _dereq_("./util.js").isArray; + +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; + +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); + + 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, 4 | 1); + } + 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 && !(i in promises)) { + 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); +}; + +}; + +},{"./util.js":38}],30:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var getDomain = Promise._getDomain; +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + 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, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; + } + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(fn); + this._accum = accum; + if (!rejected) async.invoke(init, this, undefined); +} +function init() { + 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) { + 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 = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex= this._length) { + this._resolve(this._values); + } +}; + +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { + var ret = new PromiseInspection(); + ret._bitField = 268435456; + ret._settledValue = value; + this._promiseResolved(index, ret); +}; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { + 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(); +}; +}; + +},{"./util.js":38}],33:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = _dereq_("./util.js"); +var RangeError = _dereq_("./errors.js").RangeError; +var AggregateError = _dereq_("./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) { + this._howMany = count; +}; + +SomePromiseArray.prototype._promiseFulfilled = function (value) { + 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) { + 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(); + 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; +}; + +},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.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 = 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.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.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],35:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + promise._resolveCallback(value); + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} + +return tryConvertToPromise; +}; + +},{"./util.js":38}],36:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var TimeoutError = Promise.TimeoutError; + +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + + var err; + if(!util.isPrimitive(message) && (message instanceof Error)) { + err = message; + } else { + if (typeof message !== "string") { + message = "operation timed out"; + } + err = new TimeoutError(message); + } + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; + +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +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 = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; + +},{"./util.js":38}],37:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = _dereq_("./errors.js").TypeError; + var inherits = _dereq_("./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); + 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), + resources.promise); + } 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, context) { + this._data = data; + this._promise = promise; + this._context = context; + } + + 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().value(); + } + return null; + }; + + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; + + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); + }; + + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); + }; + + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); + } + return value; + } + + 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"); + + var input; + var spreadArgs = true; + if (len === 2 && Array.isArray(arguments[0])) { + input = arguments[0]; + len = input.length; + spreadArgs = false; + } else { + input = arguments; + len--; + } + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = input[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } + } + resources[i] = resource; + } + + var promise = Promise.settle(resources) + .then(inspectionMapper) + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = spreadArgs + ? fn.apply(undefined, vals) : fn.call(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; + return promise; + }; + + 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, createContext()); + } + throw new TypeError(); + }; + +}; + +},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; +var haveGetters = (function(){ + try { + var o = {}; + es5.defineProperty(o, "f", { + get: function () { + return 3; + } + }); + return o.f === 3; + } + catch (e) { + return false; + } + +})(); + +var errorObj = {e: {}}; +var tryCatchTarget; +function tryCatcher() { + try { + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); + } catch (e) { + errorObj.e = e; + return errorObj; + } +} +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; +} + +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 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(safeToString(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; +} + +function thrower(r) { + throw r; +} + +var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; + + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; + + if (es5.isES5) { + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && !isExcludedProto(obj)) { + 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 { + var hasProp = {}.hasOwnProperty; + return function(obj) { + if (isExcludedProto(obj)) return []; + var ret = []; + + /*jshint forin:false */ + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } + } + return ret; + }; + } + +})(); + +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } + } + return false; + } catch (e) { + return false; + } +} + +function toFastProperties(obj) { + /*jshint -W027,-W055,-W031*/ + function f() {} + f.prototype = obj; + var l = 8; + while (l--) new f(); + return obj; + 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; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} + } + } +} + +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, + tryCatch: tryCatch, + inherits: inherits, + withAppended: withAppended, + maybeWrapAsError: maybeWrapAsError, + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + hasDevTools: typeof chrome !== "undefined" && chrome && + typeof chrome.loadTimes === "function", + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" +}; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + +try {throw new Error(); } catch (e) {ret.lastLineError = e;} +module.exports = ret; + +},{"./es5.js":14}]},{},[4])(4) +}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } \ No newline at end of file diff --git a/node_modules/express-validator/node_modules/bluebird/js/browser/bluebird.min.js b/node_modules/express-validator/node_modules/bluebird/js/browser/bluebird.min.js new file mode 100644 index 0000000..9d066dd --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2015 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. + * + */ +/** + * bluebird build version 2.10.2 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers +*/ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,r;return function n(t,e,r){function i(s,a){if(!e[s]){if(!t[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=e[s]={exports:{}};t[s][0].call(l.exports,function(e){var r=t[s][1][e];return i(r?r:e)},l,l.exports,n,t,e,r)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0},r.prototype.throwLater=function(t,e){if(1===arguments.length&&(e=t,t=function(){throw e}),"undefined"!=typeof setTimeout)setTimeout(function(){t(e)},0);else try{this._schedule(function(){t(e)})}catch(r){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")}},l.hasDevTools?(u.isStatic&&(u=function(t){setTimeout(t,0)}),r.prototype.invokeLater=function(t,e,r){this._trampolineEnabled?n.call(this,t,e,r):this._schedule(function(){setTimeout(function(){t.call(e,r)},100)})},r.prototype.invoke=function(t,e,r){this._trampolineEnabled?i.call(this,t,e,r):this._schedule(function(){t.call(e,r)})},r.prototype.settlePromises=function(t){this._trampolineEnabled?o.call(this,t):this._schedule(function(){t._settlePromises()})}):(r.prototype.invokeLater=n,r.prototype.invoke=i,r.prototype.settlePromises=o),r.prototype.invokeFirst=function(t,e,r){this._normalQueue.unshift(t,e,r),this._queueTick()},r.prototype._drainQueue=function(t){for(;t.length()>0;){var e=t.shift();if("function"==typeof e){var r=t.shift(),n=t.shift();e.call(r,n)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=new r,e.exports.firstLineError=s},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(t,e){"use strict";e.exports=function(t,e,r){var n=function(t,e){this._reject(e)},i=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(n,n,null,this,t)},o=function(t,e){this._isPending()&&this._resolveCallback(e.target)},s=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(n){var a=r(n),u=new t(e);u._propagateFrom(this,1);var c=this._target();if(u._setBoundTo(a),a instanceof t){var l={promiseRejectionQueued:!1,promise:u,target:c,bindingPromise:a};c._then(e,i,u._progress,u,l),a._then(o,s,u._progress,u,l)}else u._resolveCallback(c);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=131072|this._bitField,this._boundTo=t):this._bitField=-131073&this._bitField},t.prototype._isBound=function(){return 131072===(131072&this._bitField)},t.bind=function(n,i){var o=r(n),s=new t(e);return s._setBoundTo(o),o instanceof t?o._then(function(){s._resolveCallback(i)},s._reject,s._progress,s,null):s._resolveCallback(i),s}}},{}],4:[function(t,e){"use strict";function r(){try{Promise===i&&(Promise=n)}catch(t){}return i}var n;"undefined"!=typeof Promise&&(n=Promise);var i=t("./promise.js")();i.noConflict=r,e.exports=i},{"./promise.js":23}],5:[function(t,e){"use strict";var r=Object.create;if(r){var n=r(null),i=r(null);n[" size"]=i[" size"]=0}e.exports=function(e){function r(t,r){var n;if(null!=t&&(n=t[r]),"function"!=typeof n){var i="Object "+a.classString(t)+" has no method '"+a.toString(r)+"'";throw new e.TypeError(i)}return n}function n(t){var e=this.pop(),n=r(t,e);return n.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}{var s,a=t("./util.js"),u=a.canEvaluate;a.isIdentifier}e.prototype.call=function(t){for(var e=arguments.length,r=new Array(e-1),i=1;e>i;++i)r[i-1]=arguments[i];return r.push(t),this._then(n,void 0,void 0,r,void 0)},e.prototype.get=function(t){var e,r="number"==typeof t;if(r)e=o;else if(u){var n=s(t);e=null!==n?n:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util.js":38}],6:[function(t,e){"use strict";e.exports=function(e){var r=t("./errors.js"),n=t("./async.js"),i=r.CancellationError;e.prototype._cancel=function(t){if(!this.isCancellable())return this;for(var e,r=this;void 0!==(e=r._cancellationParent)&&e.isCancellable();)r=e;this._unsetCancellable(),r._target()._rejectCallback(t,!1,!0)},e.prototype.cancel=function(t){return this.isCancellable()?(void 0===t&&(t=new i),n.invokeLater(this._cancel,this,t),this):this},e.prototype.cancellable=function(){return this._cancellable()?this:(n.enableTrampoline(),this._setCancellable(),this._cancellationParent=void 0,this)},e.prototype.uncancellable=function(){var t=this.then();return t._unsetCancellable(),t},e.prototype.fork=function(t,e,r){var n=this._then(t,e,r,void 0,void 0);return n._setCancellable(),n._cancellationParent=void 0,n}}},{"./async.js":2,"./errors.js":13}],7:[function(t,e){"use strict";e.exports=function(){function e(t){this._parent=t;var r=this._length=1+(void 0===t?0:t._length);j(this,e),r>32&&this.uncycle()}function r(t,e){for(var r=0;r=0;--a)if(n[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=n[a];if(e[i]!==u)break;e.pop(),i--}e=n}}function o(t){for(var e=[],r=0;r0&&(e=e.slice(r)),e}function a(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t.toString();var r=/\[object [a-zA-Z0-9$_]+\]/;if(r.test(e))try{var n=JSON.stringify(t);e=n}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+u(e)+">, no stack trace)"}function u(t){var e=41;return t.lengtht)){for(var e=[],r={},n=0,i=this;void 0!==i;++n)e.push(i),i=i._parent;t=this._length=n;for(var n=t-1;n>=0;--n){var o=e[n].stack;void 0===r[o]&&(r[o]=n)}for(var n=0;t>n;++n){var s=e[n].stack,a=r[s];if(void 0!==a&&a!==n){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[n]._parent=void 0,e[n]._length=1;var u=n>0?e[n-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,l=n-2;l>=0;--l)e[l]._length=c,c++;return}}}},e.prototype.parent=function(){return this._parent},e.prototype.hasParent=function(){return void 0!==this._parent},e.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var s=e.parseStackAndMessage(t),a=s.message,u=[s.stack],c=this;void 0!==c;)u.push(o(c.stack.split("\n"))),c=c._parent;i(u),n(u),p.notEnumerableProp(t,"stack",r(a,u)),p.notEnumerableProp(t,"__stackCleaned__",!0)}},e.parseStackAndMessage=function(t){var e=t.stack,r=t.toString();return e="string"==typeof e&&e.length>0?s(t):[" (No stack trace)"],{message:r,stack:o(e)}},e.formatAndLogError=function(t,e){if("undefined"!=typeof console){var r;if("object"==typeof t||"function"==typeof t){var n=t.stack;r=e+d(n,t)}else r=e+String(t);"function"==typeof l?l(r):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}},e.unhandledRejection=function(t){e.formatAndLogError(t,"^--- With additional stack trace: ")},e.isSupported=function(){return"function"==typeof j},e.fireRejectionEvent=function(t,r,n,i){var o=!1;try{"function"==typeof r&&(o=!0,"rejectionHandled"===t?r(i):r(n,i))}catch(s){h.throwLater(s)}var a=!1;try{a=b(t,n,i)}catch(s){a=!0,h.throwLater(s)}var u=!1;if(m)try{u=m(t.toLowerCase(),{reason:n,promise:i})}catch(s){u=!0,h.throwLater(s)}a||o||u||"unhandledRejection"!==t||e.formatAndLogError(n,"Unhandled rejection ")};var y=function(){return!1},g=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;e.setBounds=function(t,r){if(e.isSupported()){for(var n,i,o=t.stack.split("\n"),s=r.stack.split("\n"),a=-1,u=-1,l=0;la||0>u||!n||!i||n!==i||a>=u||(y=function(t){if(f.test(t))return!0;var e=c(t);return e&&e.fileName===n&&a<=e.line&&e.line<=u?!0:!1})}};var m,j=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():a(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit=Error.stackTraceLimit+6,_=t,d=e;var r=Error.captureStackTrace;return y=function(t){return f.test(t)},function(t,e){Error.stackTraceLimit=Error.stackTraceLimit+6,r(t,e),Error.stackTraceLimit=Error.stackTraceLimit-6}}var n=new Error;if("string"==typeof n.stack&&n.stack.split("\n")[0].indexOf("stackDetection@")>=0)return _=/@/,d=e,v=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in n||!i||"number"!=typeof Error.stackTraceLimit?(d=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?a(e):e.toString()},null):(_=t,d=e,function(t){Error.stackTraceLimit=Error.stackTraceLimit+6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit=Error.stackTraceLimit-6})}([]),b=function(){if(p.isNode)return function(t,e,r){return"rejectionHandled"===t?process.emit(t,r):process.emit(t,e,r)};var t=!1,e=!0;try{var r=new self.CustomEvent("test");t=r instanceof CustomEvent}catch(n){}if(!t)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(n){e=!1}e&&(m=function(e,r){var n;return t?n=new self.CustomEvent(e,{detail:r,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(n=document.createEvent("CustomEvent"),n.initCustomEvent(e,!1,!0,r)),n?!self.dispatchEvent(n):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,r){var n=o[t],i=self[n];return i?("rejectionHandled"===t?i.call(self,r):i.call(self,e,r),!0):!1}}();return"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(l=function(t){console.warn(t)},p.isNode&&process.stderr.isTTY?l=function(t){process.stderr.write(""+t+"\n")}:p.isNode||"string"!=typeof(new Error).stack||(l=function(t){console.warn("%c"+t,"color: red")})),e}},{"./async.js":2,"./util.js":38}],8:[function(t,e){"use strict";e.exports=function(e){function r(t,e,r){this._instances=t,this._callback=e,this._promise=r}function n(t,e){var r={},n=s(t).call(r,e);if(n===a)return n;var i=u(r);return i.length?(a.e=new c("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"),a):n}var i=t("./util.js"),o=t("./errors.js"),s=i.tryCatch,a=i.errorObj,u=t("./es5.js").keys,c=o.TypeError;return r.prototype.doFilter=function(t){for(var r=this._callback,i=this._promise,o=i._boundValue(),u=0,c=this._instances.length;c>u;++u){var l=this._instances[u],h=l===Error||null!=l&&l.prototype instanceof Error;if(h&&t instanceof l){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}if("function"==typeof l&&!h){var f=n(l,t);if(f===a){t=a.e;break}if(f){var p=s(r).call(o,t);return p===a?(e.e=p.e,e):p}}}return e.e=t,e},r}},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(t,e){"use strict";e.exports=function(t,e,r){function n(){this._trace=new e(o())}function i(){return r()?new n:void 0}function o(){var t=s.length-1;return t>=0?s[t]:void 0}var s=[];return n.prototype._pushContext=function(){r()&&void 0!==this._trace&&s.push(this._trace)},n.prototype._popContext=function(){r()&&void 0!==this._trace&&s.pop()},t.prototype._peekContext=o,t.prototype._pushContext=n.prototype._pushContext,t.prototype._popContext=n.prototype._popContext,i}},{}],10:[function(t,e){"use strict";e.exports=function(e,r){var n,i,o=e._getDomain,s=t("./async.js"),a=t("./errors.js").Warning,u=t("./util.js"),c=u.canAttachTrace,l=!1||u.isNode&&(!!process.env.BLUEBIRD_DEBUG||"development"===process.env.NODE_ENV);return u.isNode&&0==process.env.BLUEBIRD_DEBUG&&(l=!1),l&&s.disableTrampolineIfNecessary(),e.prototype._ignoreRejections=function(){this._unsetRejectionIsUnhandled(),this._bitField=16777216|this._bitField},e.prototype._ensurePossibleRejectionHandled=function(){0===(16777216&this._bitField)&&(this._setRejectionIsUnhandled(),s.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){r.fireRejectionEvent("rejectionHandled",n,void 0,this)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._getCarriedStackTrace()||this._settledValue;this._setUnhandledRejectionIsNotified(),r.fireRejectionEvent("unhandledRejection",i,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},e.prototype._setCarriedStackTrace=function(t){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=t},e.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},e.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},e.prototype._captureStackTrace=function(){return l&&(this._trace=new r(this._peekContext())),this},e.prototype._attachExtraTrace=function(t,e){if(l&&c(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var i=r.parseStackAndMessage(t);u.notEnumerableProp(t,"stack",i.message+"\n"+i.stack.join("\n")),u.notEnumerableProp(t,"__stackCleaned__",!0)}}},e.prototype._warn=function(t){var e=new a(t),n=this._peekContext();if(n)n.attachExtraTrace(e);else{var i=r.parseStackAndMessage(e);e.stack=i.message+"\n"+i.stack.join("\n")}r.formatAndLogError(e,"")},e.onPossiblyUnhandledRejection=function(t){var e=o();i="function"==typeof t?null===e?t:e.bind(t):void 0},e.onUnhandledRejectionHandled=function(t){var e=o();n="function"==typeof t?null===e?t:e.bind(t):void 0},e.longStackTraces=function(){if(s.haveItemsQueued()&&l===!1)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/DT1qyG\n");l=r.isSupported(),l&&s.disableTrampolineIfNecessary()},e.hasLongStackTraces=function(){return l&&r.isSupported()},r.isSupported()||(e.longStackTraces=function(){},l=!1),function(){return l}}},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(t,e){"use strict";var r=t("./util.js"),n=r.isPrimitive;e.exports=function(t){var e=function(){return this},r=function(){throw this},i=function(){},o=function(){throw void 0},s=function(t,e){return 1===e?function(){throw t}:2===e?function(){return t}:void 0};t.prototype["return"]=t.prototype.thenReturn=function(r){return void 0===r?this.then(i):n(r)?this._then(s(r,2),void 0,void 0,void 0,void 0):(r instanceof t&&r._ignoreRejections(),this._then(e,void 0,void 0,r,void 0))},t.prototype["throw"]=t.prototype.thenThrow=function(t){return void 0===t?this.then(o):n(t)?this._then(s(t,1),void 0,void 0,void 0,void 0):this._then(r,void 0,void 0,t,void 0)}}},{"./util.js":38}],12:[function(t,e){"use strict";e.exports=function(t,e){var r=t.reduce;t.prototype.each=function(t){return r(this,t,null,e)},t.each=function(t,n){return r(t,n,null,e)}}},{}],13:[function(t,e){"use strict";function r(t,e){function r(n){return this instanceof r?(l(this,"message","string"==typeof n?n:e),l(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new r(n)}return c(r,Error),r}function n(t){return this instanceof n?(l(this,"name","OperationalError"),l(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(l(this,"message",t.message),l(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new n(t)}var i,o,s=t("./es5.js"),a=s.freeze,u=t("./util.js"),c=u.inherits,l=u.notEnumerableProp,h=r("Warning","warning"),p=r("CancellationError","cancellation error"),f=r("TimeoutError","timeout error"),_=r("AggregateError","aggregate error");try{i=TypeError,o=RangeError}catch(d){i=r("TypeError","type error"),o=r("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y0&&"function"==typeof arguments[e]){t=arguments[e];var n}for(var i=arguments.length,o=new Array(i),s=0;i>s;++s)o[s]=arguments[s];t&&o.pop();var n=new r(o).promise();return void 0!==t?n.spread(t):n}}},{"./util.js":38}],19:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,e,r,n){this.constructor$(t),this._promise._captureStackTrace();var i=c();this._callback=null===i?e:i.bind(e),this._preservedValues=n===o?new Array(this.length()):null,this._limit=r,this._inFlight=0,this._queue=r>=1?[]:d,l.invoke(a,this,void 0)}function a(){this._init$(void 0,-2)}function u(t,e,r,n){var i="object"==typeof r&&null!==r?r.concurrency:0;return i="number"==typeof i&&isFinite(i)&&i>=1?i:0,new s(t,e,i,n)}var c=e._getDomain,l=t("./async.js"),h=t("./util.js"),p=h.tryCatch,f=h.errorObj,_={},d=[];h.inherits(s,r),s.prototype._init=function(){},s.prototype._promiseFulfilled=function(t,r){var n=this._values,o=this.length(),s=this._preservedValues,a=this._limit;if(n[r]===_){if(n[r]=t,a>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return}else{if(a>=1&&this._inFlight>=a)return n[r]=t,void this._queue.push(r);null!==s&&(s[r]=t);var u=this._callback,c=this._promise._boundValue();this._promise._pushContext();var l=p(u).call(c,t,r,o);if(this._promise._popContext(),l===f)return this._reject(l.e);var h=i(l,this._promise);if(h instanceof e){if(h=h._target(),h._isPending())return a>=1&&this._inFlight++,n[r]=_,h._proxyPromiseArray(this,r);if(!h._isFulfilled())return this._reject(h._reason());l=h._value()}n[r]=l}var d=++this._totalResolved;d>=o&&(null!==s?this._filter(n,s):this._resolve(n))},s.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,r=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(n[i++]=e[o]);n.length=i,this._resolve(n)},s.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return"function"!=typeof t?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(this,t,e,null).promise()},e.map=function(t,e,r,i){return"function"!=typeof e?n("fn must be a function\n\n See http://goo.gl/916lJJ\n"):u(t,e,r,i).promise()}}},{"./async.js":2,"./util.js":38}],20:[function(t,e){"use strict";e.exports=function(e,r,n,i){var o=t("./util.js"),s=o.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("fn must be a function\n\n See http://goo.gl/916lJJ\n");return function(){var n=new e(r);n._captureStackTrace(),n._pushContext();var i=s(t).apply(this,arguments);return n._popContext(),n._resolveFromSyncValue(i),n}},e.attempt=e["try"]=function(t,n,a){if("function"!=typeof t)return i("fn must be a function\n\n See http://goo.gl/916lJJ\n");var u=new e(r);u._captureStackTrace(),u._pushContext();var c=o.isArray(n)?s(t).apply(a,n):s(t).call(a,n);return u._popContext(),u._resolveFromSyncValue(c),u},e.prototype._resolveFromSyncValue=function(t){t===o.errorObj?this._rejectCallback(t.e,!1,!0):this._resolveCallback(t,!0)}}},{"./util.js":38}],21:[function(t,e){"use strict";e.exports=function(e){function r(t,e){var r=this;if(!o.isArray(t))return n.call(r,t,e);var i=a(e).apply(r._boundValue(),[null].concat(t));i===u&&s.throwLater(i.e)}function n(t,e){var r=this,n=r._boundValue(),i=void 0===t?a(e).call(n,null):a(e).call(n,null,t);i===u&&s.throwLater(i.e)}function i(t,e){var r=this;if(!t){var n=r._target(),i=n._getCarriedStackTrace();i.cause=t,t=i}var o=a(e).call(r._boundValue(),t);o===u&&s.throwLater(o.e)}var o=t("./util.js"),s=t("./async.js"),a=o.tryCatch,u=o.errorObj;e.prototype.asCallback=e.prototype.nodeify=function(t,e){if("function"==typeof t){var o=n;void 0!==e&&Object(e).spread&&(o=r),this._then(o,i,void 0,this,t)}return this}}},{"./async.js":2,"./util.js":38}],22:[function(t,e){"use strict";e.exports=function(e,r){var n=t("./util.js"),i=t("./async.js"),o=n.tryCatch,s=n.errorObj;e.prototype.progressed=function(t){return this._then(void 0,void 0,t,void 0,void 0)},e.prototype._progress=function(t){this._isFollowingOrFulfilledOrRejected()||this._target()._progressUnchecked(t)},e.prototype._progressHandlerAt=function(t){return 0===t?this._progressHandler0:this[(t<<2)+t-5+2]},e.prototype._doProgressWith=function(t){var r=t.value,i=t.handler,a=t.promise,u=t.receiver,c=o(i).call(u,r);if(c===s){if(null!=c.e&&"StopProgressPropagation"!==c.e.name){var l=n.canAttachTrace(c.e)?c.e:new Error(n.toString(c.e));a._attachExtraTrace(l),a._progress(c.e)}}else c instanceof e?c._then(a._progress,null,null,a,void 0):a._progress(c)},e.prototype._progressUnchecked=function(t){for(var n=this._length(),o=this._progress,s=0;n>s;s++){var a=this._progressHandlerAt(s),u=this._promiseAt(s);if(u instanceof e)"function"==typeof a?i.invoke(this._doProgressWith,this,{handler:a,promise:u,receiver:this._receiverAt(s),value:t}):i.invoke(o,u,t);else{var c=this._receiverAt(s);"function"==typeof a?a.call(c,t,u):c instanceof r&&!c._isResolved()&&c._promiseProgressed(t,u)}}}}},{"./async.js":2,"./util.js":38}],23:[function(t,e){"use strict";e.exports=function(){function e(t){if("function"!=typeof t)throw new h("the promise constructor requires a resolver function\n\n See http://goo.gl/EC22Yn\n");if(this.constructor!==e)throw new h("the promise constructor cannot be invoked directly\n\n See http://goo.gl/KsIlge\n");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._progressHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,t!==p&&this._resolveFromResolver(t)}function r(t){var r=new e(p);r._fulfillmentHandler0=t,r._rejectionHandler0=t,r._progressHandler0=t,r._promise0=t,r._receiver0=t,r._settledValue=t}var n,i=function(){return new h("circular promise resolution chain\n\n See http://goo.gl/LhFpo0\n")},o=function(){return new e.PromiseInspection(this._target())},s=function(t){return e.reject(new h(t))},a=t("./util.js");n=a.isNode?function(){var t=process.domain;return void 0===t&&(t=null),t}:function(){return null},a.notEnumerableProp(e,"_getDomain",n);var u={},c=t("./async.js"),l=t("./errors.js"),h=e.TypeError=l.TypeError;e.RangeError=l.RangeError,e.CancellationError=l.CancellationError,e.TimeoutError=l.TimeoutError,e.OperationalError=l.OperationalError,e.RejectionError=l.OperationalError,e.AggregateError=l.AggregateError;var p=function(){},f={},_={e:null},d=t("./thenables.js")(e,p),v=t("./promise_array.js")(e,p,d,s),y=t("./captured_trace.js")(),g=t("./debuggability.js")(e,y),m=t("./context.js")(e,y,g),j=t("./catch_filter.js")(_),b=t("./promise_resolver.js"),w=b._nodebackForPromise,k=a.errorObj,E=a.tryCatch;return e.prototype.toString=function(){return"[object Promise]"},e.prototype.caught=e.prototype["catch"]=function(t){var r=arguments.length;if(r>1){var n,i=new Array(r-1),o=0;for(n=0;r-1>n;++n){var s=arguments[n];if("function"!=typeof s)return e.reject(new h("Catch filter must inherit from Error or be a simple predicate function\n\n See http://goo.gl/o84o68\n"));i[o++]=s}i.length=o,t=arguments[n];var a=new j(i,t,this);return this._then(void 0,a.doFilter,void 0,a,void 0)}return this._then(void 0,t,void 0,void 0,void 0)},e.prototype.reflect=function(){return this._then(o,o,void 0,this,void 0)},e.prototype.then=function(t,e,r){if(g()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+a.classString(t);arguments.length>1&&(n+=", "+a.classString(e)),this._warn(n)}return this._then(t,e,r,void 0,void 0)},e.prototype.done=function(t,e,r){var n=this._then(t,e,r,void 0,void 0); +n._setIsFinal()},e.prototype.spread=function(t,e){return this.all()._then(t,e,void 0,f,void 0)},e.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable()},e.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},e.prototype.all=function(){return new v(this).promise()},e.prototype.error=function(t){return this.caught(a.originatesFromRejection,t)},e.is=function(t){return t instanceof e},e.fromNode=function(t){var r=new e(p),n=E(t)(w(r));return n===k&&r._rejectCallback(n.e,!0,!0),r},e.all=function(t){return new v(t).promise()},e.defer=e.pending=function(){var t=new e(p);return new b(t)},e.cast=function(t){var r=d(t);if(!(r instanceof e)){var n=r;r=new e(p),r._fulfillUnchecked(n)}return r},e.resolve=e.fulfilled=e.cast,e.reject=e.rejected=function(t){var r=new e(p);return r._captureStackTrace(),r._rejectCallback(t,!0),r},e.setScheduler=function(t){if("function"!=typeof t)throw new h("fn must be a function\n\n See http://goo.gl/916lJJ\n");var e=c._schedule;return c._schedule=t,e},e.prototype._then=function(t,r,i,o,s){var a=void 0!==s,u=a?s:new e(p);a||(u._propagateFrom(this,5),u._captureStackTrace());var l=this._target();l!==this&&(void 0===o&&(o=this._boundTo),a||u._setIsMigrated());var h=l._addCallbacks(t,r,i,u,o,n());return l._isResolved()&&!l._isSettlePromisesQueued()&&c.invoke(l._settlePromiseAtPostResolution,l,h),u},e.prototype._settlePromiseAtPostResolution=function(t){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),this._settlePromiseAt(t)},e.prototype._length=function(){return 131071&this._bitField},e.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},e.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},e.prototype._setLength=function(t){this._bitField=-131072&this._bitField|131071&t},e.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},e.prototype._setRejected=function(){this._bitField=134217728|this._bitField},e.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},e.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},e.prototype._isFinal=function(){return(33554432&this._bitField)>0},e.prototype._cancellable=function(){return(67108864&this._bitField)>0},e.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},e.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},e.prototype._setIsMigrated=function(){this._bitField=4194304|this._bitField},e.prototype._unsetIsMigrated=function(){this._bitField=-4194305&this._bitField},e.prototype._isMigrated=function(){return(4194304&this._bitField)>0},e.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[5*t-5+4];return e===u?void 0:void 0===e&&this._isBound()?this._boundValue():e},e.prototype._promiseAt=function(t){return 0===t?this._promise0:this[5*t-5+3]},e.prototype._fulfillmentHandlerAt=function(t){return 0===t?this._fulfillmentHandler0:this[5*t-5+0]},e.prototype._rejectionHandlerAt=function(t){return 0===t?this._rejectionHandler0:this[5*t-5+1]},e.prototype._boundValue=function(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t},e.prototype._migrateCallbacks=function(t,r){var n=t._fulfillmentHandlerAt(r),i=t._rejectionHandlerAt(r),o=t._progressHandlerAt(r),s=t._promiseAt(r),a=t._receiverAt(r);s instanceof e&&s._setIsMigrated(),void 0===a&&(a=u),this._addCallbacks(n,i,o,s,a,null)},e.prototype._addCallbacks=function(t,e,r,n,i,o){var s=this._length();if(s>=131066&&(s=0,this._setLength(0)),0===s)this._promise0=n,void 0!==i&&(this._receiver0=i),"function"!=typeof t||this._isCarryingStackTrace()||(this._fulfillmentHandler0=null===o?t:o.bind(t)),"function"==typeof e&&(this._rejectionHandler0=null===o?e:o.bind(e)),"function"==typeof r&&(this._progressHandler0=null===o?r:o.bind(r));else{var a=5*s-5;this[a+3]=n,this[a+4]=i,"function"==typeof t&&(this[a+0]=null===o?t:o.bind(t)),"function"==typeof e&&(this[a+1]=null===o?e:o.bind(e)),"function"==typeof r&&(this[a+2]=null===o?r:o.bind(r))}return this._setLength(s+1),s},e.prototype._setProxyHandlers=function(t,e){var r=this._length();if(r>=131066&&(r=0,this._setLength(0)),0===r)this._promise0=e,this._receiver0=t;else{var n=5*r-5;this[n+3]=e,this[n+4]=t}this._setLength(r+1)},e.prototype._proxyPromiseArray=function(t,e){this._setProxyHandlers(t,e)},e.prototype._resolveCallback=function(t,r){if(!this._isFollowingOrFulfilledOrRejected()){if(t===this)return this._rejectCallback(i(),!1,!0);var n=d(t,this);if(!(n instanceof e))return this._fulfill(t);var o=1|(r?4:0);this._propagateFrom(n,o);var s=n._target();if(s._isPending()){for(var a=this._length(),u=0;a>u;++u)s._migrateCallbacks(this,u);this._setFollowing(),this._setLength(0),this._setFollowee(s)}else s._isFulfilled()?this._fulfillUnchecked(s._value()):this._rejectUnchecked(s._reason(),s._getCarriedStackTrace())}},e.prototype._rejectCallback=function(t,e,r){r||a.markAsOriginatingFromRejection(t);var n=a.ensureErrorObject(t),i=n===t;this._attachExtraTrace(n,e?i:!1),this._reject(t,i?void 0:n)},e.prototype._resolveFromResolver=function(t){var e=this;this._captureStackTrace(),this._pushContext();var r=!0,n=E(t)(function(t){null!==e&&(e._resolveCallback(t),e=null)},function(t){null!==e&&(e._rejectCallback(t,r),e=null)});r=!1,this._popContext(),void 0!==n&&n===k&&null!==e&&(e._rejectCallback(n.e,!0,!0),e=null)},e.prototype._settlePromiseFromHandler=function(t,e,r,n){if(!n._isRejected()){n._pushContext();var o;if(o=e!==f||this._isRejected()?E(t).call(e,r):E(t).apply(this._boundValue(),r),n._popContext(),o===k||o===n||o===_){var s=o===n?i():o.e;n._rejectCallback(s,!1,!0)}else n._resolveCallback(o)}},e.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},e.prototype._followee=function(){return this._rejectionHandler0},e.prototype._setFollowee=function(t){this._rejectionHandler0=t},e.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},e.prototype._propagateFrom=function(t,e){(1&e)>0&&t._cancellable()&&(this._setCancellable(),this._cancellationParent=t),(4&e)>0&&t._isBound()&&this._setBoundTo(t._boundTo)},e.prototype._fulfill=function(t){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(t)},e.prototype._reject=function(t,e){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(t,e)},e.prototype._settlePromiseAt=function(t){var r=this._promiseAt(t),n=r instanceof e;if(n&&r._isMigrated())return r._unsetIsMigrated(),c.invoke(this._settlePromiseAt,this,t);var i=this._isFulfilled()?this._fulfillmentHandlerAt(t):this._rejectionHandlerAt(t),o=this._isCarryingStackTrace()?this._getCarriedStackTrace():void 0,s=this._settledValue,a=this._receiverAt(t);this._clearCallbackDataAtIndex(t),"function"==typeof i?n?this._settlePromiseFromHandler(i,a,s,r):i.call(a,s,r):a instanceof v?a._isResolved()||(this._isFulfilled()?a._promiseFulfilled(s,r):a._promiseRejected(s,r)):n&&(this._isFulfilled()?r._fulfill(s):r._reject(s,o)),t>=4&&4===(31&t)&&c.invokeLater(this._setLength,this,0)},e.prototype._clearCallbackDataAtIndex=function(t){if(0===t)this._isCarryingStackTrace()||(this._fulfillmentHandler0=void 0),this._rejectionHandler0=this._progressHandler0=this._receiver0=this._promise0=void 0;else{var e=5*t-5;this[e+3]=this[e+4]=this[e+0]=this[e+1]=this[e+2]=void 0}},e.prototype._isSettlePromisesQueued=function(){return-1073741824===(-1073741824&this._bitField)},e.prototype._setSettlePromisesQueued=function(){this._bitField=-1073741824|this._bitField},e.prototype._unsetSettlePromisesQueued=function(){this._bitField=1073741823&this._bitField},e.prototype._queueSettlePromises=function(){c.settlePromises(this),this._setSettlePromisesQueued()},e.prototype._fulfillUnchecked=function(t){if(t===this){var e=i();return this._attachExtraTrace(e),this._rejectUnchecked(e,void 0)}this._setFulfilled(),this._settledValue=t,this._cleanValues(),this._length()>0&&this._queueSettlePromises()},e.prototype._rejectUncheckedCheckError=function(t){var e=a.ensureErrorObject(t);this._rejectUnchecked(t,e===t?void 0:e)},e.prototype._rejectUnchecked=function(t,e){if(t===this){var r=i();return this._attachExtraTrace(r),this._rejectUnchecked(r)}return this._setRejected(),this._settledValue=t,this._cleanValues(),this._isFinal()?void c.throwLater(function(t){throw"stack"in t&&c.invokeFirst(y.unhandledRejection,void 0,t),t},void 0===e?t:e):(void 0!==e&&e!==t&&this._setCarriedStackTrace(e),void(this._length()>0?this._queueSettlePromises():this._ensurePossibleRejectionHandled()))},e.prototype._settlePromises=function(){this._unsetSettlePromisesQueued();for(var t=this._length(),e=0;t>e;e++)this._settlePromiseAt(e)},a.notEnumerableProp(e,"_makeSelfResolutionError",i),t("./progress.js")(e,v),t("./method.js")(e,p,d,s),t("./bind.js")(e,p,d),t("./finally.js")(e,_,d),t("./direct_resolve.js")(e),t("./synchronous_inspection.js")(e),t("./join.js")(e,v,d,p),e.Promise=e,t("./map.js")(e,v,s,d,p),t("./cancel.js")(e),t("./using.js")(e,s,d,m),t("./generators.js")(e,s,p,d),t("./nodeify.js")(e),t("./call_get.js")(e),t("./props.js")(e,v,d,s),t("./race.js")(e,p,d,s),t("./reduce.js")(e,v,s,d,p),t("./settle.js")(e,v),t("./some.js")(e,v,s),t("./promisify.js")(e,p),t("./any.js")(e),t("./each.js")(e,p),t("./timers.js")(e,p),t("./filter.js")(e,p),a.toFastProperties(e),a.toFastProperties(e.prototype),r({a:1}),r({b:2}),r({c:3}),r(1),r(function(){}),r(void 0),r(!1),r(new e(p)),y.setBounds(c.firstLineError,a.lastLineError),e}},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){switch(t){case-2:return[];case-3:return{}}}function s(t){var n,i=this._promise=new e(r);t instanceof e&&(n=t,i._propagateFrom(n,5)),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var a=t("./util.js"),u=a.isArray;return s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function c(t,r){var s=n(this._values,this._promise);if(s instanceof e){if(s=s._target(),this._values=s,!s._isFulfilled())return s._isPending()?void s._then(c,this._reject,void 0,this,r):void this._reject(s._reason());if(s=s._value(),!u(s)){var a=new e.TypeError("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n");return void this.__hardReject__(a)}}else if(!u(s))return void this._promise._reject(i("expecting an array, a promise or a thenable\n\n See http://goo.gl/s8MMhc\n")._reason());if(0===s.length)return void(-5===r?this._resolveEmptyArray():this._resolve(o(r)));var l=this.getActualLength(s.length);this._length=l,this._values=this.shouldCopyValues()?new Array(l):this._values;for(var h=this._promise,p=0;l>p;++p){var f=this._isResolved(),_=n(s[p],h);_ instanceof e?(_=_._target(),f?_._ignoreRejections():_._isPending()?_._proxyPromiseArray(this,p):_._isFulfilled()?this._promiseFulfilled(_._value(),p):this._promiseRejected(_._reason(),p)):f||this._promiseFulfilled(_,p)}},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype.__hardReject__=s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1,!0)},s.prototype._promiseProgressed=function(t,e){this._promise._progress({index:e,value:t})},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},s.prototype._promiseRejected=function(t){this._totalResolved++,this._reject(t)},s.prototype.shouldCopyValues=function(){return!0},s.prototype.getActualLength=function(t){return t},s}},{"./util.js":38}],25:[function(t,e){"use strict";function r(t){return t instanceof Error&&p.getPrototypeOf(t)===Error.prototype}function n(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=p.keys(t),i=0;i2){for(var o=arguments.length,s=new Array(o-1),u=1;o>u;++u)s[u-1]=arguments[u];t._fulfill(s)}else t._fulfill(r);t=null}}}var o,s=t("./util.js"),a=s.maybeWrapAsError,u=t("./errors.js"),c=u.TimeoutError,l=u.OperationalError,h=s.haveGetters,p=t("./es5.js"),f=/^(?:name|message|stack|cause)$/;if(o=h?function(t){this.promise=t}:function(t){this.promise=t,this.asCallback=i(t),this.callback=this.asCallback},h){var _={get:function(){return i(this.promise)}};p.defineProperty(o.prototype,"asCallback",_),p.defineProperty(o.prototype,"callback",_)}o._nodebackForPromise=i,o.prototype.toString=function(){return"[object PromiseResolver]"},o.prototype.resolve=o.prototype.fulfill=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._resolveCallback(t)},o.prototype.reject=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._rejectCallback(t)},o.prototype.progress=function(t){if(!(this instanceof o))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\n\n See http://goo.gl/sdkXL9\n");this.promise._progress(t)},o.prototype.cancel=function(t){this.promise.cancel(t)},o.prototype.timeout=function(){this.reject(new c("timeout"))},o.prototype.isResolved=function(){return this.promise.isResolved()},o.prototype.toJSON=function(){return this.promise.toJSON()},e.exports=o},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(t,e){"use strict";e.exports=function(e,r){function n(t){return!w.test(t)}function i(t){try{return t.__isPromisified__===!0}catch(e){return!1}}function o(t,e,r){var n=f.getDataPropertyOrDefault(t,e+r,j);return n?i(n):!1}function s(t,e,r){for(var n=0;ns;s+=2){var c=o[s],l=o[s+1],h=c+e;if(n===F)t[h]=F(c,p,c,l,e);else{var _=n(l,function(){return F(c,p,c,l,e)});f.notEnumerableProp(_,"__isPromisified__",!0),t[h]=_}}return f.toFastProperties(t),t}function l(t,e){return F(t,e,void 0,t)}var h,p={},f=t("./util.js"),_=t("./promise_resolver.js")._nodebackForPromise,d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,g=t("./errors").TypeError,m="Async",j={__isPromisified__:!0},b=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],w=new RegExp("^(?:"+b.join("|")+")$"),k=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},E=function(t){return t.replace(/([$])/,"\\$")},F=y?h:u;e.promisify=function(t,e){if("function"!=typeof t)throw new g("fn must be a function\n\n See http://goo.gl/916lJJ\n");if(i(t))return t;var r=l(t,arguments.length<2?p:e);return f.copyDescriptors(t,r,n),r},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new g("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/9ITlV0\n");e=Object(e);var r=e.suffix;"string"!=typeof r&&(r=m);var n=e.filter;"function"!=typeof n&&(n=k);var i=e.promisifier;if("function"!=typeof i&&(i=F),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/8FZo5V\n");for(var o=f.inheritedDataKeys(t),s=0;si;++i){var o=e[i];n[i]=t[o],n[i+r]=o}this.constructor$(n)}function s(t){var r,s=n(t);return u(s)?(r=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&r._propagateFrom(s,4),r):i("cannot await properties of a non-object\n\n See http://goo.gl/OsFKC8\n")}var a=t("./util.js"),u=a.isObject,c=t("./es5.js");a.inherits(o,r),o.prototype._init=function(){this._init$(void 0,-3)},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var r=++this._totalResolved;if(r>=this._length){for(var n={},i=this.length(),o=0,s=this.length();s>o;++o)n[this._values[o+i]]=this._values[o];this._resolve(n)}},o.prototype._promiseProgressed=function(t,e){this._promise._progress({key:this._values[e+this.length()],value:t})},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5.js":14,"./util.js":38}],28:[function(t,e){"use strict";function r(t,e,r,n,i){for(var o=0;i>o;++o)r[o+n]=t[o+e],t[o+e]=void 0}function n(t){this._capacity=t,this._length=0,this._front=0}n.prototype._willBeOverCapacity=function(t){return this._capacityp;++p){var _=t[p];(void 0!==_||p in t)&&e.cast(_)._then(l,h,void 0,c,null)}return c}var s=t("./util.js").isArray,a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util.js":38}],30:[function(t,e){"use strict";e.exports=function(e,r,n,i,o){function s(t,r,n,s){this.constructor$(t),this._promise._captureStackTrace(),this._preservedValues=s===o?[]:null,this._zerothIsAccum=void 0===n,this._gotAccum=!1,this._reducingIndex=this._zerothIsAccum?1:0,this._valuesPhase=void 0;var u=i(n,this._promise),h=!1,p=u instanceof e;p&&(u=u._target(),u._isPending()?u._proxyPromiseArray(this,-1):u._isFulfilled()?(n=u._value(),this._gotAccum=!0):(this._reject(u._reason()),h=!0)),p||this._zerothIsAccum||(this._gotAccum=!0);var f=c();this._callback=null===f?r:f.bind(r),this._accum=n,h||l.invoke(a,this,void 0)}function a(){this._init$(void 0,-5)}function u(t,e,r,i){if("function"!=typeof e)return n("fn must be a function\n\n See http://goo.gl/916lJJ\n");var o=new s(t,e,r,i);return o.promise()}var c=e._getDomain,l=t("./async.js"),h=t("./util.js"),p=h.tryCatch,f=h.errorObj;h.inherits(s,r),s.prototype._init=function(){},s.prototype._resolveEmptyArray=function(){(this._gotAccum||this._zerothIsAccum)&&this._resolve(null!==this._preservedValues?[]:this._accum)},s.prototype._promiseFulfilled=function(t,r){var n=this._values;n[r]=t;var o,s=this.length(),a=this._preservedValues,u=null!==a,c=this._gotAccum,l=this._valuesPhase;if(!l)for(l=this._valuesPhase=new Array(s),o=0;s>o;++o)l[o]=0;if(o=l[r],0===r&&this._zerothIsAccum?(this._accum=t,this._gotAccum=c=!0,l[r]=0===o?1:2):-1===r?(this._accum=t,this._gotAccum=c=!0):0===o?l[r]=1:(l[r]=2,this._accum=t),c){for(var h,_=this._callback,d=this._promise._boundValue(),v=this._reducingIndex;s>v;++v)if(o=l[v],2!==o){if(1!==o)return;if(t=n[v],this._promise._pushContext(),u?(a.push(t),h=p(_).call(d,t,v,s)):h=p(_).call(d,this._accum,t,v,s),this._promise._popContext(),h===f)return this._reject(h.e);var y=i(h,this._promise);if(y instanceof e){if(y=y._target(),y._isPending())return l[v]=4,y._proxyPromiseArray(this,v);if(!y._isFulfilled())return this._reject(y._reason());h=y._value()}this._reducingIndex=v+1,this._accum=h}else this._reducingIndex=v+1;this._resolve(u?a:this._accum)}},e.prototype.reduce=function(t,e){return u(this,t,e,null)},e.reduce=function(t,e,r,n){return u(t,e,r,n)}}},{"./async.js":2,"./util.js":38}],31:[function(t,e){"use strict";var r,n=t("./util"),i=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/m3OTXk\n")};if(n.isNode&&"undefined"==typeof MutationObserver){var o=global.setImmediate,s=process.nextTick;r=n.isRecentNode?function(t){o.call(global,t)}:function(t){s.call(process,t)}}else"undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&window.navigator.standalone?r="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:i:(r=function(t){var e=document.createElement("div"),r=new MutationObserver(t);return r.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},r.isStatic=!0);e.exports=r},{"./util":38}],32:[function(t,e){"use strict";e.exports=function(e,r){function n(t){this.constructor$(t)}var i=e.PromiseInspection,o=t("./util.js");o.inherits(n,r),n.prototype._promiseResolved=function(t,e){this._values[t]=e;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)},n.prototype._promiseFulfilled=function(t,e){var r=new i;r._bitField=268435456,r._settledValue=t,this._promiseResolved(e,r)},n.prototype._promiseRejected=function(t,e){var r=new i;r._bitField=134217728,r._settledValue=t,this._promiseResolved(e,r)},e.settle=function(t){return new n(t).promise()},e.prototype.settle=function(){return new n(this).promise()}}},{"./util.js":38}],33:[function(t,e){"use strict";e.exports=function(e,r,n){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return n("expecting a positive integer\n\n See http://goo.gl/1wAmHx\n");var r=new i(t),o=r.promise();return r.setHowMany(e),r.init(),o}var s=t("./util.js"),a=t("./errors.js").RangeError,u=t("./errors.js").AggregateError,c=s.isArray;s.inherits(i,r),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){this._addFulfilled(t),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),this._resolve(1===this.howMany()&&this._unwrap?this._values[0]:this._values))},i.prototype._promiseRejected=function(t){if(this._addRejected(t),this.howMany()>this._canPossiblyFulfill()){for(var e=new u,r=this.length();r0},e.prototype.isRejected=t.prototype._isRejected=function(){return(134217728&this._bitField)>0},e.prototype.isPending=t.prototype._isPending=function(){return 0===(402653184&this._bitField)},e.prototype.isResolved=t.prototype._isResolved=function(){return(402653184&this._bitField)>0},t.prototype.isPending=function(){return this._target()._isPending()},t.prototype.isRejected=function(){return this._target()._isRejected()},t.prototype.isFulfilled=function(){return this._target()._isFulfilled()},t.prototype.isResolved=function(){return this._target()._isResolved()},t.prototype._value=function(){return this._settledValue},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue},t.prototype.value=function(){var t=this._target();if(!t.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/hc1DLj\n");return t._settledValue},t.prototype.reason=function(){var t=this._target();if(!t.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/hPuiwB\n");return t._unsetRejectionIsUnhandled(),t._settledValue},t.PromiseInspection=e}},{}],35:[function(t,e){"use strict";e.exports=function(e,r){function n(t,n){if(c(t)){if(t instanceof e)return t;if(o(t)){var l=new e(r);return t._then(l._fulfillUnchecked,l._rejectUncheckedCheckError,l._progressUnchecked,l,null),l}var h=a.tryCatch(i)(t);if(h===u){n&&n._pushContext();var l=e.reject(h.e);return n&&n._popContext(),l}if("function"==typeof h)return s(t,h,n)}return t}function i(t){return t.then}function o(t){return l.call(t,"_promise0")}function s(t,n,i){function o(t){l&&(l._resolveCallback(t),l=null)}function s(t){l&&(l._rejectCallback(t,p,!0),l=null)}function c(t){l&&"function"==typeof l._progress&&l._progress(t)}var l=new e(r),h=l;i&&i._pushContext(),l._captureStackTrace(),i&&i._popContext();var p=!0,f=a.tryCatch(n).call(t,o,s,c);return p=!1,l&&f===u&&(l._rejectCallback(f.e,!0,!0),l=null),h}var a=t("./util.js"),u=a.errorObj,c=a.isObject,l={}.hasOwnProperty;return n}},{"./util.js":38}],36:[function(t,e){"use strict";e.exports=function(e,r){function n(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util.js"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){var r;!o.isPrimitive(e)&&e instanceof Error?r=e:("string"!=typeof e&&(e="operation timed out"),r=new s(e)),o.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._cancel(r)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,n){if(void 0===n){n=t,t=void 0;var i=new e(r);return setTimeout(function(){i._fulfill()},n),i}return n=+n,e.resolve(t)._then(u,null,null,n,void 0)};e.prototype.delay=function(t){return c(this,t)},e.prototype.timeout=function(t,e){t=+t;var r=this.then().cancellable();r._cancellationParent=this;var o=setTimeout(function(){a(r,e)},t);return r._then(n,i,void 0,o,void 0)}}},{"./util.js":38}],37:[function(t,e){"use strict";e.exports=function(e,r,n,i){function o(t){for(var r=t.length,n=0;r>n;++n){var i=t[n];if(i.isRejected())return e.reject(i.error());t[n]=i._settledValue}return t}function s(t){setTimeout(function(){throw t},0)}function a(t){var e=n(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function u(t,r){function i(){if(o>=u)return c.resolve();var l=a(t[o++]);if(l instanceof e&&l._isDisposable()){try{l=n(l._getDisposer().tryDispose(r),t.promise)}catch(h){return s(h)}if(l instanceof e)return l._then(i,s,null,null,null)}i()}var o=0,u=t.length,c=e.defer();return i(),c.promise}function c(t){var e=new v;return e._settledValue=t,e._bitField=268435456,u(this,e).thenReturn(t)}function l(t){var e=new v;return e._settledValue=t,e._bitField=134217728,u(this,e).thenThrow(t)}function h(t,e,r){this._data=t,this._promise=e,this._context=r}function p(t,e,r){this.constructor$(t,e,r)}function f(t){return h.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}var _=t("./errors.js").TypeError,d=t("./util.js").inherits,v=e.PromiseInspection;h.prototype.data=function(){return this._data},h.prototype.promise=function(){return this._promise},h.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},h.prototype.tryDispose=function(t){var e=this.resource(),r=this._context;void 0!==r&&r._pushContext();var n=null!==e?this.doDispose(e,t):null;return void 0!==r&&r._popContext(),this._promise._unsetDisposable(),this._data=null,n},h.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},d(p,h),p.prototype.doDispose=function(t,e){var r=this.data();return r.call(t,t,e)},e.using=function(){var t=arguments.length;if(2>t)return r("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return r("fn must be a function\n\n See http://goo.gl/916lJJ\n");var s,a=!0;2===t&&Array.isArray(arguments[0])?(s=arguments[0],t=s.length,a=!1):(s=arguments,t--);for(var u=new Array(t),p=0;t>p;++p){var _=s[p];if(h.isDisposer(_)){var d=_;_=_.promise(),_._setDisposable(d) +}else{var v=n(_);v instanceof e&&(_=v._then(f,null,null,{resources:u,index:p},void 0))}u[p]=_}var y=e.settle(u).then(o).then(function(t){y._pushContext();var e;try{e=a?i.apply(void 0,t):i.call(void 0,t)}finally{y._popContext()}return e})._then(c,l,void 0,u,void 0);return u.promise=y,y},e.prototype._setDisposable=function(t){this._bitField=262144|this._bitField,this._disposer=t},e.prototype._isDisposable=function(){return(262144&this._bitField)>0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-262145&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new _}}},{"./errors.js":13,"./util.js":38}],38:[function(t,e,r){"use strict";function n(){try{var t=C;return C=null,t.apply(this,arguments)}catch(e){return F.e=e,F}}function i(t){return C=t,n}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return!o(t)}function a(t){return o(t)?new Error(v(t)):t}function u(t,e){var r,n=t.length,i=new Array(n+1);for(r=0;n>r;++r)i[r]=t[r];return i[r]=e,i}function c(t,e,r){if(!w.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var n=Object.getOwnPropertyDescriptor(t,e);return null!=n?null==n.get&&null==n.set?n.value:r:void 0}function l(t,e,r){if(o(t))return t;var n={value:r,configurable:!0,enumerable:!1,writable:!0};return w.defineProperty(t,e,n),t}function h(t){throw t}function p(t){try{if("function"==typeof t){var e=w.names(t.prototype),r=w.isES5&&e.length>1,n=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=x.test(t+"")&&w.names(t).length>0;if(r||n||i)return!0}return!1}catch(o){return!1}}function f(t){function e(){}e.prototype=t;for(var r=8;r--;)new e;return t}function _(t){return R.test(t)}function d(t,e,r){for(var n=new Array(t),i=0;t>i;++i)n[i]=e+i+r;return n}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){try{l(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function m(t){return t instanceof Error&&w.propertyIsWritable(t,"stack")}function j(t){return{}.toString.call(t)}function b(t,e,r){for(var n=w.names(t),i=0;i10||t[0]>0}(),A.isNode&&A.toFastProperties(process);try{throw new Error}catch(O){A.lastLineError=O}e.exports=A},{"./es5.js":14}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/node_modules/express-validator/node_modules/bluebird/js/main/any.js b/node_modules/express-validator/node_modules/bluebird/js/main/any.js new file mode 100644 index 0000000..05a6228 --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/js/main/any.js @@ -0,0 +1,21 @@ +"use strict"; +module.exports = function(Promise) { +var SomePromiseArray = Promise._SomePromiseArray; +function any(promises) { + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(1); + ret.setUnwrap(); + ret.init(); + return promise; +} + +Promise.any = function (promises) { + return any(promises); +}; + +Promise.prototype.any = function () { + return any(this); +}; + +}; diff --git a/node_modules/bluebird/js/main/assert.js b/node_modules/express-validator/node_modules/bluebird/js/main/assert.js similarity index 100% rename from node_modules/bluebird/js/main/assert.js rename to node_modules/express-validator/node_modules/bluebird/js/main/assert.js diff --git a/node_modules/bluebird/js/main/async.js b/node_modules/express-validator/node_modules/bluebird/js/main/async.js similarity index 63% rename from node_modules/bluebird/js/main/async.js rename to node_modules/express-validator/node_modules/bluebird/js/main/async.js index 39f2340..0104459 100644 --- a/node_modules/bluebird/js/main/async.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/async.js @@ -42,8 +42,6 @@ Async.prototype.throwLater = function(fn, arg) { arg = fn; fn = function () { throw arg; }; } - var domain = this._getDomain(); - if (domain !== undefined) fn = domain.bind(fn); if (typeof setTimeout !== "undefined") { setTimeout(function() { fn(arg); @@ -57,71 +55,18 @@ Async.prototype.throwLater = function(fn, arg) { } }; -Async.prototype._getDomain = function() {}; - -if (util.isNode) { - var EventsModule = require("events"); - - var domainGetter = function() { - var domain = process.domain; - if (domain === null) return undefined; - return domain; - }; - - if (EventsModule.usingDomains) { - Async.prototype._getDomain = domainGetter; - } else { - var descriptor = - Object.getOwnPropertyDescriptor(EventsModule, "usingDomains"); - - if (!descriptor.configurable) { - process.on("domainsActivated", function() { - Async.prototype._getDomain = domainGetter; - }); - } else { - var usingDomains = false; - Object.defineProperty(EventsModule, "usingDomains", { - configurable: false, - enumerable: true, - get: function() { - return usingDomains; - }, - set: function(value) { - if (usingDomains || !value) return; - usingDomains = true; - Async.prototype._getDomain = domainGetter; - util.toFastProperties(process); - process.emit("domainsActivated"); - } - }); - } - - - } -} - function AsyncInvokeLater(fn, receiver, arg) { - var domain = this._getDomain(); - if (domain !== undefined) fn = domain.bind(fn); this._lateQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncInvoke(fn, receiver, arg) { - var domain = this._getDomain(); - if (domain !== undefined) fn = domain.bind(fn); this._normalQueue.push(fn, receiver, arg); this._queueTick(); } function AsyncSettlePromises(promise) { - var domain = this._getDomain(); - if (domain !== undefined) { - var fn = domain.bind(promise._settlePromises); - this._normalQueue.push(fn, promise, undefined); - } else { - this._normalQueue._pushOne(promise); - } + this._normalQueue._pushOne(promise); this._queueTick(); } @@ -130,13 +75,18 @@ if (!util.hasDevTools) { Async.prototype.invoke = AsyncInvoke; Async.prototype.settlePromises = AsyncSettlePromises; } else { + if (schedule.isStatic) { + schedule = function(fn) { setTimeout(fn, 0); }; + } Async.prototype.invokeLater = function (fn, receiver, arg) { if (this._trampolineEnabled) { AsyncInvokeLater.call(this, fn, receiver, arg); } else { - setTimeout(function() { - fn.call(receiver, arg); - }, 100); + this._schedule(function() { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + }); } }; @@ -144,9 +94,9 @@ if (!util.hasDevTools) { if (this._trampolineEnabled) { AsyncInvoke.call(this, fn, receiver, arg); } else { - setTimeout(function() { + this._schedule(function() { fn.call(receiver, arg); - }, 0); + }); } }; @@ -154,16 +104,14 @@ if (!util.hasDevTools) { if (this._trampolineEnabled) { AsyncSettlePromises.call(this, promise); } else { - setTimeout(function() { + this._schedule(function() { promise._settlePromises(); - }, 0); + }); } }; } Async.prototype.invokeFirst = function (fn, receiver, arg) { - var domain = this._getDomain(); - if (domain !== undefined) fn = domain.bind(fn); this._normalQueue.unshift(fn, receiver, arg); this._queueTick(); }; diff --git a/node_modules/bluebird/js/main/bind.js b/node_modules/express-validator/node_modules/bluebird/js/main/bind.js similarity index 91% rename from node_modules/bluebird/js/main/bind.js rename to node_modules/express-validator/node_modules/bluebird/js/main/bind.js index d6f6da2..9d8257a 100644 --- a/node_modules/bluebird/js/main/bind.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/bind.js @@ -10,7 +10,6 @@ var targetRejected = function(e, context) { }; var bindingResolved = function(thisArg, context) { - this._setBoundTo(thisArg); if (this._isPending()) { this._resolveCallback(context.target); } @@ -25,6 +24,8 @@ Promise.prototype.bind = function (thisArg) { var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); + + ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, @@ -36,7 +37,6 @@ Promise.prototype.bind = function (thisArg) { maybePromise._then( bindingResolved, bindingRejected, ret._progress, ret, context); } else { - ret._setBoundTo(thisArg); ret._resolveCallback(target); } return ret; @@ -59,13 +59,12 @@ Promise.bind = function (thisArg, value) { var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); + ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { - maybePromise._then(function(thisArg) { - ret._setBoundTo(thisArg); + maybePromise._then(function() { ret._resolveCallback(value); }, ret._reject, ret._progress, ret, null); } else { - ret._setBoundTo(thisArg); ret._resolveCallback(value); } return ret; diff --git a/node_modules/bluebird/js/main/bluebird.js b/node_modules/express-validator/node_modules/bluebird/js/main/bluebird.js similarity index 100% rename from node_modules/bluebird/js/main/bluebird.js rename to node_modules/express-validator/node_modules/bluebird/js/main/bluebird.js diff --git a/node_modules/bluebird/js/main/call_get.js b/node_modules/express-validator/node_modules/bluebird/js/main/call_get.js similarity index 100% rename from node_modules/bluebird/js/main/call_get.js rename to node_modules/express-validator/node_modules/bluebird/js/main/call_get.js diff --git a/node_modules/bluebird/js/main/cancel.js b/node_modules/express-validator/node_modules/bluebird/js/main/cancel.js similarity index 100% rename from node_modules/bluebird/js/main/cancel.js rename to node_modules/express-validator/node_modules/bluebird/js/main/cancel.js diff --git a/node_modules/bluebird/js/main/captured_trace.js b/node_modules/express-validator/node_modules/bluebird/js/main/captured_trace.js similarity index 99% rename from node_modules/bluebird/js/main/captured_trace.js rename to node_modules/express-validator/node_modules/bluebird/js/main/captured_trace.js index 6fda9e8..802acd3 100644 --- a/node_modules/bluebird/js/main/captured_trace.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/captured_trace.js @@ -382,7 +382,8 @@ var captureStackTrace = (function stackDetection() { catch(e) { hasStackAfterThrow = ("stack" in e); } - if (!("stack" in err) && hasStackAfterThrow) { + if (!("stack" in err) && hasStackAfterThrow && + typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { diff --git a/node_modules/bluebird/js/main/catch_filter.js b/node_modules/express-validator/node_modules/bluebird/js/main/catch_filter.js similarity index 98% rename from node_modules/bluebird/js/main/catch_filter.js rename to node_modules/express-validator/node_modules/bluebird/js/main/catch_filter.js index 040f057..df12733 100644 --- a/node_modules/bluebird/js/main/catch_filter.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/catch_filter.js @@ -30,7 +30,7 @@ function safePredicate(predicate, e) { CatchFilter.prototype.doFilter = function (e) { var cb = this._callback; var promise = this._promise; - var boundTo = promise._boundTo; + var boundTo = promise._boundValue(); for (var i = 0, len = this._instances.length; i < len; ++i) { var item = this._instances[i]; var itemIsErrorType = item === Error || diff --git a/node_modules/bluebird/js/main/context.js b/node_modules/express-validator/node_modules/bluebird/js/main/context.js similarity index 100% rename from node_modules/bluebird/js/main/context.js rename to node_modules/express-validator/node_modules/bluebird/js/main/context.js diff --git a/node_modules/bluebird/js/main/debuggability.js b/node_modules/express-validator/node_modules/bluebird/js/main/debuggability.js similarity index 86% rename from node_modules/bluebird/js/main/debuggability.js rename to node_modules/express-validator/node_modules/bluebird/js/main/debuggability.js index 5ac1767..106baf6 100644 --- a/node_modules/bluebird/js/main/debuggability.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/debuggability.js @@ -1,5 +1,6 @@ "use strict"; module.exports = function(Promise, CapturedTrace) { +var getDomain = Promise._getDomain; var async = require("./async.js"); var Warning = require("./errors.js").Warning; var util = require("./util.js"); @@ -10,11 +11,19 @@ var debugging = false || (util.isNode && (!!process.env["BLUEBIRD_DEBUG"] || process.env["NODE_ENV"] === "development")); +if (util.isNode && process.env["BLUEBIRD_DEBUG"] == 0) debugging = false; + if (debugging) { async.disableTrampolineIfNecessary(); } +Promise.prototype._ignoreRejections = function() { + this._unsetRejectionIsUnhandled(); + this._bitField = this._bitField | 16777216; +}; + Promise.prototype._ensurePossibleRejectionHandled = function () { + if ((this._bitField & 16777216) !== 0) return; this._setRejectionIsUnhandled(); async.invokeLater(this._notifyUnhandledRejection, this, undefined); }; @@ -113,11 +122,17 @@ Promise.prototype._warn = function(message) { }; Promise.onPossiblyUnhandledRejection = function (fn) { - possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined; + var domain = getDomain(); + possiblyUnhandledRejection = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { - unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; + var domain = getDomain(); + unhandledRejectionHandled = + typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) + : undefined; }; Promise.longStackTraces = function () { diff --git a/node_modules/bluebird/js/main/direct_resolve.js b/node_modules/express-validator/node_modules/bluebird/js/main/direct_resolve.js similarity index 75% rename from node_modules/bluebird/js/main/direct_resolve.js rename to node_modules/express-validator/node_modules/bluebird/js/main/direct_resolve.js index c61a367..054685a 100644 --- a/node_modules/bluebird/js/main/direct_resolve.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/direct_resolve.js @@ -1,7 +1,6 @@ "use strict"; var util = require("./util.js"); var isPrimitive = util.isPrimitive; -var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; module.exports = function(Promise) { var returner = function () { @@ -10,6 +9,10 @@ var returner = function () { var thrower = function () { throw this; }; +var returnUndefined = function() {}; +var throwUndefined = function() { + throw undefined; +}; var wrapper = function (value, action) { if (action === 1) { @@ -26,7 +29,9 @@ var wrapper = function (value, action) { Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { - if (wrapsPrimitiveReceiver && isPrimitive(value)) { + if (value === undefined) return this.then(returnUndefined); + + if (isPrimitive(value)) { return this._then( wrapper(value, 2), undefined, @@ -34,13 +39,17 @@ Promise.prototype.thenReturn = function (value) { undefined, undefined ); + } else if (value instanceof Promise) { + value._ignoreRejections(); } return this._then(returner, undefined, undefined, value, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { - if (wrapsPrimitiveReceiver && isPrimitive(reason)) { + if (reason === undefined) return this.then(throwUndefined); + + if (isPrimitive(reason)) { return this._then( wrapper(reason, 1), undefined, diff --git a/node_modules/bluebird/js/main/each.js b/node_modules/express-validator/node_modules/bluebird/js/main/each.js similarity index 100% rename from node_modules/bluebird/js/main/each.js rename to node_modules/express-validator/node_modules/bluebird/js/main/each.js diff --git a/node_modules/bluebird/js/main/errors.js b/node_modules/express-validator/node_modules/bluebird/js/main/errors.js similarity index 100% rename from node_modules/bluebird/js/main/errors.js rename to node_modules/express-validator/node_modules/bluebird/js/main/errors.js diff --git a/node_modules/express-validator/node_modules/bluebird/js/main/es5.js b/node_modules/express-validator/node_modules/bluebird/js/main/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/js/main/es5.js @@ -0,0 +1,80 @@ +var isES5 = (function(){ + "use strict"; + return this === undefined; +})(); + +if (isES5) { + module.exports = { + freeze: Object.freeze, + defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, + keys: Object.keys, + names: Object.getOwnPropertyNames, + 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 ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + 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, + names: ObjectKeys, + defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, + freeze: ObjectFreeze, + getPrototypeOf: ObjectGetPrototypeOf, + isES5: isES5, + propertyIsWritable: function() { + return true; + } + }; +} diff --git a/node_modules/express-validator/node_modules/bluebird/js/main/filter.js b/node_modules/express-validator/node_modules/bluebird/js/main/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/js/main/filter.js @@ -0,0 +1,12 @@ +"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); +}; +}; diff --git a/node_modules/bluebird/js/main/finally.js b/node_modules/express-validator/node_modules/bluebird/js/main/finally.js similarity index 91% rename from node_modules/bluebird/js/main/finally.js rename to node_modules/express-validator/node_modules/bluebird/js/main/finally.js index ed84a2a..c9342bc 100644 --- a/node_modules/bluebird/js/main/finally.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/finally.js @@ -1,7 +1,6 @@ "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; @@ -23,7 +22,7 @@ function throw$(r) { } function promisedFinally(ret, reasonOrValue, isFulfilled) { var then; - if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + if (isPrimitive(reasonOrValue)) { then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); } else { then = isFulfilled ? returnThis : throwThis; @@ -36,7 +35,7 @@ function finallyHandler(reasonOrValue) { var handler = this.handler; var ret = promise._isBound() - ? handler.call(promise._boundTo) + ? handler.call(promise._boundValue()) : handler(); if (ret !== undefined) { @@ -61,7 +60,7 @@ function tapHandler(value) { var handler = this.handler; var ret = promise._isBound() - ? handler.call(promise._boundTo, value) + ? handler.call(promise._boundValue(), value) : handler(value); if (ret !== undefined) { diff --git a/node_modules/bluebird/js/main/generators.js b/node_modules/express-validator/node_modules/bluebird/js/main/generators.js similarity index 100% rename from node_modules/bluebird/js/main/generators.js rename to node_modules/express-validator/node_modules/bluebird/js/main/generators.js diff --git a/node_modules/bluebird/js/main/join.js b/node_modules/express-validator/node_modules/bluebird/js/main/join.js similarity index 100% rename from node_modules/bluebird/js/main/join.js rename to node_modules/express-validator/node_modules/bluebird/js/main/join.js diff --git a/node_modules/bluebird/js/main/map.js b/node_modules/express-validator/node_modules/bluebird/js/main/map.js similarity index 95% rename from node_modules/bluebird/js/main/map.js rename to node_modules/express-validator/node_modules/bluebird/js/main/map.js index 66a5b17..2f40efd 100644 --- a/node_modules/bluebird/js/main/map.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/map.js @@ -4,6 +4,7 @@ module.exports = function(Promise, apiRejection, tryConvertToPromise, INTERNAL) { +var getDomain = Promise._getDomain; var async = require("./async.js"); var util = require("./util.js"); var tryCatch = util.tryCatch; @@ -14,7 +15,8 @@ var EMPTY_ARRAY = []; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); - this._callback = fn; + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; @@ -49,7 +51,7 @@ MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { if (preservedValues !== null) preservedValues[index] = value; var callback = this._callback; - var receiver = this._promise._boundTo; + var receiver = this._promise._boundValue(); this._promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); this._promise._popContext(); diff --git a/node_modules/bluebird/js/main/method.js b/node_modules/express-validator/node_modules/bluebird/js/main/method.js similarity index 100% rename from node_modules/bluebird/js/main/method.js rename to node_modules/express-validator/node_modules/bluebird/js/main/method.js diff --git a/node_modules/bluebird/js/main/nodeify.js b/node_modules/express-validator/node_modules/bluebird/js/main/nodeify.js similarity index 85% rename from node_modules/bluebird/js/main/nodeify.js rename to node_modules/express-validator/node_modules/bluebird/js/main/nodeify.js index f305b93..257565d 100644 --- a/node_modules/bluebird/js/main/nodeify.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/nodeify.js @@ -8,7 +8,8 @@ var errorObj = util.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val)); + var ret = + tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); if (ret === errorObj) { async.throwLater(ret.e); } @@ -16,7 +17,7 @@ function spreadAdapter(val, nodeback) { function successAdapter(val, nodeback) { var promise = this; - var receiver = promise._boundTo; + var receiver = promise._boundValue(); var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); @@ -32,13 +33,13 @@ function errorAdapter(reason, nodeback) { newReason.cause = reason; reason = newReason; } - var ret = tryCatch(nodeback).call(promise._boundTo, reason); + var ret = tryCatch(nodeback).call(promise._boundValue(), reason); if (ret === errorObj) { async.throwLater(ret.e); } } -Promise.prototype.asCallback = +Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { if (typeof nodeback == "function") { var adapter = successAdapter; diff --git a/node_modules/bluebird/js/main/progress.js b/node_modules/express-validator/node_modules/bluebird/js/main/progress.js similarity index 100% rename from node_modules/bluebird/js/main/progress.js rename to node_modules/express-validator/node_modules/bluebird/js/main/progress.js diff --git a/node_modules/bluebird/js/main/promise.js b/node_modules/express-validator/node_modules/bluebird/js/main/promise.js similarity index 90% rename from node_modules/bluebird/js/main/promise.js rename to node_modules/express-validator/node_modules/bluebird/js/main/promise.js index f80d247..96bd545 100644 --- a/node_modules/bluebird/js/main/promise.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/promise.js @@ -9,7 +9,24 @@ var reflect = function() { var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; + var util = require("./util.js"); + +var getDomain; +if (util.isNode) { + getDomain = function() { + var ret = process.domain; + if (ret === undefined) ret = null; + return ret; + }; +} else { + getDomain = function() { + return null; + }; +} +util.notEnumerableProp(Promise, "_getDomain", getDomain); + +var UNDEFINED_BINDING = {}; var async = require("./async.js"); var errors = require("./errors.js"); var TypeError = Promise.TypeError = errors.TypeError; @@ -208,8 +225,12 @@ Promise.prototype._then = function ( if (!haveInternalData) ret._setIsMigrated(); } - var callbackIndex = - target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); + var callbackIndex = target._addCallbacks(didFulfill, + didReject, + didProgress, + ret, + receiver, + getDomain()); if (target._isResolved() && !target._isSettlePromisesQueued()) { async.invoke( @@ -290,8 +311,10 @@ Promise.prototype._receiverAt = function (index) { ? this._receiver0 : this[ index * 5 - 5 + 4]; - if (ret === undefined && this._isBound()) { - return this._boundTo; + if (ret === UNDEFINED_BINDING) { + return undefined; + } else if (ret === undefined && this._isBound()) { + return this._boundValue(); } return ret; }; @@ -314,6 +337,20 @@ Promise.prototype._rejectionHandlerAt = function (index) { : this[index * 5 - 5 + 1]; }; +Promise.prototype._boundValue = function() { + var ret = this._boundTo; + if (ret !== undefined) { + if (ret instanceof Promise) { + if (ret.isFulfilled()) { + return ret.value(); + } else { + return undefined; + } + } + } + return ret; +}; + Promise.prototype._migrateCallbacks = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); @@ -321,7 +358,8 @@ Promise.prototype._migrateCallbacks = function (follower, index) { var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (promise instanceof Promise) promise._setIsMigrated(); - this._addCallbacks(fulfill, reject, progress, promise, receiver); + if (receiver === undefined) receiver = UNDEFINED_BINDING; + this._addCallbacks(fulfill, reject, progress, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( @@ -329,7 +367,8 @@ Promise.prototype._addCallbacks = function ( reject, progress, promise, - receiver + receiver, + domain ) { var index = this._length(); @@ -341,20 +380,34 @@ Promise.prototype._addCallbacks = function ( if (index === 0) { 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; + if (typeof fulfill === "function" && !this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this._rejectionHandler0 = + domain === null ? reject : domain.bind(reject); + } + if (typeof progress === "function") { + this._progressHandler0 = + domain === null ? progress : domain.bind(progress); + } } else { 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; + if (typeof fulfill === "function") { + this[base + 0] = + domain === null ? fulfill : domain.bind(fulfill); + } + if (typeof reject === "function") { + this[base + 1] = + domain === null ? reject : domain.bind(reject); + } + if (typeof progress === "function") { + this[base + 2] = + domain === null ? progress : domain.bind(progress); + } } this._setLength(index + 1); return index; @@ -449,7 +502,7 @@ Promise.prototype._settlePromiseFromHandler = function ( promise._pushContext(); var x; if (receiver === APPLY && !this._isRejected()) { - x = tryCatch(handler).apply(this._boundTo, value); + x = tryCatch(handler).apply(this._boundValue(), value); } else { x = tryCatch(handler).call(receiver, value); } @@ -519,8 +572,6 @@ Promise.prototype._settlePromiseAt = function (index) { this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; var value = this._settledValue; var receiver = this._receiverAt(index); - - this._clearCallbackDataAtIndex(index); if (typeof handler === "function") { @@ -647,7 +698,10 @@ Promise.prototype._settlePromises = function () { } }; -Promise._makeSelfResolutionError = makeSelfResolutionError; +util.notEnumerableProp(Promise, + "_makeSelfResolutionError", + makeSelfResolutionError); + require("./progress.js")(Promise, PromiseArray); require("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); require("./bind.js")(Promise, INTERNAL, tryConvertToPromise); diff --git a/node_modules/bluebird/js/main/promise_array.js b/node_modules/express-validator/node_modules/bluebird/js/main/promise_array.js similarity index 98% rename from node_modules/bluebird/js/main/promise_array.js rename to node_modules/express-validator/node_modules/bluebird/js/main/promise_array.js index 6dac866..b2e8f1c 100644 --- a/node_modules/bluebird/js/main/promise_array.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/promise_array.js @@ -80,7 +80,7 @@ PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); if (isResolved) { - maybePromise._unsetRejectionIsUnhandled(); + maybePromise._ignoreRejections(); } else if (maybePromise._isPending()) { maybePromise._proxyPromiseArray(this, i); } else if (maybePromise._isFulfilled()) { diff --git a/node_modules/bluebird/js/main/promise_resolver.js b/node_modules/express-validator/node_modules/bluebird/js/main/promise_resolver.js similarity index 100% rename from node_modules/bluebird/js/main/promise_resolver.js rename to node_modules/express-validator/node_modules/bluebird/js/main/promise_resolver.js diff --git a/node_modules/bluebird/js/main/promisify.js b/node_modules/express-validator/node_modules/bluebird/js/main/promisify.js similarity index 91% rename from node_modules/bluebird/js/main/promisify.js rename to node_modules/express-validator/node_modules/bluebird/js/main/promisify.js index 0355344..86763d6 100644 --- a/node_modules/bluebird/js/main/promisify.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/promisify.js @@ -10,12 +10,21 @@ var canEvaluate = util.canEvaluate; var TypeError = require("./errors").TypeError; var defaultSuffix = "Async"; var defaultPromisified = {__isPromisified__: true}; -var noCopyPropsPattern = - /^(?:length|name|arguments|caller|callee|prototype|__isPromisified__)$/; -var defaultFilter = function(name, func) { +var noCopyProps = [ + "arity", "length", + "name", + "arguments", + "caller", + "callee", + "prototype", + "__isPromisified__" +]; +var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); + +var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && - !util.isClass(func); + name !== "constructor"; }; function propsFilter(key) { @@ -159,6 +168,7 @@ function(callback, receiver, originalName, fn) { "nodebackForPromise", "tryCatch", "errorObj", + "notEnumerableProp", "INTERNAL","'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ @@ -176,7 +186,7 @@ function(callback, receiver, originalName, fn) { } \n\ return promise; \n\ }; \n\ - ret.__isPromisified__ = true; \n\ + notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ " .replace("Parameters", parameterDeclaration(newParameterCount)) @@ -190,6 +200,7 @@ function(callback, receiver, originalName, fn) { nodebackForPromise, util.tryCatch, util.errorObj, + util.notEnumerableProp, INTERNAL ); }; @@ -216,7 +227,7 @@ function makeNodePromisifiedClosure(callback, receiver, _, fn) { } return promise; } - promisified.__isPromisified__ = true; + util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } @@ -233,11 +244,16 @@ function promisifyAll(obj, suffix, filter, promisifier) { 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, function() { - return makeNodePromisified(key, THIS, key, fn, suffix); - }); + if (promisifier === makeNodePromisified) { + obj[promisifiedKey] = + makeNodePromisified(key, THIS, key, fn, suffix); + } else { + var promisified = promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); + util.notEnumerableProp(promisified, "__isPromisified__", true); + obj[promisifiedKey] = promisified; + } } util.toFastProperties(obj); return obj; diff --git a/node_modules/bluebird/js/main/props.js b/node_modules/express-validator/node_modules/bluebird/js/main/props.js similarity index 100% rename from node_modules/bluebird/js/main/props.js rename to node_modules/express-validator/node_modules/bluebird/js/main/props.js diff --git a/node_modules/express-validator/node_modules/bluebird/js/main/queue.js b/node_modules/express-validator/node_modules/bluebird/js/main/queue.js new file mode 100644 index 0000000..84d57d5 --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/js/main/queue.js @@ -0,0 +1,90 @@ +"use strict"; +function arrayMove(src, srcIndex, dst, dstIndex, len) { + for (var j = 0; j < len; ++j) { + dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; + } +} + +function Queue(capacity) { + this._capacity = capacity; + this._length = 0; + this._front = 0; +} + +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) { + 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 () { + 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._checkCapacity = function (size) { + if (this._capacity < size) { + this._resizeTo(this._capacity << 1); + } +}; + +Queue.prototype._resizeTo = function (capacity) { + var oldCapacity = this._capacity; + this._capacity = capacity; + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); +}; + +module.exports = Queue; diff --git a/node_modules/bluebird/js/main/race.js b/node_modules/express-validator/node_modules/bluebird/js/main/race.js similarity index 100% rename from node_modules/bluebird/js/main/race.js rename to node_modules/express-validator/node_modules/bluebird/js/main/race.js diff --git a/node_modules/bluebird/js/main/reduce.js b/node_modules/express-validator/node_modules/bluebird/js/main/reduce.js similarity index 96% rename from node_modules/bluebird/js/main/reduce.js rename to node_modules/express-validator/node_modules/bluebird/js/main/reduce.js index 3192220..1f92daf 100644 --- a/node_modules/bluebird/js/main/reduce.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/reduce.js @@ -4,6 +4,7 @@ module.exports = function(Promise, apiRejection, tryConvertToPromise, INTERNAL) { +var getDomain = Promise._getDomain; var async = require("./async.js"); var util = require("./util.js"); var tryCatch = util.tryCatch; @@ -32,7 +33,8 @@ function ReductionPromiseArray(promises, fn, accum, _each) { } } if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; - this._callback = fn; + var domain = getDomain(); + this._callback = domain === null ? fn : domain.bind(fn); this._accum = accum; if (!rejected) async.invoke(init, this, undefined); } @@ -86,7 +88,7 @@ ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { if (!gotAccum) return; var callback = this._callback; - var receiver = this._promise._boundTo; + var receiver = this._promise._boundValue(); var ret; for (var i = this._reducingIndex; i < length; ++i) { diff --git a/node_modules/bluebird/js/main/schedule.js b/node_modules/express-validator/node_modules/bluebird/js/main/schedule.js similarity index 57% rename from node_modules/bluebird/js/main/schedule.js rename to node_modules/express-validator/node_modules/bluebird/js/main/schedule.js index 2355ffb..bb04a8a 100644 --- a/node_modules/bluebird/js/main/schedule.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/schedule.js @@ -1,23 +1,19 @@ "use strict"; var schedule; +var util = require("./util"); var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); }; -if (require("./util.js").isNode) { - var version = process.versions.node.split(".").map(Number); - schedule = (version[0] === 0 && version[1] > 10) || (version[0] > 0) - ? global.setImmediate : process.nextTick; - - if (!schedule) { - if (typeof setImmediate !== "undefined") { - schedule = setImmediate; - } else if (typeof setTimeout !== "undefined") { - schedule = setTimeout; - } else { - schedule = noAsyncScheduler; - } - } -} else if (typeof MutationObserver !== "undefined") { +if (util.isNode && typeof MutationObserver === "undefined") { + var GlobalSetImmediate = global.setImmediate; + var ProcessNextTick = process.nextTick; + schedule = util.isRecentNode + ? function(fn) { GlobalSetImmediate.call(global, fn); } + : function(fn) { ProcessNextTick.call(process, fn); }; +} else if ((typeof MutationObserver !== "undefined") && + !(typeof window !== "undefined" && + window.navigator && + window.navigator.standalone)) { schedule = function(fn) { var div = document.createElement("div"); var observer = new MutationObserver(fn); diff --git a/node_modules/bluebird/js/main/settle.js b/node_modules/express-validator/node_modules/bluebird/js/main/settle.js similarity index 100% rename from node_modules/bluebird/js/main/settle.js rename to node_modules/express-validator/node_modules/bluebird/js/main/settle.js diff --git a/node_modules/bluebird/js/main/some.js b/node_modules/express-validator/node_modules/bluebird/js/main/some.js similarity index 100% rename from node_modules/bluebird/js/main/some.js rename to node_modules/express-validator/node_modules/bluebird/js/main/some.js diff --git a/node_modules/bluebird/js/main/synchronous_inspection.js b/node_modules/express-validator/node_modules/bluebird/js/main/synchronous_inspection.js similarity index 100% rename from node_modules/bluebird/js/main/synchronous_inspection.js rename to node_modules/express-validator/node_modules/bluebird/js/main/synchronous_inspection.js diff --git a/node_modules/bluebird/js/main/thenables.js b/node_modules/express-validator/node_modules/bluebird/js/main/thenables.js similarity index 91% rename from node_modules/bluebird/js/main/thenables.js rename to node_modules/express-validator/node_modules/bluebird/js/main/thenables.js index c858f86..eadfffb 100644 --- a/node_modules/bluebird/js/main/thenables.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/thenables.js @@ -61,12 +61,7 @@ function doThenable(x, then, context) { function resolveFromThenable(value) { if (!promise) return; - if (x === value) { - promise._rejectCallback( - Promise._makeSelfResolutionError(), false, true); - } else { - promise._resolveCallback(value); - } + promise._resolveCallback(value); promise = null; } diff --git a/node_modules/bluebird/js/main/timers.js b/node_modules/express-validator/node_modules/bluebird/js/main/timers.js similarity index 85% rename from node_modules/bluebird/js/main/timers.js rename to node_modules/express-validator/node_modules/bluebird/js/main/timers.js index ecf1b57..f26431a 100644 --- a/node_modules/bluebird/js/main/timers.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/timers.js @@ -5,10 +5,16 @@ var TimeoutError = Promise.TimeoutError; var afterTimeout = function (promise, message) { if (!promise.isPending()) return; - if (typeof message !== "string") { - message = "operation timed out"; + + var err; + if(!util.isPrimitive(message) && (message instanceof Error)) { + err = message; + } else { + if (typeof message !== "string") { + message = "operation timed out"; + } + err = new TimeoutError(message); } - var err = new TimeoutError(message); util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._cancel(err); diff --git a/node_modules/bluebird/js/main/using.js b/node_modules/express-validator/node_modules/bluebird/js/main/using.js similarity index 93% rename from node_modules/bluebird/js/main/using.js rename to node_modules/express-validator/node_modules/bluebird/js/main/using.js index 4038711..957182d 100644 --- a/node_modules/bluebird/js/main/using.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/using.js @@ -135,10 +135,20 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, "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 input; + var spreadArgs = true; + if (len === 2 && Array.isArray(arguments[0])) { + input = arguments[0]; + len = input.length; + spreadArgs = false; + } else { + input = arguments; + len--; + } var resources = new Array(len); for (var i = 0; i < len; ++i) { - var resource = arguments[i]; + var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); @@ -162,7 +172,8 @@ module.exports = function (Promise, apiRejection, tryConvertToPromise, promise._pushContext(); var ret; try { - ret = fn.apply(undefined, vals); + ret = spreadArgs + ? fn.apply(undefined, vals) : fn.call(undefined, vals); } finally { promise._popContext(); } diff --git a/node_modules/bluebird/js/main/util.js b/node_modules/express-validator/node_modules/bluebird/js/main/util.js similarity index 77% rename from node_modules/bluebird/js/main/util.js rename to node_modules/express-validator/node_modules/bluebird/js/main/util.js index fbee5de..ea39344 100644 --- a/node_modules/bluebird/js/main/util.js +++ b/node_modules/express-validator/node_modules/bluebird/js/main/util.js @@ -21,7 +21,9 @@ var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { - return tryCatchTarget.apply(this, arguments); + var target = tryCatchTarget; + tryCatchTarget = null; + return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; @@ -82,6 +84,7 @@ function withAppended(target, appendee) { 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 @@ -104,23 +107,32 @@ function notEnumerableProp(obj, name, value) { return obj; } - -var wrapsPrimitiveReceiver = (function() { - return this !== "string"; -}).call("string"); - function thrower(r) { throw r; } var inheritedDataKeys = (function() { + var excludedPrototypes = [ + Array.prototype, + Object.prototype, + Function.prototype + ]; + + var isExcludedProto = function(val) { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (excludedPrototypes[i] === val) { + return true; + } + } + return false; + }; + if (es5.isES5) { - var oProto = Object.prototype; var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); - while (obj != null && obj !== oProto) { + while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); @@ -141,11 +153,23 @@ var inheritedDataKeys = (function() { return ret; }; } else { + var hasProp = {}.hasOwnProperty; return function(obj) { + if (isExcludedProto(obj)) return []; var ret = []; + /*jshint forin:false */ - for (var key in obj) { - ret.push(key); + enumeration: for (var key in obj) { + if (hasProp.call(obj, key)) { + ret.push(key); + } else { + for (var i = 0; i < excludedPrototypes.length; ++i) { + if (hasProp.call(excludedPrototypes[i], key)) { + continue enumeration; + } + } + ret.push(key); + } } return ret; }; @@ -153,13 +177,22 @@ var inheritedDataKeys = (function() { })(); +var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); - if (es5.isES5) return keys.length > 1; - return keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); + + var hasMethods = es5.isES5 && keys.length > 1; + var hasMethodsOtherThanConstructor = keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + var hasThisAssignmentAndStaticMethods = + thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; + + if (hasMethods || hasMethodsOtherThanConstructor || + hasThisAssignmentAndStaticMethods) { + return true; + } } return false; } catch (e) { @@ -239,7 +272,9 @@ function copyDescriptors(from, to, filter) { for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); + try { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } catch (ignore) {} } } } @@ -261,7 +296,6 @@ var ret = { inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, - wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, @@ -276,5 +310,12 @@ var ret = { isNode: typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]" }; +ret.isRecentNode = ret.isNode && (function() { + var version = process.versions.node.split(".").map(Number); + return (version[0] === 0 && version[1] > 10) || (version[0] > 0); +})(); + +if (ret.isNode) ret.toFastProperties(process); + try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; diff --git a/node_modules/express-validator/node_modules/bluebird/package.json b/node_modules/express-validator/node_modules/bluebird/package.json new file mode 100644 index 0000000..b3255ae --- /dev/null +++ b/node_modules/express-validator/node_modules/bluebird/package.json @@ -0,0 +1,127 @@ +{ + "_args": [ + [ + "bluebird@^2.9.x", + "/Users/akira/src/biomedjs/node_modules/express-validator" + ] + ], + "_from": "bluebird@>=2.9.0 <3.0.0", + "_id": "bluebird@2.10.2", + "_inCache": true, + "_installable": true, + "_location": "/express-validator/bluebird", + "_nodeVersion": "2.3.0", + "_npmUser": { + "email": "petka_antonov@hotmail.com", + "name": "esailija" + }, + "_npmVersion": "2.11.1", + "_phantomChildren": {}, + "_requested": { + "name": "bluebird", + "raw": "bluebird@^2.9.x", + "rawSpec": "^2.9.x", + "scope": null, + "spec": ">=2.9.0 <3.0.0", + "type": "range" + }, + "_requiredBy": [ + "/express-validator" + ], + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.10.2.tgz", + "_shasum": "024a5517295308857f14f91f1106fc3b555f446b", + "_shrinkwrap": null, + "_spec": "bluebird@^2.9.x", + "_where": "/Users/akira/src/biomedjs/node_modules/express-validator", + "author": { + "email": "petka_antonov@hotmail.com", + "name": "Petka Antonov", + "url": "http://github.com/petkaantonov/" + }, + "browser": "./js/browser/bluebird.js", + "bugs": { + "url": "http://github.com/petkaantonov/bluebird/issues" + }, + "dependencies": {}, + "description": "Full featured Promises/A+ implementation with exceptionally good performance", + "devDependencies": { + "acorn": "~0.6.0", + "baconjs": "^0.7.43", + "bluebird": "^2.9.2", + "body-parser": "^1.10.2", + "browserify": "^8.1.1", + "cli-table": "~0.3.1", + "co": "^4.2.0", + "cross-spawn": "^0.2.3", + "glob": "^4.3.2", + "grunt-saucelabs": "~8.4.1", + "highland": "^2.3.0", + "istanbul": "^0.3.5", + "jshint": "^2.6.0", + "jshint-stylish": "~0.2.0", + "kefir": "^2.4.1", + "mkdirp": "~0.5.0", + "mocha": "~2.1", + "open": "~0.0.5", + "optimist": "~0.6.1", + "rimraf": "~2.2.6", + "rx": "^2.3.25", + "serve-static": "^1.7.1", + "sinon": "~1.7.3", + "uglify-js": "~2.4.16" + }, + "directories": {}, + "dist": { + "shasum": "024a5517295308857f14f91f1106fc3b555f446b", + "tarball": "http://registry.npmjs.org/bluebird/-/bluebird-2.10.2.tgz" + }, + "files": [ + "js/browser", + "js/main", + "js/zalgo", + "zalgo.js" + ], + "gitHead": "02c0fd252cf7c0c86e6b27bb06422c404829b539", + "homepage": "https://github.com/petkaantonov/bluebird", + "keywords": [ + "async", + "await", + "concurrency", + "deferred", + "deferreds", + "dsl", + "flow control", + "fluent interface", + "future", + "parallel", + "performance", + "promise", + "promises", + "promises-a", + "promises-aplus", + "thread" + ], + "license": "MIT", + "main": "./js/main/bluebird.js", + "maintainers": [ + { + "name": "esailija", + "email": "petka_antonov@hotmail.com" + } + ], + "name": "bluebird", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "scripts": { + "generate-browser-core": "node tools/build.js --features=core --no-debug --main --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js", + "istanbul": "istanbul", + "lint": "node scripts/jshint.js", + "prepublish": "node tools/build.js --no-debug --main --zalgo --browser --minify", + "test": "node tools/test.js" + }, + "version": "2.10.2" +} diff --git a/node_modules/express-validator/node_modules/lodash/LICENSE b/node_modules/express-validator/node_modules/lodash/LICENSE new file mode 100644 index 0000000..9cd87e5 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/LICENSE @@ -0,0 +1,22 @@ +Copyright 2012-2015 The Dojo Foundation +Based on Underscore.js, copyright 2009-2015 Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +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. diff --git a/node_modules/express-validator/node_modules/lodash/README.md b/node_modules/express-validator/node_modules/lodash/README.md new file mode 100644 index 0000000..fd98e5c --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/README.md @@ -0,0 +1,121 @@ +# lodash v3.10.1 + +The [modern build](https://github.com/lodash/lodash/wiki/Build-Differences) of [lodash](https://lodash.com/) exported as [Node.js](http://nodejs.org/)/[io.js](https://iojs.org/) modules. + +Generated using [lodash-cli](https://www.npmjs.com/package/lodash-cli): +```bash +$ lodash modularize modern exports=node -o ./ +$ lodash modern -d -o ./index.js +``` + +## Installation + +Using npm: + +```bash +$ {sudo -H} npm i -g npm +$ npm i --save lodash +``` + +In Node.js/io.js: + +```js +// load the modern build +var _ = require('lodash'); +// or a method category +var array = require('lodash/array'); +// or a method (great for smaller builds with browserify/webpack) +var chunk = require('lodash/array/chunk'); +``` + +See the [package source](https://github.com/lodash/lodash/tree/3.10.1-npm) for more details. + +**Note:**
+Don’t assign values to the [special variable](http://nodejs.org/api/repl.html#repl_repl_features) `_` when in the REPL.
+Install [n_](https://www.npmjs.com/package/n_) for a REPL that includes lodash by default. + +## Module formats + +lodash is also available in a variety of other builds & module formats. + + * npm packages for [modern](https://www.npmjs.com/package/lodash), [compatibility](https://www.npmjs.com/package/lodash-compat), & [per method](https://www.npmjs.com/browse/keyword/lodash-modularized) builds + * AMD modules for [modern](https://github.com/lodash/lodash/tree/3.10.1-amd) & [compatibility](https://github.com/lodash/lodash-compat/tree/3.10.1-amd) builds + * ES modules for the [modern](https://github.com/lodash/lodash/tree/3.10.1-es) build + +## Further Reading + + * [API Documentation](https://lodash.com/docs) + * [Build Differences](https://github.com/lodash/lodash/wiki/Build-Differences) + * [Changelog](https://github.com/lodash/lodash/wiki/Changelog) + * [Roadmap](https://github.com/lodash/lodash/wiki/Roadmap) + * [More Resources](https://github.com/lodash/lodash/wiki/Resources) + +## Features + + * ~100% [code coverage](https://coveralls.io/r/lodash) + * Follows [semantic versioning](http://semver.org/) for releases + * [Lazily evaluated](http://filimanjaro.com/blog/2014/introducing-lazy-evaluation/) chaining + * [_(…)](https://lodash.com/docs#_) supports implicit chaining + * [_.ary](https://lodash.com/docs#ary) & [_.rearg](https://lodash.com/docs#rearg) to change function argument limits & order + * [_.at](https://lodash.com/docs#at) for cherry-picking collection values + * [_.attempt](https://lodash.com/docs#attempt) to execute functions which may error without a try-catch + * [_.before](https://lodash.com/docs#before) to complement [_.after](https://lodash.com/docs#after) + * [_.bindKey](https://lodash.com/docs#bindKey) for binding [*“lazy”*](http://michaux.ca/articles/lazy-function-definition-pattern) defined methods + * [_.chunk](https://lodash.com/docs#chunk) for splitting an array into chunks of a given size + * [_.clone](https://lodash.com/docs#clone) supports shallow cloning of `Date` & `RegExp` objects + * [_.cloneDeep](https://lodash.com/docs#cloneDeep) for deep cloning arrays & objects + * [_.curry](https://lodash.com/docs#curry) & [_.curryRight](https://lodash.com/docs#curryRight) for creating [curried](http://hughfdjackson.com/javascript/why-curry-helps/) functions + * [_.debounce](https://lodash.com/docs#debounce) & [_.throttle](https://lodash.com/docs#throttle) are cancelable & accept options for more control + * [_.defaultsDeep](https://lodash.com/docs#defaultsDeep) for recursively assigning default properties + * [_.fill](https://lodash.com/docs#fill) to fill arrays with values + * [_.findKey](https://lodash.com/docs#findKey) for finding keys + * [_.flow](https://lodash.com/docs#flow) to complement [_.flowRight](https://lodash.com/docs#flowRight) (a.k.a `_.compose`) + * [_.forEach](https://lodash.com/docs#forEach) supports exiting early + * [_.forIn](https://lodash.com/docs#forIn) for iterating all enumerable properties + * [_.forOwn](https://lodash.com/docs#forOwn) for iterating own properties + * [_.get](https://lodash.com/docs#get) & [_.set](https://lodash.com/docs#set) for deep property getting & setting + * [_.gt](https://lodash.com/docs#gt), [_.gte](https://lodash.com/docs#gte), [_.lt](https://lodash.com/docs#lt), & [_.lte](https://lodash.com/docs#lte) relational methods + * [_.inRange](https://lodash.com/docs#inRange) for checking whether a number is within a given range + * [_.isNative](https://lodash.com/docs#isNative) to check for native functions + * [_.isPlainObject](https://lodash.com/docs#isPlainObject) & [_.toPlainObject](https://lodash.com/docs#toPlainObject) to check for & convert to `Object` objects + * [_.isTypedArray](https://lodash.com/docs#isTypedArray) to check for typed arrays + * [_.mapKeys](https://lodash.com/docs#mapKeys) for mapping keys to an object + * [_.matches](https://lodash.com/docs#matches) supports deep object comparisons + * [_.matchesProperty](https://lodash.com/docs#matchesProperty) to complement [_.matches](https://lodash.com/docs#matches) & [_.property](https://lodash.com/docs#property) + * [_.merge](https://lodash.com/docs#merge) for a deep [_.extend](https://lodash.com/docs#extend) + * [_.method](https://lodash.com/docs#method) & [_.methodOf](https://lodash.com/docs#methodOf) to create functions that invoke methods + * [_.modArgs](https://lodash.com/docs#modArgs) for more advanced functional composition + * [_.parseInt](https://lodash.com/docs#parseInt) for consistent cross-environment behavior + * [_.pull](https://lodash.com/docs#pull), [_.pullAt](https://lodash.com/docs#pullAt), & [_.remove](https://lodash.com/docs#remove) for mutating arrays + * [_.random](https://lodash.com/docs#random) supports returning floating-point numbers + * [_.restParam](https://lodash.com/docs#restParam) & [_.spread](https://lodash.com/docs#spread) for applying rest parameters & spreading arguments to functions + * [_.runInContext](https://lodash.com/docs#runInContext) for collisionless mixins & easier mocking + * [_.slice](https://lodash.com/docs#slice) for creating subsets of array-like values + * [_.sortByAll](https://lodash.com/docs#sortByAll) & [_.sortByOrder](https://lodash.com/docs#sortByOrder) for sorting by multiple properties & orders + * [_.support](https://lodash.com/docs#support) for flagging environment features + * [_.template](https://lodash.com/docs#template) supports [*“imports”*](https://lodash.com/docs#templateSettings-imports) options & [ES template delimiters](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components) + * [_.transform](https://lodash.com/docs#transform) as a powerful alternative to [_.reduce](https://lodash.com/docs#reduce) for transforming objects + * [_.unzipWith](https://lodash.com/docs#unzipWith) & [_.zipWith](https://lodash.com/docs#zipWith) to specify how grouped values should be combined + * [_.valuesIn](https://lodash.com/docs#valuesIn) for getting values of all enumerable properties + * [_.xor](https://lodash.com/docs#xor) to complement [_.difference](https://lodash.com/docs#difference), [_.intersection](https://lodash.com/docs#intersection), & [_.union](https://lodash.com/docs#union) + * [_.add](https://lodash.com/docs#add), [_.round](https://lodash.com/docs#round), [_.sum](https://lodash.com/docs#sum), & + [more](https://lodash.com/docs "_.ceil & _.floor") math methods + * [_.bind](https://lodash.com/docs#bind), [_.curry](https://lodash.com/docs#curry), [_.partial](https://lodash.com/docs#partial), & + [more](https://lodash.com/docs "_.bindKey, _.curryRight, _.partialRight") support customizable argument placeholders + * [_.capitalize](https://lodash.com/docs#capitalize), [_.trim](https://lodash.com/docs#trim), & + [more](https://lodash.com/docs "_.camelCase, _.deburr, _.endsWith, _.escapeRegExp, _.kebabCase, _.pad, _.padLeft, _.padRight, _.repeat, _.snakeCase, _.startCase, _.startsWith, _.trimLeft, _.trimRight, _.trunc, _.words") string methods + * [_.clone](https://lodash.com/docs#clone), [_.isEqual](https://lodash.com/docs#isEqual), & + [more](https://lodash.com/docs "_.assign, _.cloneDeep, _.merge") accept customizer callbacks + * [_.dropWhile](https://lodash.com/docs#dropWhile), [_.takeWhile](https://lodash.com/docs#takeWhile), & + [more](https://lodash.com/docs "_.drop, _.dropRight, _.dropRightWhile, _.take, _.takeRight, _.takeRightWhile") to complement [_.first](https://lodash.com/docs#first), [_.initial](https://lodash.com/docs#initial), [_.last](https://lodash.com/docs#last), & [_.rest](https://lodash.com/docs#rest) + * [_.findLast](https://lodash.com/docs#findLast), [_.findLastKey](https://lodash.com/docs#findLastKey), & + [more](https://lodash.com/docs "_.curryRight, _.dropRight, _.dropRightWhile, _.flowRight, _.forEachRight, _.forInRight, _.forOwnRight, _.padRight, partialRight, _.takeRight, _.trimRight, _.takeRightWhile") right-associative methods + * [_.includes](https://lodash.com/docs#includes), [_.toArray](https://lodash.com/docs#toArray), & + [more](https://lodash.com/docs "_.at, _.countBy, _.every, _.filter, _.find, _.findLast, _.findWhere, _.forEach, _.forEachRight, _.groupBy, _.indexBy, _.invoke, _.map, _.max, _.min, _.partition, _.pluck, _.reduce, _.reduceRight, _.reject, _.shuffle, _.size, _.some, _.sortBy, _.sortByAll, _.sortByOrder, _.sum, _.where") accept strings + * [_#commit](https://lodash.com/docs#prototype-commit) & [_#plant](https://lodash.com/docs#prototype-plant) for working with chain sequences + * [_#thru](https://lodash.com/docs#thru) to pass values thru a chain sequence + +## Support + +Tested in Chrome 43-44, Firefox 38-39, IE 6-11, MS Edge, Safari 5-8, ChakraNode 0.12.2, io.js 2.5.0, Node.js 0.8.28, 0.10.40, & 0.12.7, PhantomJS 1.9.8, RingoJS 0.11, & Rhino 1.7.6. +Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. Special thanks to [Sauce Labs](https://saucelabs.com/) for providing automated browser testing. diff --git a/node_modules/express-validator/node_modules/lodash/array.js b/node_modules/express-validator/node_modules/lodash/array.js new file mode 100644 index 0000000..e5121fa --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array.js @@ -0,0 +1,44 @@ +module.exports = { + 'chunk': require('./array/chunk'), + 'compact': require('./array/compact'), + 'difference': require('./array/difference'), + 'drop': require('./array/drop'), + 'dropRight': require('./array/dropRight'), + 'dropRightWhile': require('./array/dropRightWhile'), + 'dropWhile': require('./array/dropWhile'), + 'fill': require('./array/fill'), + 'findIndex': require('./array/findIndex'), + 'findLastIndex': require('./array/findLastIndex'), + 'first': require('./array/first'), + 'flatten': require('./array/flatten'), + 'flattenDeep': require('./array/flattenDeep'), + 'head': require('./array/head'), + 'indexOf': require('./array/indexOf'), + 'initial': require('./array/initial'), + 'intersection': require('./array/intersection'), + 'last': require('./array/last'), + 'lastIndexOf': require('./array/lastIndexOf'), + 'object': require('./array/object'), + 'pull': require('./array/pull'), + 'pullAt': require('./array/pullAt'), + 'remove': require('./array/remove'), + 'rest': require('./array/rest'), + 'slice': require('./array/slice'), + 'sortedIndex': require('./array/sortedIndex'), + 'sortedLastIndex': require('./array/sortedLastIndex'), + 'tail': require('./array/tail'), + 'take': require('./array/take'), + 'takeRight': require('./array/takeRight'), + 'takeRightWhile': require('./array/takeRightWhile'), + 'takeWhile': require('./array/takeWhile'), + 'union': require('./array/union'), + 'uniq': require('./array/uniq'), + 'unique': require('./array/unique'), + 'unzip': require('./array/unzip'), + 'unzipWith': require('./array/unzipWith'), + 'without': require('./array/without'), + 'xor': require('./array/xor'), + 'zip': require('./array/zip'), + 'zipObject': require('./array/zipObject'), + 'zipWith': require('./array/zipWith') +}; diff --git a/node_modules/express-validator/node_modules/lodash/array/chunk.js b/node_modules/express-validator/node_modules/lodash/array/chunk.js new file mode 100644 index 0000000..c8be1fb --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/chunk.js @@ -0,0 +1,46 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeMax = Math.max; + +/** + * Creates an array of elements split into groups the length of `size`. + * If `collection` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new array containing chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ +function chunk(array, size, guard) { + if (guard ? isIterateeCall(array, size, guard) : size == null) { + size = 1; + } else { + size = nativeMax(nativeFloor(size) || 1, 1); + } + var index = 0, + length = array ? array.length : 0, + resIndex = -1, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[++resIndex] = baseSlice(array, index, (index += size)); + } + return result; +} + +module.exports = chunk; diff --git a/node_modules/express-validator/node_modules/lodash/array/compact.js b/node_modules/express-validator/node_modules/lodash/array/compact.js new file mode 100644 index 0000000..1dc1c55 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/compact.js @@ -0,0 +1,30 @@ +/** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ +function compact(array) { + var index = -1, + length = array ? array.length : 0, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[++resIndex] = value; + } + } + return result; +} + +module.exports = compact; diff --git a/node_modules/express-validator/node_modules/lodash/array/difference.js b/node_modules/express-validator/node_modules/lodash/array/difference.js new file mode 100644 index 0000000..128932a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/difference.js @@ -0,0 +1,29 @@ +var baseDifference = require('../internal/baseDifference'), + baseFlatten = require('../internal/baseFlatten'), + isArrayLike = require('../internal/isArrayLike'), + isObjectLike = require('../internal/isObjectLike'), + restParam = require('../function/restParam'); + +/** + * Creates an array of unique `array` values not included in the other + * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.difference([1, 2, 3], [4, 2]); + * // => [1, 3] + */ +var difference = restParam(function(array, values) { + return (isObjectLike(array) && isArrayLike(array)) + ? baseDifference(array, baseFlatten(values, false, true)) + : []; +}); + +module.exports = difference; diff --git a/node_modules/express-validator/node_modules/lodash/array/drop.js b/node_modules/express-validator/node_modules/lodash/array/drop.js new file mode 100644 index 0000000..039a0b5 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/drop.js @@ -0,0 +1,39 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function drop(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, n < 0 ? 0 : n); +} + +module.exports = drop; diff --git a/node_modules/express-validator/node_modules/lodash/array/dropRight.js b/node_modules/express-validator/node_modules/lodash/array/dropRight.js new file mode 100644 index 0000000..14b5eb6 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/dropRight.js @@ -0,0 +1,40 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function dropRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, 0, n < 0 ? 0 : n); +} + +module.exports = dropRight; diff --git a/node_modules/express-validator/node_modules/lodash/array/dropRightWhile.js b/node_modules/express-validator/node_modules/lodash/array/dropRightWhile.js new file mode 100644 index 0000000..be158bd --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/dropRightWhile.js @@ -0,0 +1,59 @@ +var baseCallback = require('../internal/baseCallback'), + baseWhile = require('../internal/baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that match the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRightWhile([1, 2, 3], function(n) { + * return n > 1; + * }); + * // => [1] + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); + * // => ['barney', 'fred'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.dropRightWhile(users, 'active', false), 'user'); + * // => ['barney'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.dropRightWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ +function dropRightWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, baseCallback(predicate, thisArg, 3), true, true) + : []; +} + +module.exports = dropRightWhile; diff --git a/node_modules/express-validator/node_modules/lodash/array/dropWhile.js b/node_modules/express-validator/node_modules/lodash/array/dropWhile.js new file mode 100644 index 0000000..d9eabae --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/dropWhile.js @@ -0,0 +1,59 @@ +var baseCallback = require('../internal/baseCallback'), + baseWhile = require('../internal/baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropWhile([1, 2, 3], function(n) { + * return n < 3; + * }); + * // => [3] + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.dropWhile(users, 'active', false), 'user'); + * // => ['pebbles'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.dropWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ +function dropWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, baseCallback(predicate, thisArg, 3), true) + : []; +} + +module.exports = dropWhile; diff --git a/node_modules/express-validator/node_modules/lodash/array/fill.js b/node_modules/express-validator/node_modules/lodash/array/fill.js new file mode 100644 index 0000000..2c8f6da --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/fill.js @@ -0,0 +1,44 @@ +var baseFill = require('../internal/baseFill'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8], '*', 1, 2); + * // => [4, '*', 8] + */ +function fill(array, value, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); +} + +module.exports = fill; diff --git a/node_modules/express-validator/node_modules/lodash/array/findIndex.js b/node_modules/express-validator/node_modules/lodash/array/findIndex.js new file mode 100644 index 0000000..2a6b8e1 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/findIndex.js @@ -0,0 +1,53 @@ +var createFindIndex = require('../internal/createFindIndex'); + +/** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(chr) { + * return chr.user == 'barney'; + * }); + * // => 0 + * + * // using the `_.matches` callback shorthand + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // using the `_.matchesProperty` callback shorthand + * _.findIndex(users, 'active', false); + * // => 0 + * + * // using the `_.property` callback shorthand + * _.findIndex(users, 'active'); + * // => 2 + */ +var findIndex = createFindIndex(); + +module.exports = findIndex; diff --git a/node_modules/express-validator/node_modules/lodash/array/findLastIndex.js b/node_modules/express-validator/node_modules/lodash/array/findLastIndex.js new file mode 100644 index 0000000..d6d8eca --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/findLastIndex.js @@ -0,0 +1,53 @@ +var createFindIndex = require('../internal/createFindIndex'); + +/** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(chr) { + * return chr.user == 'pebbles'; + * }); + * // => 2 + * + * // using the `_.matches` callback shorthand + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // using the `_.matchesProperty` callback shorthand + * _.findLastIndex(users, 'active', false); + * // => 2 + * + * // using the `_.property` callback shorthand + * _.findLastIndex(users, 'active'); + * // => 0 + */ +var findLastIndex = createFindIndex(true); + +module.exports = findLastIndex; diff --git a/node_modules/express-validator/node_modules/lodash/array/first.js b/node_modules/express-validator/node_modules/lodash/array/first.js new file mode 100644 index 0000000..b3b9c79 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/first.js @@ -0,0 +1,22 @@ +/** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @alias head + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([]); + * // => undefined + */ +function first(array) { + return array ? array[0] : undefined; +} + +module.exports = first; diff --git a/node_modules/express-validator/node_modules/lodash/array/flatten.js b/node_modules/express-validator/node_modules/lodash/array/flatten.js new file mode 100644 index 0000000..dc2eff8 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/flatten.js @@ -0,0 +1,32 @@ +var baseFlatten = require('../internal/baseFlatten'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Flattens a nested array. If `isDeep` is `true` the array is recursively + * flattened, otherwise it's only flattened a single level. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to flatten. + * @param {boolean} [isDeep] Specify a deep flatten. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, 3, [4]]]); + * // => [1, 2, 3, [4]] + * + * // using `isDeep` + * _.flatten([1, [2, 3, [4]]], true); + * // => [1, 2, 3, 4] + */ +function flatten(array, isDeep, guard) { + var length = array ? array.length : 0; + if (guard && isIterateeCall(array, isDeep, guard)) { + isDeep = false; + } + return length ? baseFlatten(array, isDeep) : []; +} + +module.exports = flatten; diff --git a/node_modules/express-validator/node_modules/lodash/array/flattenDeep.js b/node_modules/express-validator/node_modules/lodash/array/flattenDeep.js new file mode 100644 index 0000000..9f775fe --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/flattenDeep.js @@ -0,0 +1,21 @@ +var baseFlatten = require('../internal/baseFlatten'); + +/** + * Recursively flattens a nested array. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to recursively flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, 3, [4]]]); + * // => [1, 2, 3, 4] + */ +function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, true) : []; +} + +module.exports = flattenDeep; diff --git a/node_modules/express-validator/node_modules/lodash/array/head.js b/node_modules/express-validator/node_modules/lodash/array/head.js new file mode 100644 index 0000000..1961b08 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/head.js @@ -0,0 +1 @@ +module.exports = require('./first'); diff --git a/node_modules/express-validator/node_modules/lodash/array/indexOf.js b/node_modules/express-validator/node_modules/lodash/array/indexOf.js new file mode 100644 index 0000000..4cfc682 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/indexOf.js @@ -0,0 +1,53 @@ +var baseIndexOf = require('../internal/baseIndexOf'), + binaryIndex = require('../internal/binaryIndex'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the offset + * from the end of `array`. If `array` is sorted providing `true` for `fromIndex` + * performs a faster binary search. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=0] The index to search from or `true` + * to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // using `fromIndex` + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + * + * // performing a binary search + * _.indexOf([1, 1, 2, 2], 2, true); + * // => 2 + */ +function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + if (typeof fromIndex == 'number') { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; + } else if (fromIndex) { + var index = binaryIndex(array, value); + if (index < length && + (value === value ? (value === array[index]) : (array[index] !== array[index]))) { + return index; + } + return -1; + } + return baseIndexOf(array, value, fromIndex || 0); +} + +module.exports = indexOf; diff --git a/node_modules/express-validator/node_modules/lodash/array/initial.js b/node_modules/express-validator/node_modules/lodash/array/initial.js new file mode 100644 index 0000000..59b7a7d --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/initial.js @@ -0,0 +1,20 @@ +var dropRight = require('./dropRight'); + +/** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ +function initial(array) { + return dropRight(array, 1); +} + +module.exports = initial; diff --git a/node_modules/express-validator/node_modules/lodash/array/intersection.js b/node_modules/express-validator/node_modules/lodash/array/intersection.js new file mode 100644 index 0000000..f218432 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/intersection.js @@ -0,0 +1,58 @@ +var baseIndexOf = require('../internal/baseIndexOf'), + cacheIndexOf = require('../internal/cacheIndexOf'), + createCache = require('../internal/createCache'), + isArrayLike = require('../internal/isArrayLike'), + restParam = require('../function/restParam'); + +/** + * Creates an array of unique values that are included in all of the provided + * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of shared values. + * @example + * _.intersection([1, 2], [4, 2], [2, 1]); + * // => [2] + */ +var intersection = restParam(function(arrays) { + var othLength = arrays.length, + othIndex = othLength, + caches = Array(length), + indexOf = baseIndexOf, + isCommon = true, + result = []; + + while (othIndex--) { + var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : []; + caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null; + } + var array = arrays[0], + index = -1, + length = array ? array.length : 0, + seen = caches[0]; + + outer: + while (++index < length) { + value = array[index]; + if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) { + var othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) { + continue outer; + } + } + if (seen) { + seen.push(value); + } + result.push(value); + } + } + return result; +}); + +module.exports = intersection; diff --git a/node_modules/express-validator/node_modules/lodash/array/last.js b/node_modules/express-validator/node_modules/lodash/array/last.js new file mode 100644 index 0000000..299af31 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/last.js @@ -0,0 +1,19 @@ +/** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ +function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; +} + +module.exports = last; diff --git a/node_modules/express-validator/node_modules/lodash/array/lastIndexOf.js b/node_modules/express-validator/node_modules/lodash/array/lastIndexOf.js new file mode 100644 index 0000000..02b8062 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/lastIndexOf.js @@ -0,0 +1,60 @@ +var binaryIndex = require('../internal/binaryIndex'), + indexOfNaN = require('../internal/indexOfNaN'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=array.length-1] The index to search from + * or `true` to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // using `fromIndex` + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + * + * // performing a binary search + * _.lastIndexOf([1, 1, 2, 2], 2, true); + * // => 3 + */ +function lastIndexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1; + } else if (fromIndex) { + index = binaryIndex(array, value, true) - 1; + var other = array[index]; + if (value === value ? (value === other) : (other !== other)) { + return index; + } + return -1; + } + if (value !== value) { + return indexOfNaN(array, index, true); + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +module.exports = lastIndexOf; diff --git a/node_modules/express-validator/node_modules/lodash/array/object.js b/node_modules/express-validator/node_modules/lodash/array/object.js new file mode 100644 index 0000000..f4a3453 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/object.js @@ -0,0 +1 @@ +module.exports = require('./zipObject'); diff --git a/node_modules/express-validator/node_modules/lodash/array/pull.js b/node_modules/express-validator/node_modules/lodash/array/pull.js new file mode 100644 index 0000000..7bcbb4a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/pull.js @@ -0,0 +1,52 @@ +var baseIndexOf = require('../internal/baseIndexOf'); + +/** Used for native method references. */ +var arrayProto = Array.prototype; + +/** Native method references. */ +var splice = arrayProto.splice; + +/** + * Removes all provided values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * + * _.pull(array, 2, 3); + * console.log(array); + * // => [1, 1] + */ +function pull() { + var args = arguments, + array = args[0]; + + if (!(array && array.length)) { + return array; + } + var index = 0, + indexOf = baseIndexOf, + length = args.length; + + while (++index < length) { + var fromIndex = 0, + value = args[index]; + + while ((fromIndex = indexOf(array, value, fromIndex)) > -1) { + splice.call(array, fromIndex, 1); + } + } + return array; +} + +module.exports = pull; diff --git a/node_modules/express-validator/node_modules/lodash/array/pullAt.js b/node_modules/express-validator/node_modules/lodash/array/pullAt.js new file mode 100644 index 0000000..4ca2476 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/pullAt.js @@ -0,0 +1,40 @@ +var baseAt = require('../internal/baseAt'), + baseCompareAscending = require('../internal/baseCompareAscending'), + baseFlatten = require('../internal/baseFlatten'), + basePullAt = require('../internal/basePullAt'), + restParam = require('../function/restParam'); + +/** + * Removes elements from `array` corresponding to the given indexes and returns + * an array of the removed elements. Indexes may be specified as an array of + * indexes or as individual arguments. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove, + * specified as individual indexes or arrays of indexes. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [5, 10, 15, 20]; + * var evens = _.pullAt(array, 1, 3); + * + * console.log(array); + * // => [5, 15] + * + * console.log(evens); + * // => [10, 20] + */ +var pullAt = restParam(function(array, indexes) { + indexes = baseFlatten(indexes); + + var result = baseAt(array, indexes); + basePullAt(array, indexes.sort(baseCompareAscending)); + return result; +}); + +module.exports = pullAt; diff --git a/node_modules/express-validator/node_modules/lodash/array/remove.js b/node_modules/express-validator/node_modules/lodash/array/remove.js new file mode 100644 index 0000000..0cf979b --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/remove.js @@ -0,0 +1,64 @@ +var baseCallback = require('../internal/baseCallback'), + basePullAt = require('../internal/basePullAt'); + +/** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is bound to + * `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * **Note:** Unlike `_.filter`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ +function remove(array, predicate, thisArg) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = baseCallback(predicate, thisArg, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; +} + +module.exports = remove; diff --git a/node_modules/express-validator/node_modules/lodash/array/rest.js b/node_modules/express-validator/node_modules/lodash/array/rest.js new file mode 100644 index 0000000..9bfb734 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/rest.js @@ -0,0 +1,21 @@ +var drop = require('./drop'); + +/** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @alias tail + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + */ +function rest(array) { + return drop(array, 1); +} + +module.exports = rest; diff --git a/node_modules/express-validator/node_modules/lodash/array/slice.js b/node_modules/express-validator/node_modules/lodash/array/slice.js new file mode 100644 index 0000000..48ef1a1 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/slice.js @@ -0,0 +1,30 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of `Array#slice` to support node + * lists in IE < 9 and to ensure dense arrays are returned. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function slice(array, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + return baseSlice(array, start, end); +} + +module.exports = slice; diff --git a/node_modules/express-validator/node_modules/lodash/array/sortedIndex.js b/node_modules/express-validator/node_modules/lodash/array/sortedIndex.js new file mode 100644 index 0000000..6903bca --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/sortedIndex.js @@ -0,0 +1,53 @@ +var createSortedIndex = require('../internal/createSortedIndex'); + +/** + * Uses a binary search to determine the lowest index at which `value` should + * be inserted into `array` in order to maintain its sort order. If an iteratee + * function is provided it's invoked for `value` and each element of `array` + * to compute their sort ranking. The iteratee is bound to `thisArg` and + * invoked with one argument; (value). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + * + * _.sortedIndex([4, 4, 5, 5], 5); + * // => 2 + * + * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } }; + * + * // using an iteratee function + * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) { + * return this.data[word]; + * }, dict); + * // => 1 + * + * // using the `_.property` callback shorthand + * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 1 + */ +var sortedIndex = createSortedIndex(); + +module.exports = sortedIndex; diff --git a/node_modules/express-validator/node_modules/lodash/array/sortedLastIndex.js b/node_modules/express-validator/node_modules/lodash/array/sortedLastIndex.js new file mode 100644 index 0000000..81a4a86 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/sortedLastIndex.js @@ -0,0 +1,25 @@ +var createSortedIndex = require('../internal/createSortedIndex'); + +/** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 4, 5, 5], 5); + * // => 4 + */ +var sortedLastIndex = createSortedIndex(true); + +module.exports = sortedLastIndex; diff --git a/node_modules/express-validator/node_modules/lodash/array/tail.js b/node_modules/express-validator/node_modules/lodash/array/tail.js new file mode 100644 index 0000000..c5dfe77 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/tail.js @@ -0,0 +1 @@ +module.exports = require('./rest'); diff --git a/node_modules/express-validator/node_modules/lodash/array/take.js b/node_modules/express-validator/node_modules/lodash/array/take.js new file mode 100644 index 0000000..875917a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/take.js @@ -0,0 +1,39 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ +function take(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, 0, n < 0 ? 0 : n); +} + +module.exports = take; diff --git a/node_modules/express-validator/node_modules/lodash/array/takeRight.js b/node_modules/express-validator/node_modules/lodash/array/takeRight.js new file mode 100644 index 0000000..6e89c87 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/takeRight.js @@ -0,0 +1,40 @@ +var baseSlice = require('../internal/baseSlice'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ +function takeRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, n < 0 ? 0 : n); +} + +module.exports = takeRight; diff --git a/node_modules/express-validator/node_modules/lodash/array/takeRightWhile.js b/node_modules/express-validator/node_modules/lodash/array/takeRightWhile.js new file mode 100644 index 0000000..5464d13 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/takeRightWhile.js @@ -0,0 +1,59 @@ +var baseCallback = require('../internal/baseCallback'), + baseWhile = require('../internal/baseWhile'); + +/** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is bound to `thisArg` + * and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRightWhile([1, 2, 3], function(n) { + * return n > 1; + * }); + * // => [2, 3] + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); + * // => ['pebbles'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.takeRightWhile(users, 'active', false), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.takeRightWhile(users, 'active'), 'user'); + * // => [] + */ +function takeRightWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, baseCallback(predicate, thisArg, 3), false, true) + : []; +} + +module.exports = takeRightWhile; diff --git a/node_modules/express-validator/node_modules/lodash/array/takeWhile.js b/node_modules/express-validator/node_modules/lodash/array/takeWhile.js new file mode 100644 index 0000000..f7e28a1 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/takeWhile.js @@ -0,0 +1,59 @@ +var baseCallback = require('../internal/baseCallback'), + baseWhile = require('../internal/baseWhile'); + +/** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is bound to + * `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeWhile([1, 2, 3], function(n) { + * return n < 3; + * }); + * // => [1, 2] + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false}, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.takeWhile(users, 'active', false), 'user'); + * // => ['barney', 'fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.takeWhile(users, 'active'), 'user'); + * // => [] + */ +function takeWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, baseCallback(predicate, thisArg, 3)) + : []; +} + +module.exports = takeWhile; diff --git a/node_modules/express-validator/node_modules/lodash/array/union.js b/node_modules/express-validator/node_modules/lodash/array/union.js new file mode 100644 index 0000000..53cefe4 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/union.js @@ -0,0 +1,24 @@ +var baseFlatten = require('../internal/baseFlatten'), + baseUniq = require('../internal/baseUniq'), + restParam = require('../function/restParam'); + +/** + * Creates an array of unique values, in order, from all of the provided arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([1, 2], [4, 2], [2, 1]); + * // => [1, 2, 4] + */ +var union = restParam(function(arrays) { + return baseUniq(baseFlatten(arrays, false, true)); +}); + +module.exports = union; diff --git a/node_modules/express-validator/node_modules/lodash/array/uniq.js b/node_modules/express-validator/node_modules/lodash/array/uniq.js new file mode 100644 index 0000000..ae937ef --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/uniq.js @@ -0,0 +1,71 @@ +var baseCallback = require('../internal/baseCallback'), + baseUniq = require('../internal/baseUniq'), + isIterateeCall = require('../internal/isIterateeCall'), + sortedUniq = require('../internal/sortedUniq'); + +/** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurence of each element + * is kept. Providing `true` for `isSorted` performs a faster search algorithm + * for sorted arrays. If an iteratee function is provided it's invoked for + * each element in the array to generate the criterion by which uniqueness + * is computed. The `iteratee` is bound to `thisArg` and invoked with three + * arguments: (value, index, array). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias unique + * @category Array + * @param {Array} array The array to inspect. + * @param {boolean} [isSorted] Specify the array is sorted. + * @param {Function|Object|string} [iteratee] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new duplicate-value-free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + * + * // using `isSorted` + * _.uniq([1, 1, 2], true); + * // => [1, 2] + * + * // using an iteratee function + * _.uniq([1, 2.5, 1.5, 2], function(n) { + * return this.floor(n); + * }, Math); + * // => [1, 2.5] + * + * // using the `_.property` callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ +function uniq(array, isSorted, iteratee, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (isSorted != null && typeof isSorted != 'boolean') { + thisArg = iteratee; + iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted; + isSorted = false; + } + iteratee = iteratee == null ? iteratee : baseCallback(iteratee, thisArg, 3); + return (isSorted) + ? sortedUniq(array, iteratee) + : baseUniq(array, iteratee); +} + +module.exports = uniq; diff --git a/node_modules/express-validator/node_modules/lodash/array/unique.js b/node_modules/express-validator/node_modules/lodash/array/unique.js new file mode 100644 index 0000000..396de1b --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/unique.js @@ -0,0 +1 @@ +module.exports = require('./uniq'); diff --git a/node_modules/express-validator/node_modules/lodash/array/unzip.js b/node_modules/express-validator/node_modules/lodash/array/unzip.js new file mode 100644 index 0000000..0a539fa --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/unzip.js @@ -0,0 +1,47 @@ +var arrayFilter = require('../internal/arrayFilter'), + arrayMap = require('../internal/arrayMap'), + baseProperty = require('../internal/baseProperty'), + isArrayLike = require('../internal/isArrayLike'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + * + * _.unzip(zipped); + * // => [['fred', 'barney'], [30, 40], [true, false]] + */ +function unzip(array) { + if (!(array && array.length)) { + return []; + } + var index = -1, + length = 0; + + array = arrayFilter(array, function(group) { + if (isArrayLike(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + var result = Array(length); + while (++index < length) { + result[index] = arrayMap(array, baseProperty(index)); + } + return result; +} + +module.exports = unzip; diff --git a/node_modules/express-validator/node_modules/lodash/array/unzipWith.js b/node_modules/express-validator/node_modules/lodash/array/unzipWith.js new file mode 100644 index 0000000..324a2b1 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/unzipWith.js @@ -0,0 +1,41 @@ +var arrayMap = require('../internal/arrayMap'), + arrayReduce = require('../internal/arrayReduce'), + bindCallback = require('../internal/bindCallback'), + unzip = require('./unzip'); + +/** + * This method is like `_.unzip` except that it accepts an iteratee to specify + * how regrouped values should be combined. The `iteratee` is bound to `thisArg` + * and invoked with four arguments: (accumulator, value, index, group). + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee] The function to combine regrouped values. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ +function unzipWith(array, iteratee, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + iteratee = bindCallback(iteratee, thisArg, 4); + return arrayMap(result, function(group) { + return arrayReduce(group, iteratee, undefined, true); + }); +} + +module.exports = unzipWith; diff --git a/node_modules/express-validator/node_modules/lodash/array/without.js b/node_modules/express-validator/node_modules/lodash/array/without.js new file mode 100644 index 0000000..2ac3d11 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/without.js @@ -0,0 +1,27 @@ +var baseDifference = require('../internal/baseDifference'), + isArrayLike = require('../internal/isArrayLike'), + restParam = require('../function/restParam'); + +/** + * Creates an array excluding all provided values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to filter. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.without([1, 2, 1, 3], 1, 2); + * // => [3] + */ +var without = restParam(function(array, values) { + return isArrayLike(array) + ? baseDifference(array, values) + : []; +}); + +module.exports = without; diff --git a/node_modules/express-validator/node_modules/lodash/array/xor.js b/node_modules/express-validator/node_modules/lodash/array/xor.js new file mode 100644 index 0000000..04ef32a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/xor.js @@ -0,0 +1,35 @@ +var arrayPush = require('../internal/arrayPush'), + baseDifference = require('../internal/baseDifference'), + baseUniq = require('../internal/baseUniq'), + isArrayLike = require('../internal/isArrayLike'); + +/** + * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the provided arrays. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of values. + * @example + * + * _.xor([1, 2], [4, 2]); + * // => [1, 4] + */ +function xor() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var array = arguments[index]; + if (isArrayLike(array)) { + var result = result + ? arrayPush(baseDifference(result, array), baseDifference(array, result)) + : array; + } + } + return result ? baseUniq(result) : []; +} + +module.exports = xor; diff --git a/node_modules/express-validator/node_modules/lodash/array/zip.js b/node_modules/express-validator/node_modules/lodash/array/zip.js new file mode 100644 index 0000000..53a6f69 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/zip.js @@ -0,0 +1,21 @@ +var restParam = require('../function/restParam'), + unzip = require('./unzip'); + +/** + * Creates an array of grouped elements, the first of which contains the first + * elements of the given arrays, the second of which contains the second elements + * of the given arrays, and so on. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + */ +var zip = restParam(unzip); + +module.exports = zip; diff --git a/node_modules/express-validator/node_modules/lodash/array/zipObject.js b/node_modules/express-validator/node_modules/lodash/array/zipObject.js new file mode 100644 index 0000000..dec7a21 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/zipObject.js @@ -0,0 +1,43 @@ +var isArray = require('../lang/isArray'); + +/** + * The inverse of `_.pairs`; this method returns an object composed from arrays + * of property names and values. Provide either a single two dimensional array, + * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names + * and one of corresponding values. + * + * @static + * @memberOf _ + * @alias object + * @category Array + * @param {Array} props The property names. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject([['fred', 30], ['barney', 40]]); + * // => { 'fred': 30, 'barney': 40 } + * + * _.zipObject(['fred', 'barney'], [30, 40]); + * // => { 'fred': 30, 'barney': 40 } + */ +function zipObject(props, values) { + var index = -1, + length = props ? props.length : 0, + result = {}; + + if (length && !values && !isArray(props[0])) { + values = []; + } + while (++index < length) { + var key = props[index]; + if (values) { + result[key] = values[index]; + } else if (key) { + result[key[0]] = key[1]; + } + } + return result; +} + +module.exports = zipObject; diff --git a/node_modules/express-validator/node_modules/lodash/array/zipWith.js b/node_modules/express-validator/node_modules/lodash/array/zipWith.js new file mode 100644 index 0000000..ad10374 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/array/zipWith.js @@ -0,0 +1,36 @@ +var restParam = require('../function/restParam'), + unzipWith = require('./unzipWith'); + +/** + * This method is like `_.zip` except that it accepts an iteratee to specify + * how grouped values should be combined. The `iteratee` is bound to `thisArg` + * and invoked with four arguments: (accumulator, value, index, group). + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee] The function to combine grouped values. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], _.add); + * // => [111, 222] + */ +var zipWith = restParam(function(arrays) { + var length = arrays.length, + iteratee = length > 2 ? arrays[length - 2] : undefined, + thisArg = length > 1 ? arrays[length - 1] : undefined; + + if (length > 2 && typeof iteratee == 'function') { + length -= 2; + } else { + iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined; + thisArg = undefined; + } + arrays.length = length; + return unzipWith(arrays, iteratee, thisArg); +}); + +module.exports = zipWith; diff --git a/node_modules/express-validator/node_modules/lodash/chain.js b/node_modules/express-validator/node_modules/lodash/chain.js new file mode 100644 index 0000000..6439627 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain.js @@ -0,0 +1,16 @@ +module.exports = { + 'chain': require('./chain/chain'), + 'commit': require('./chain/commit'), + 'concat': require('./chain/concat'), + 'lodash': require('./chain/lodash'), + 'plant': require('./chain/plant'), + 'reverse': require('./chain/reverse'), + 'run': require('./chain/run'), + 'tap': require('./chain/tap'), + 'thru': require('./chain/thru'), + 'toJSON': require('./chain/toJSON'), + 'toString': require('./chain/toString'), + 'value': require('./chain/value'), + 'valueOf': require('./chain/valueOf'), + 'wrapperChain': require('./chain/wrapperChain') +}; diff --git a/node_modules/express-validator/node_modules/lodash/chain/chain.js b/node_modules/express-validator/node_modules/lodash/chain/chain.js new file mode 100644 index 0000000..453ba1e --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/chain.js @@ -0,0 +1,35 @@ +var lodash = require('./lodash'); + +/** + * Creates a `lodash` object that wraps `value` with explicit method + * chaining enabled. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _.chain(users) + * .sortBy('age') + * .map(function(chr) { + * return chr.user + ' is ' + chr.age; + * }) + * .first() + * .value(); + * // => 'pebbles is 1' + */ +function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; +} + +module.exports = chain; diff --git a/node_modules/express-validator/node_modules/lodash/chain/commit.js b/node_modules/express-validator/node_modules/lodash/chain/commit.js new file mode 100644 index 0000000..c732d1b --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/commit.js @@ -0,0 +1 @@ +module.exports = require('./wrapperCommit'); diff --git a/node_modules/express-validator/node_modules/lodash/chain/concat.js b/node_modules/express-validator/node_modules/lodash/chain/concat.js new file mode 100644 index 0000000..90607d1 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/concat.js @@ -0,0 +1 @@ +module.exports = require('./wrapperConcat'); diff --git a/node_modules/express-validator/node_modules/lodash/chain/lodash.js b/node_modules/express-validator/node_modules/lodash/chain/lodash.js new file mode 100644 index 0000000..1c3467e --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/lodash.js @@ -0,0 +1,125 @@ +var LazyWrapper = require('../internal/LazyWrapper'), + LodashWrapper = require('../internal/LodashWrapper'), + baseLodash = require('../internal/baseLodash'), + isArray = require('../lang/isArray'), + isObjectLike = require('../internal/isObjectLike'), + wrapperClone = require('../internal/wrapperClone'); + +/** Used for native method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates a `lodash` object which wraps `value` to enable implicit chaining. + * Methods that operate on and return arrays, collections, and functions can + * be chained together. Methods that retrieve a single value or may return a + * primitive value will automatically end the chain returning the unwrapped + * value. Explicit chaining may be enabled using `_.chain`. The execution of + * chained methods is lazy, that is, execution is deferred until `_#value` + * is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. Shortcut + * fusion is an optimization strategy which merge iteratee calls; this can help + * to avoid the creation of intermediate data structures and greatly reduce the + * number of iteratee executions. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, + * `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, + * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, + * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, + * and `where` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, + * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, + * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`, + * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`, + * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, + * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, + * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, + * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, + * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`, + * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, + * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, + * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`, + * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, + * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`, + * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`, + * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`, + * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`, + * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, + * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, + * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`, + * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, + * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`, + * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`, + * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`, + * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`, + * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`, + * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`, + * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`, + * `unescape`, `uniqueId`, `value`, and `words` + * + * The wrapper method `sample` will return a wrapped value when `n` is provided, + * otherwise an unwrapped value is returned. + * + * @name _ + * @constructor + * @category Chain + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(total, n) { + * return total + n; + * }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(n) { + * return n * n; + * }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ +function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); +} + +// Ensure wrappers are instances of `baseLodash`. +lodash.prototype = baseLodash.prototype; + +module.exports = lodash; diff --git a/node_modules/express-validator/node_modules/lodash/chain/plant.js b/node_modules/express-validator/node_modules/lodash/chain/plant.js new file mode 100644 index 0000000..04099f2 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/plant.js @@ -0,0 +1 @@ +module.exports = require('./wrapperPlant'); diff --git a/node_modules/express-validator/node_modules/lodash/chain/reverse.js b/node_modules/express-validator/node_modules/lodash/chain/reverse.js new file mode 100644 index 0000000..f72a64a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/reverse.js @@ -0,0 +1 @@ +module.exports = require('./wrapperReverse'); diff --git a/node_modules/express-validator/node_modules/lodash/chain/run.js b/node_modules/express-validator/node_modules/lodash/chain/run.js new file mode 100644 index 0000000..5e751a2 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/run.js @@ -0,0 +1 @@ +module.exports = require('./wrapperValue'); diff --git a/node_modules/express-validator/node_modules/lodash/chain/tap.js b/node_modules/express-validator/node_modules/lodash/chain/tap.js new file mode 100644 index 0000000..3d0257e --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/tap.js @@ -0,0 +1,29 @@ +/** + * This method invokes `interceptor` and returns `value`. The interceptor is + * bound to `thisArg` and invoked with one argument; (value). The purpose of + * this method is to "tap into" a method chain in order to perform operations + * on intermediate results within the chain. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ +function tap(value, interceptor, thisArg) { + interceptor.call(thisArg, value); + return value; +} + +module.exports = tap; diff --git a/node_modules/express-validator/node_modules/lodash/chain/thru.js b/node_modules/express-validator/node_modules/lodash/chain/thru.js new file mode 100644 index 0000000..a715780 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/thru.js @@ -0,0 +1,26 @@ +/** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ +function thru(value, interceptor, thisArg) { + return interceptor.call(thisArg, value); +} + +module.exports = thru; diff --git a/node_modules/express-validator/node_modules/lodash/chain/toJSON.js b/node_modules/express-validator/node_modules/lodash/chain/toJSON.js new file mode 100644 index 0000000..5e751a2 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/toJSON.js @@ -0,0 +1 @@ +module.exports = require('./wrapperValue'); diff --git a/node_modules/express-validator/node_modules/lodash/chain/toString.js b/node_modules/express-validator/node_modules/lodash/chain/toString.js new file mode 100644 index 0000000..c7bcbf9 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/toString.js @@ -0,0 +1 @@ +module.exports = require('./wrapperToString'); diff --git a/node_modules/express-validator/node_modules/lodash/chain/value.js b/node_modules/express-validator/node_modules/lodash/chain/value.js new file mode 100644 index 0000000..5e751a2 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/value.js @@ -0,0 +1 @@ +module.exports = require('./wrapperValue'); diff --git a/node_modules/express-validator/node_modules/lodash/chain/valueOf.js b/node_modules/express-validator/node_modules/lodash/chain/valueOf.js new file mode 100644 index 0000000..5e751a2 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/valueOf.js @@ -0,0 +1 @@ +module.exports = require('./wrapperValue'); diff --git a/node_modules/express-validator/node_modules/lodash/chain/wrapperChain.js b/node_modules/express-validator/node_modules/lodash/chain/wrapperChain.js new file mode 100644 index 0000000..3823481 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/wrapperChain.js @@ -0,0 +1,32 @@ +var chain = require('./chain'); + +/** + * Enables explicit method chaining on the wrapper object. + * + * @name chain + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // without explicit chaining + * _(users).first(); + * // => { 'user': 'barney', 'age': 36 } + * + * // with explicit chaining + * _(users).chain() + * .first() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ +function wrapperChain() { + return chain(this); +} + +module.exports = wrapperChain; diff --git a/node_modules/express-validator/node_modules/lodash/chain/wrapperCommit.js b/node_modules/express-validator/node_modules/lodash/chain/wrapperCommit.js new file mode 100644 index 0000000..c3d2898 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/wrapperCommit.js @@ -0,0 +1,32 @@ +var LodashWrapper = require('../internal/LodashWrapper'); + +/** + * Executes the chained sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ +function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); +} + +module.exports = wrapperCommit; diff --git a/node_modules/express-validator/node_modules/lodash/chain/wrapperConcat.js b/node_modules/express-validator/node_modules/lodash/chain/wrapperConcat.js new file mode 100644 index 0000000..799156c --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/wrapperConcat.js @@ -0,0 +1,34 @@ +var arrayConcat = require('../internal/arrayConcat'), + baseFlatten = require('../internal/baseFlatten'), + isArray = require('../lang/isArray'), + restParam = require('../function/restParam'), + toObject = require('../internal/toObject'); + +/** + * Creates a new array joining a wrapped array with any additional arrays + * and/or values. + * + * @name concat + * @memberOf _ + * @category Chain + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var wrapped = _(array).concat(2, [3], [[4]]); + * + * console.log(wrapped.value()); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ +var wrapperConcat = restParam(function(values) { + values = baseFlatten(values); + return this.thru(function(array) { + return arrayConcat(isArray(array) ? array : [toObject(array)], values); + }); +}); + +module.exports = wrapperConcat; diff --git a/node_modules/express-validator/node_modules/lodash/chain/wrapperPlant.js b/node_modules/express-validator/node_modules/lodash/chain/wrapperPlant.js new file mode 100644 index 0000000..234fe41 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/wrapperPlant.js @@ -0,0 +1,45 @@ +var baseLodash = require('../internal/baseLodash'), + wrapperClone = require('../internal/wrapperClone'); + +/** + * Creates a clone of the chained sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).map(function(value) { + * return Math.pow(value, 2); + * }); + * + * var other = [3, 4]; + * var otherWrapped = wrapped.plant(other); + * + * otherWrapped.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ +function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; +} + +module.exports = wrapperPlant; diff --git a/node_modules/express-validator/node_modules/lodash/chain/wrapperReverse.js b/node_modules/express-validator/node_modules/lodash/chain/wrapperReverse.js new file mode 100644 index 0000000..6ba546d --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/wrapperReverse.js @@ -0,0 +1,43 @@ +var LazyWrapper = require('../internal/LazyWrapper'), + LodashWrapper = require('../internal/LodashWrapper'), + thru = require('./thru'); + +/** + * Reverses the wrapped array so the first element becomes the last, the + * second element becomes the second to last, and so on. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new reversed `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ +function wrapperReverse() { + var value = this.__wrapped__; + + var interceptor = function(value) { + return value.reverse(); + }; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(interceptor); +} + +module.exports = wrapperReverse; diff --git a/node_modules/express-validator/node_modules/lodash/chain/wrapperToString.js b/node_modules/express-validator/node_modules/lodash/chain/wrapperToString.js new file mode 100644 index 0000000..db975a5 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/wrapperToString.js @@ -0,0 +1,17 @@ +/** + * Produces the result of coercing the unwrapped value to a string. + * + * @name toString + * @memberOf _ + * @category Chain + * @returns {string} Returns the coerced string value. + * @example + * + * _([1, 2, 3]).toString(); + * // => '1,2,3' + */ +function wrapperToString() { + return (this.value() + ''); +} + +module.exports = wrapperToString; diff --git a/node_modules/express-validator/node_modules/lodash/chain/wrapperValue.js b/node_modules/express-validator/node_modules/lodash/chain/wrapperValue.js new file mode 100644 index 0000000..2734e41 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/chain/wrapperValue.js @@ -0,0 +1,20 @@ +var baseWrapperValue = require('../internal/baseWrapperValue'); + +/** + * Executes the chained sequence to extract the unwrapped value. + * + * @name value + * @memberOf _ + * @alias run, toJSON, valueOf + * @category Chain + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ +function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); +} + +module.exports = wrapperValue; diff --git a/node_modules/express-validator/node_modules/lodash/collection.js b/node_modules/express-validator/node_modules/lodash/collection.js new file mode 100644 index 0000000..0338857 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection.js @@ -0,0 +1,44 @@ +module.exports = { + 'all': require('./collection/all'), + 'any': require('./collection/any'), + 'at': require('./collection/at'), + 'collect': require('./collection/collect'), + 'contains': require('./collection/contains'), + 'countBy': require('./collection/countBy'), + 'detect': require('./collection/detect'), + 'each': require('./collection/each'), + 'eachRight': require('./collection/eachRight'), + 'every': require('./collection/every'), + 'filter': require('./collection/filter'), + 'find': require('./collection/find'), + 'findLast': require('./collection/findLast'), + 'findWhere': require('./collection/findWhere'), + 'foldl': require('./collection/foldl'), + 'foldr': require('./collection/foldr'), + 'forEach': require('./collection/forEach'), + 'forEachRight': require('./collection/forEachRight'), + 'groupBy': require('./collection/groupBy'), + 'include': require('./collection/include'), + 'includes': require('./collection/includes'), + 'indexBy': require('./collection/indexBy'), + 'inject': require('./collection/inject'), + 'invoke': require('./collection/invoke'), + 'map': require('./collection/map'), + 'max': require('./math/max'), + 'min': require('./math/min'), + 'partition': require('./collection/partition'), + 'pluck': require('./collection/pluck'), + 'reduce': require('./collection/reduce'), + 'reduceRight': require('./collection/reduceRight'), + 'reject': require('./collection/reject'), + 'sample': require('./collection/sample'), + 'select': require('./collection/select'), + 'shuffle': require('./collection/shuffle'), + 'size': require('./collection/size'), + 'some': require('./collection/some'), + 'sortBy': require('./collection/sortBy'), + 'sortByAll': require('./collection/sortByAll'), + 'sortByOrder': require('./collection/sortByOrder'), + 'sum': require('./math/sum'), + 'where': require('./collection/where') +}; diff --git a/node_modules/express-validator/node_modules/lodash/collection/all.js b/node_modules/express-validator/node_modules/lodash/collection/all.js new file mode 100644 index 0000000..d0839f7 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/all.js @@ -0,0 +1 @@ +module.exports = require('./every'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/any.js b/node_modules/express-validator/node_modules/lodash/collection/any.js new file mode 100644 index 0000000..900ac25 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/any.js @@ -0,0 +1 @@ +module.exports = require('./some'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/at.js b/node_modules/express-validator/node_modules/lodash/collection/at.js new file mode 100644 index 0000000..29236e5 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/at.js @@ -0,0 +1,29 @@ +var baseAt = require('../internal/baseAt'), + baseFlatten = require('../internal/baseFlatten'), + restParam = require('../function/restParam'); + +/** + * Creates an array of elements corresponding to the given keys, or indexes, + * of `collection`. Keys may be specified as individual arguments or as arrays + * of keys. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(number|number[]|string|string[])} [props] The property names + * or indexes of elements to pick, specified individually or in arrays. + * @returns {Array} Returns the new array of picked elements. + * @example + * + * _.at(['a', 'b', 'c'], [0, 2]); + * // => ['a', 'c'] + * + * _.at(['barney', 'fred', 'pebbles'], 0, 2); + * // => ['barney', 'pebbles'] + */ +var at = restParam(function(collection, props) { + return baseAt(collection, baseFlatten(props)); +}); + +module.exports = at; diff --git a/node_modules/express-validator/node_modules/lodash/collection/collect.js b/node_modules/express-validator/node_modules/lodash/collection/collect.js new file mode 100644 index 0000000..0d1e1ab --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/collect.js @@ -0,0 +1 @@ +module.exports = require('./map'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/contains.js b/node_modules/express-validator/node_modules/lodash/collection/contains.js new file mode 100644 index 0000000..594722a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/contains.js @@ -0,0 +1 @@ +module.exports = require('./includes'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/countBy.js b/node_modules/express-validator/node_modules/lodash/collection/countBy.js new file mode 100644 index 0000000..e97dbb7 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/countBy.js @@ -0,0 +1,54 @@ +var createAggregator = require('../internal/createAggregator'); + +/** Used for native method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the number of times the key was returned by `iteratee`. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(n) { + * return Math.floor(n); + * }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(n) { + * return this.floor(n); + * }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ +var countBy = createAggregator(function(result, value, key) { + hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); +}); + +module.exports = countBy; diff --git a/node_modules/express-validator/node_modules/lodash/collection/detect.js b/node_modules/express-validator/node_modules/lodash/collection/detect.js new file mode 100644 index 0000000..2fb6303 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/detect.js @@ -0,0 +1 @@ +module.exports = require('./find'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/each.js b/node_modules/express-validator/node_modules/lodash/collection/each.js new file mode 100644 index 0000000..8800f42 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/each.js @@ -0,0 +1 @@ +module.exports = require('./forEach'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/eachRight.js b/node_modules/express-validator/node_modules/lodash/collection/eachRight.js new file mode 100644 index 0000000..3252b2a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/eachRight.js @@ -0,0 +1 @@ +module.exports = require('./forEachRight'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/every.js b/node_modules/express-validator/node_modules/lodash/collection/every.js new file mode 100644 index 0000000..5a2d0f5 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/every.js @@ -0,0 +1,66 @@ +var arrayEvery = require('../internal/arrayEvery'), + baseCallback = require('../internal/baseCallback'), + baseEvery = require('../internal/baseEvery'), + isArray = require('../lang/isArray'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * The predicate is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // using the `_.matchesProperty` callback shorthand + * _.every(users, 'active', false); + * // => true + * + * // using the `_.property` callback shorthand + * _.every(users, 'active'); + * // => false + */ +function every(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (thisArg && isIterateeCall(collection, predicate, thisArg)) { + predicate = undefined; + } + if (typeof predicate != 'function' || thisArg !== undefined) { + predicate = baseCallback(predicate, thisArg, 3); + } + return func(collection, predicate); +} + +module.exports = every; diff --git a/node_modules/express-validator/node_modules/lodash/collection/filter.js b/node_modules/express-validator/node_modules/lodash/collection/filter.js new file mode 100644 index 0000000..7620aa7 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/filter.js @@ -0,0 +1,61 @@ +var arrayFilter = require('../internal/arrayFilter'), + baseCallback = require('../internal/baseCallback'), + baseFilter = require('../internal/baseFilter'), + isArray = require('../lang/isArray'); + +/** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * _.filter([4, 5, 6], function(n) { + * return n % 2 == 0; + * }); + * // => [4, 6] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.filter(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.filter(users, 'active'), 'user'); + * // => ['barney'] + */ +function filter(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = baseCallback(predicate, thisArg, 3); + return func(collection, predicate); +} + +module.exports = filter; diff --git a/node_modules/express-validator/node_modules/lodash/collection/find.js b/node_modules/express-validator/node_modules/lodash/collection/find.js new file mode 100644 index 0000000..7358cfe --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/find.js @@ -0,0 +1,56 @@ +var baseEach = require('../internal/baseEach'), + createFind = require('../internal/createFind'); + +/** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias detect + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.result(_.find(users, function(chr) { + * return chr.age < 40; + * }), 'user'); + * // => 'barney' + * + * // using the `_.matches` callback shorthand + * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); + * // => 'pebbles' + * + * // using the `_.matchesProperty` callback shorthand + * _.result(_.find(users, 'active', false), 'user'); + * // => 'fred' + * + * // using the `_.property` callback shorthand + * _.result(_.find(users, 'active'), 'user'); + * // => 'barney' + */ +var find = createFind(baseEach); + +module.exports = find; diff --git a/node_modules/express-validator/node_modules/lodash/collection/findLast.js b/node_modules/express-validator/node_modules/lodash/collection/findLast.js new file mode 100644 index 0000000..75dbadc --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/findLast.js @@ -0,0 +1,25 @@ +var baseEachRight = require('../internal/baseEachRight'), + createFind = require('../internal/createFind'); + +/** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ +var findLast = createFind(baseEachRight, true); + +module.exports = findLast; diff --git a/node_modules/express-validator/node_modules/lodash/collection/findWhere.js b/node_modules/express-validator/node_modules/lodash/collection/findWhere.js new file mode 100644 index 0000000..2d62065 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/findWhere.js @@ -0,0 +1,37 @@ +var baseMatches = require('../internal/baseMatches'), + find = require('./find'); + +/** + * Performs a deep comparison between each element in `collection` and the + * source object, returning the first element that has equivalent property + * values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user'); + * // => 'barney' + * + * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user'); + * // => 'fred' + */ +function findWhere(collection, source) { + return find(collection, baseMatches(source)); +} + +module.exports = findWhere; diff --git a/node_modules/express-validator/node_modules/lodash/collection/foldl.js b/node_modules/express-validator/node_modules/lodash/collection/foldl.js new file mode 100644 index 0000000..26f53cf --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/foldl.js @@ -0,0 +1 @@ +module.exports = require('./reduce'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/foldr.js b/node_modules/express-validator/node_modules/lodash/collection/foldr.js new file mode 100644 index 0000000..8fb199e --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/foldr.js @@ -0,0 +1 @@ +module.exports = require('./reduceRight'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/forEach.js b/node_modules/express-validator/node_modules/lodash/collection/forEach.js new file mode 100644 index 0000000..05a8e21 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/forEach.js @@ -0,0 +1,37 @@ +var arrayEach = require('../internal/arrayEach'), + baseEach = require('../internal/baseEach'), + createForEach = require('../internal/createForEach'); + +/** + * Iterates over elements of `collection` invoking `iteratee` for each element. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). Iteratee functions may exit iteration early + * by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" property + * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2]).forEach(function(n) { + * console.log(n); + * }).value(); + * // => logs each value from left to right and returns the array + * + * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { + * console.log(n, key); + * }); + * // => logs each value-key pair and returns the object (iteration order is not guaranteed) + */ +var forEach = createForEach(arrayEach, baseEach); + +module.exports = forEach; diff --git a/node_modules/express-validator/node_modules/lodash/collection/forEachRight.js b/node_modules/express-validator/node_modules/lodash/collection/forEachRight.js new file mode 100644 index 0000000..3499711 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/forEachRight.js @@ -0,0 +1,26 @@ +var arrayEachRight = require('../internal/arrayEachRight'), + baseEachRight = require('../internal/baseEachRight'), + createForEach = require('../internal/createForEach'); + +/** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias eachRight + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2]).forEachRight(function(n) { + * console.log(n); + * }).value(); + * // => logs each value from right to left and returns the array + */ +var forEachRight = createForEach(arrayEachRight, baseEachRight); + +module.exports = forEachRight; diff --git a/node_modules/express-validator/node_modules/lodash/collection/groupBy.js b/node_modules/express-validator/node_modules/lodash/collection/groupBy.js new file mode 100644 index 0000000..a925c89 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/groupBy.js @@ -0,0 +1,59 @@ +var createAggregator = require('../internal/createAggregator'); + +/** Used for native method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is an array of the elements responsible for generating the key. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { + * return Math.floor(n); + * }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { + * return this.floor(n); + * }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using the `_.property` callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ +var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + result[key] = [value]; + } +}); + +module.exports = groupBy; diff --git a/node_modules/express-validator/node_modules/lodash/collection/include.js b/node_modules/express-validator/node_modules/lodash/collection/include.js new file mode 100644 index 0000000..594722a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/include.js @@ -0,0 +1 @@ +module.exports = require('./includes'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/includes.js b/node_modules/express-validator/node_modules/lodash/collection/includes.js new file mode 100644 index 0000000..329486a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/includes.js @@ -0,0 +1,57 @@ +var baseIndexOf = require('../internal/baseIndexOf'), + getLength = require('../internal/getLength'), + isArray = require('../lang/isArray'), + isIterateeCall = require('../internal/isIterateeCall'), + isLength = require('../internal/isLength'), + isString = require('../lang/isString'), + values = require('../object/values'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Checks if `target` is in `collection` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the offset + * from the end of `collection`. + * + * @static + * @memberOf _ + * @alias contains, include + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {*} target The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. + * @returns {boolean} Returns `true` if a matching element is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); + * // => true + * + * _.includes('pebbles', 'eb'); + * // => true + */ +function includes(collection, target, fromIndex, guard) { + var length = collection ? getLength(collection) : 0; + if (!isLength(length)) { + collection = values(collection); + length = collection.length; + } + if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) { + fromIndex = 0; + } else { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); + } + return (typeof collection == 'string' || !isArray(collection) && isString(collection)) + ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1) + : (!!length && baseIndexOf(collection, target, fromIndex) > -1); +} + +module.exports = includes; diff --git a/node_modules/express-validator/node_modules/lodash/collection/indexBy.js b/node_modules/express-validator/node_modules/lodash/collection/indexBy.js new file mode 100644 index 0000000..34a941e --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/indexBy.js @@ -0,0 +1,53 @@ +var createAggregator = require('../internal/createAggregator'); + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the last element responsible for generating the key. The + * iteratee function is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var keyData = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.indexBy(keyData, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { + * return String.fromCharCode(object.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { + * return this.fromCharCode(object.code); + * }, String); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + */ +var indexBy = createAggregator(function(result, value, key) { + result[key] = value; +}); + +module.exports = indexBy; diff --git a/node_modules/express-validator/node_modules/lodash/collection/inject.js b/node_modules/express-validator/node_modules/lodash/collection/inject.js new file mode 100644 index 0000000..26f53cf --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/inject.js @@ -0,0 +1 @@ +module.exports = require('./reduce'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/invoke.js b/node_modules/express-validator/node_modules/lodash/collection/invoke.js new file mode 100644 index 0000000..6e71721 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/invoke.js @@ -0,0 +1,42 @@ +var baseEach = require('../internal/baseEach'), + invokePath = require('../internal/invokePath'), + isArrayLike = require('../internal/isArrayLike'), + isKey = require('../internal/isKey'), + restParam = require('../function/restParam'); + +/** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `methodName` is a function it's + * invoked for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ +var invoke = restParam(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + isProp = isKey(path), + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined); + result[++index] = func ? func.apply(value, args) : invokePath(value, path, args); + }); + return result; +}); + +module.exports = invoke; diff --git a/node_modules/express-validator/node_modules/lodash/collection/map.js b/node_modules/express-validator/node_modules/lodash/collection/map.js new file mode 100644 index 0000000..5381110 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/map.js @@ -0,0 +1,68 @@ +var arrayMap = require('../internal/arrayMap'), + baseCallback = require('../internal/baseCallback'), + baseMap = require('../internal/baseMap'), + isArray = require('../lang/isArray'); + +/** + * Creates an array of values by running each element in `collection` through + * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three + * arguments: (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, + * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, + * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, + * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, + * `sum`, `uniq`, and `words` + * + * @static + * @memberOf _ + * @alias collect + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new mapped array. + * @example + * + * function timesThree(n) { + * return n * 3; + * } + * + * _.map([1, 2], timesThree); + * // => [3, 6] + * + * _.map({ 'a': 1, 'b': 2 }, timesThree); + * // => [3, 6] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // using the `_.property` callback shorthand + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ +function map(collection, iteratee, thisArg) { + var func = isArray(collection) ? arrayMap : baseMap; + iteratee = baseCallback(iteratee, thisArg, 3); + return func(collection, iteratee); +} + +module.exports = map; diff --git a/node_modules/express-validator/node_modules/lodash/collection/max.js b/node_modules/express-validator/node_modules/lodash/collection/max.js new file mode 100644 index 0000000..bb1d213 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/max.js @@ -0,0 +1 @@ +module.exports = require('../math/max'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/min.js b/node_modules/express-validator/node_modules/lodash/collection/min.js new file mode 100644 index 0000000..eef13d0 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/min.js @@ -0,0 +1 @@ +module.exports = require('../math/min'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/partition.js b/node_modules/express-validator/node_modules/lodash/collection/partition.js new file mode 100644 index 0000000..ee35f27 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/partition.js @@ -0,0 +1,66 @@ +var createAggregator = require('../internal/createAggregator'); + +/** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, while the second of which + * contains elements `predicate` returns falsey for. The predicate is bound + * to `thisArg` and invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * _.partition([1, 2, 3], function(n) { + * return n % 2; + * }); + * // => [[1, 3], [2]] + * + * _.partition([1.2, 2.3, 3.4], function(n) { + * return this.floor(n) % 2; + * }, Math); + * // => [[1.2, 3.4], [2.3]] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * var mapper = function(array) { + * return _.pluck(array, 'user'); + * }; + * + * // using the `_.matches` callback shorthand + * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper); + * // => [['pebbles'], ['barney', 'fred']] + * + * // using the `_.matchesProperty` callback shorthand + * _.map(_.partition(users, 'active', false), mapper); + * // => [['barney', 'pebbles'], ['fred']] + * + * // using the `_.property` callback shorthand + * _.map(_.partition(users, 'active'), mapper); + * // => [['fred'], ['barney', 'pebbles']] + */ +var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); +}, function() { return [[], []]; }); + +module.exports = partition; diff --git a/node_modules/express-validator/node_modules/lodash/collection/pluck.js b/node_modules/express-validator/node_modules/lodash/collection/pluck.js new file mode 100644 index 0000000..5ee1ec8 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/pluck.js @@ -0,0 +1,31 @@ +var map = require('./map'), + property = require('../utility/property'); + +/** + * Gets the property value of `path` from all elements in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|string} path The path of the property to pluck. + * @returns {Array} Returns the property values. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * _.pluck(users, 'user'); + * // => ['barney', 'fred'] + * + * var userIndex = _.indexBy(users, 'user'); + * _.pluck(userIndex, 'age'); + * // => [36, 40] (iteration order is not guaranteed) + */ +function pluck(collection, path) { + return map(collection, property(path)); +} + +module.exports = pluck; diff --git a/node_modules/express-validator/node_modules/lodash/collection/reduce.js b/node_modules/express-validator/node_modules/lodash/collection/reduce.js new file mode 100644 index 0000000..5d5e8c9 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/reduce.js @@ -0,0 +1,44 @@ +var arrayReduce = require('../internal/arrayReduce'), + baseEach = require('../internal/baseEach'), + createReduce = require('../internal/createReduce'); + +/** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` through `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not provided the first element of `collection` is used as the initial + * value. The `iteratee` is bound to `thisArg` and invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`, + * and `sortByOrder` + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * _.reduce([1, 2], function(total, n) { + * return total + n; + * }); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) { + * result[key] = n * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed) + */ +var reduce = createReduce(arrayReduce, baseEach); + +module.exports = reduce; diff --git a/node_modules/express-validator/node_modules/lodash/collection/reduceRight.js b/node_modules/express-validator/node_modules/lodash/collection/reduceRight.js new file mode 100644 index 0000000..5a5753b --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/reduceRight.js @@ -0,0 +1,29 @@ +var arrayReduceRight = require('../internal/arrayReduceRight'), + baseEachRight = require('../internal/baseEachRight'), + createReduce = require('../internal/createReduce'); + +/** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ +var reduceRight = createReduce(arrayReduceRight, baseEachRight); + +module.exports = reduceRight; diff --git a/node_modules/express-validator/node_modules/lodash/collection/reject.js b/node_modules/express-validator/node_modules/lodash/collection/reject.js new file mode 100644 index 0000000..5592453 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/reject.js @@ -0,0 +1,50 @@ +var arrayFilter = require('../internal/arrayFilter'), + baseCallback = require('../internal/baseCallback'), + baseFilter = require('../internal/baseFilter'), + isArray = require('../lang/isArray'); + +/** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * _.reject([1, 2, 3, 4], function(n) { + * return n % 2 == 0; + * }); + * // => [1, 3] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.reject(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.reject(users, 'active'), 'user'); + * // => ['barney'] + */ +function reject(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = baseCallback(predicate, thisArg, 3); + return func(collection, function(value, index, collection) { + return !predicate(value, index, collection); + }); +} + +module.exports = reject; diff --git a/node_modules/express-validator/node_modules/lodash/collection/sample.js b/node_modules/express-validator/node_modules/lodash/collection/sample.js new file mode 100644 index 0000000..8e01533 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/sample.js @@ -0,0 +1,50 @@ +var baseRandom = require('../internal/baseRandom'), + isIterateeCall = require('../internal/isIterateeCall'), + toArray = require('../lang/toArray'), + toIterable = require('../internal/toIterable'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * Gets a random element or `n` random elements from a collection. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to sample. + * @param {number} [n] The number of elements to sample. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {*} Returns the random sample(s). + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + * + * _.sample([1, 2, 3, 4], 2); + * // => [3, 1] + */ +function sample(collection, n, guard) { + if (guard ? isIterateeCall(collection, n, guard) : n == null) { + collection = toIterable(collection); + var length = collection.length; + return length > 0 ? collection[baseRandom(0, length - 1)] : undefined; + } + var index = -1, + result = toArray(collection), + length = result.length, + lastIndex = length - 1; + + n = nativeMin(n < 0 ? 0 : (+n || 0), length); + while (++index < n) { + var rand = baseRandom(index, lastIndex), + value = result[rand]; + + result[rand] = result[index]; + result[index] = value; + } + result.length = n; + return result; +} + +module.exports = sample; diff --git a/node_modules/express-validator/node_modules/lodash/collection/select.js b/node_modules/express-validator/node_modules/lodash/collection/select.js new file mode 100644 index 0000000..ade80f6 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/select.js @@ -0,0 +1 @@ +module.exports = require('./filter'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/shuffle.js b/node_modules/express-validator/node_modules/lodash/collection/shuffle.js new file mode 100644 index 0000000..949689c --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/shuffle.js @@ -0,0 +1,24 @@ +var sample = require('./sample'); + +/** Used as references for `-Infinity` and `Infinity`. */ +var POSITIVE_INFINITY = Number.POSITIVE_INFINITY; + +/** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ +function shuffle(collection) { + return sample(collection, POSITIVE_INFINITY); +} + +module.exports = shuffle; diff --git a/node_modules/express-validator/node_modules/lodash/collection/size.js b/node_modules/express-validator/node_modules/lodash/collection/size.js new file mode 100644 index 0000000..78dcf4c --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/size.js @@ -0,0 +1,30 @@ +var getLength = require('../internal/getLength'), + isLength = require('../internal/isLength'), + keys = require('../object/keys'); + +/** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the size of `collection`. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ +function size(collection) { + var length = collection ? getLength(collection) : 0; + return isLength(length) ? length : keys(collection).length; +} + +module.exports = size; diff --git a/node_modules/express-validator/node_modules/lodash/collection/some.js b/node_modules/express-validator/node_modules/lodash/collection/some.js new file mode 100644 index 0000000..d0b09a4 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/some.js @@ -0,0 +1,67 @@ +var arraySome = require('../internal/arraySome'), + baseCallback = require('../internal/baseCallback'), + baseSome = require('../internal/baseSome'), + isArray = require('../lang/isArray'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * The function returns as soon as it finds a passing value and does not iterate + * over the entire collection. The predicate is bound to `thisArg` and invoked + * with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // using the `_.matchesProperty` callback shorthand + * _.some(users, 'active', false); + * // => true + * + * // using the `_.property` callback shorthand + * _.some(users, 'active'); + * // => true + */ +function some(collection, predicate, thisArg) { + var func = isArray(collection) ? arraySome : baseSome; + if (thisArg && isIterateeCall(collection, predicate, thisArg)) { + predicate = undefined; + } + if (typeof predicate != 'function' || thisArg !== undefined) { + predicate = baseCallback(predicate, thisArg, 3); + } + return func(collection, predicate); +} + +module.exports = some; diff --git a/node_modules/express-validator/node_modules/lodash/collection/sortBy.js b/node_modules/express-validator/node_modules/lodash/collection/sortBy.js new file mode 100644 index 0000000..4401c77 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/sortBy.js @@ -0,0 +1,71 @@ +var baseCallback = require('../internal/baseCallback'), + baseMap = require('../internal/baseMap'), + baseSortBy = require('../internal/baseSortBy'), + compareAscending = require('../internal/compareAscending'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through `iteratee`. This method performs + * a stable sort, that is, it preserves the original sort order of equal elements. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new sorted array. + * @example + * + * _.sortBy([1, 2, 3], function(n) { + * return Math.sin(n); + * }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(n) { + * return this.sin(n); + * }, Math); + * // => [3, 1, 2] + * + * var users = [ + * { 'user': 'fred' }, + * { 'user': 'pebbles' }, + * { 'user': 'barney' } + * ]; + * + * // using the `_.property` callback shorthand + * _.pluck(_.sortBy(users, 'user'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ +function sortBy(collection, iteratee, thisArg) { + if (collection == null) { + return []; + } + if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { + iteratee = undefined; + } + var index = -1; + iteratee = baseCallback(iteratee, thisArg, 3); + + var result = baseMap(collection, function(value, key, collection) { + return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value }; + }); + return baseSortBy(result, compareAscending); +} + +module.exports = sortBy; diff --git a/node_modules/express-validator/node_modules/lodash/collection/sortByAll.js b/node_modules/express-validator/node_modules/lodash/collection/sortByAll.js new file mode 100644 index 0000000..4766c20 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/sortByAll.js @@ -0,0 +1,52 @@ +var baseFlatten = require('../internal/baseFlatten'), + baseSortByOrder = require('../internal/baseSortByOrder'), + isIterateeCall = require('../internal/isIterateeCall'), + restParam = require('../function/restParam'); + +/** + * This method is like `_.sortBy` except that it can sort by multiple iteratees + * or property names. + * + * If a property name is provided for an iteratee the created `_.property` + * style callback returns the property value of the given element. + * + * If an object is provided for an iteratee the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees + * The iteratees to sort by, specified as individual values or arrays of values. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.map(_.sortByAll(users, ['user', 'age']), _.values); + * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] + * + * _.map(_.sortByAll(users, 'user', function(chr) { + * return Math.floor(chr.age / 10); + * }), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ +var sortByAll = restParam(function(collection, iteratees) { + if (collection == null) { + return []; + } + var guard = iteratees[2]; + if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) { + iteratees.length = 1; + } + return baseSortByOrder(collection, baseFlatten(iteratees), []); +}); + +module.exports = sortByAll; diff --git a/node_modules/express-validator/node_modules/lodash/collection/sortByOrder.js b/node_modules/express-validator/node_modules/lodash/collection/sortByOrder.js new file mode 100644 index 0000000..8b4fc19 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/sortByOrder.js @@ -0,0 +1,55 @@ +var baseSortByOrder = require('../internal/baseSortByOrder'), + isArray = require('../lang/isArray'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** + * This method is like `_.sortByAll` except that it allows specifying the + * sort orders of the iteratees to sort by. If `orders` is unspecified, all + * values are sorted in ascending order. Otherwise, a value is sorted in + * ascending order if its corresponding order is "asc", and descending if "desc". + * + * If a property name is provided for an iteratee the created `_.property` + * style callback returns the property value of the given element. + * + * If an object is provided for an iteratee the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {boolean[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // sort by `user` in ascending order and by `age` in descending order + * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ +function sortByOrder(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (guard && isIterateeCall(iteratees, orders, guard)) { + orders = undefined; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseSortByOrder(collection, iteratees, orders); +} + +module.exports = sortByOrder; diff --git a/node_modules/express-validator/node_modules/lodash/collection/sum.js b/node_modules/express-validator/node_modules/lodash/collection/sum.js new file mode 100644 index 0000000..a2e9380 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/sum.js @@ -0,0 +1 @@ +module.exports = require('../math/sum'); diff --git a/node_modules/express-validator/node_modules/lodash/collection/where.js b/node_modules/express-validator/node_modules/lodash/collection/where.js new file mode 100644 index 0000000..f603bf8 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/collection/where.js @@ -0,0 +1,37 @@ +var baseMatches = require('../internal/baseMatches'), + filter = require('./filter'); + +/** + * Performs a deep comparison between each element in `collection` and the + * source object, returning an array of all elements that have equivalent + * property values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {Array} Returns the new filtered array. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] }, + * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] } + * ]; + * + * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user'); + * // => ['barney'] + * + * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user'); + * // => ['fred'] + */ +function where(collection, source) { + return filter(collection, baseMatches(source)); +} + +module.exports = where; diff --git a/node_modules/express-validator/node_modules/lodash/date.js b/node_modules/express-validator/node_modules/lodash/date.js new file mode 100644 index 0000000..195366e --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/date.js @@ -0,0 +1,3 @@ +module.exports = { + 'now': require('./date/now') +}; diff --git a/node_modules/express-validator/node_modules/lodash/date/now.js b/node_modules/express-validator/node_modules/lodash/date/now.js new file mode 100644 index 0000000..ffe3060 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/date/now.js @@ -0,0 +1,24 @@ +var getNative = require('../internal/getNative'); + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeNow = getNative(Date, 'now'); + +/** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @category Date + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => logs the number of milliseconds it took for the deferred function to be invoked + */ +var now = nativeNow || function() { + return new Date().getTime(); +}; + +module.exports = now; diff --git a/node_modules/express-validator/node_modules/lodash/function.js b/node_modules/express-validator/node_modules/lodash/function.js new file mode 100644 index 0000000..71f8ebe --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function.js @@ -0,0 +1,28 @@ +module.exports = { + 'after': require('./function/after'), + 'ary': require('./function/ary'), + 'backflow': require('./function/backflow'), + 'before': require('./function/before'), + 'bind': require('./function/bind'), + 'bindAll': require('./function/bindAll'), + 'bindKey': require('./function/bindKey'), + 'compose': require('./function/compose'), + 'curry': require('./function/curry'), + 'curryRight': require('./function/curryRight'), + 'debounce': require('./function/debounce'), + 'defer': require('./function/defer'), + 'delay': require('./function/delay'), + 'flow': require('./function/flow'), + 'flowRight': require('./function/flowRight'), + 'memoize': require('./function/memoize'), + 'modArgs': require('./function/modArgs'), + 'negate': require('./function/negate'), + 'once': require('./function/once'), + 'partial': require('./function/partial'), + 'partialRight': require('./function/partialRight'), + 'rearg': require('./function/rearg'), + 'restParam': require('./function/restParam'), + 'spread': require('./function/spread'), + 'throttle': require('./function/throttle'), + 'wrap': require('./function/wrap') +}; diff --git a/node_modules/express-validator/node_modules/lodash/function/after.js b/node_modules/express-validator/node_modules/lodash/function/after.js new file mode 100644 index 0000000..96a51fd --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/after.js @@ -0,0 +1,48 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = global.isFinite; + +/** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => logs 'done saving!' after the two async saves have completed + */ +function after(n, func) { + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + n = nativeIsFinite(n = +n) ? n : 0; + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; +} + +module.exports = after; diff --git a/node_modules/express-validator/node_modules/lodash/function/ary.js b/node_modules/express-validator/node_modules/lodash/function/ary.js new file mode 100644 index 0000000..53a6913 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/ary.js @@ -0,0 +1,34 @@ +var createWrapper = require('../internal/createWrapper'), + isIterateeCall = require('../internal/isIterateeCall'); + +/** Used to compose bitmasks for wrapper metadata. */ +var ARY_FLAG = 128; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates a function that accepts up to `n` arguments ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ +function ary(func, n, guard) { + if (guard && isIterateeCall(func, n, guard)) { + n = undefined; + } + n = (func && n == null) ? func.length : nativeMax(+n || 0, 0); + return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n); +} + +module.exports = ary; diff --git a/node_modules/express-validator/node_modules/lodash/function/backflow.js b/node_modules/express-validator/node_modules/lodash/function/backflow.js new file mode 100644 index 0000000..1954e94 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/backflow.js @@ -0,0 +1 @@ +module.exports = require('./flowRight'); diff --git a/node_modules/express-validator/node_modules/lodash/function/before.js b/node_modules/express-validator/node_modules/lodash/function/before.js new file mode 100644 index 0000000..3d94216 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/before.js @@ -0,0 +1,42 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery('#add').on('click', _.before(5, addContactToList)); + * // => allows adding up to 4 contacts to the list + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; +} + +module.exports = before; diff --git a/node_modules/express-validator/node_modules/lodash/function/bind.js b/node_modules/express-validator/node_modules/lodash/function/bind.js new file mode 100644 index 0000000..0de126a --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/bind.js @@ -0,0 +1,56 @@ +var createWrapper = require('../internal/createWrapper'), + replaceHolders = require('../internal/replaceHolders'), + restParam = require('./restParam'); + +/** Used to compose bitmasks for wrapper metadata. */ +var BIND_FLAG = 1, + PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and prepends any additional `_.bind` arguments to those provided to the + * bound function. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind` this method does not set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var greet = function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * }; + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // using placeholders + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ +var bind = restParam(function(func, thisArg, partials) { + var bitmask = BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, bind.placeholder); + bitmask |= PARTIAL_FLAG; + } + return createWrapper(func, bitmask, thisArg, partials, holders); +}); + +// Assign default placeholders. +bind.placeholder = {}; + +module.exports = bind; diff --git a/node_modules/express-validator/node_modules/lodash/function/bindAll.js b/node_modules/express-validator/node_modules/lodash/function/bindAll.js new file mode 100644 index 0000000..a09e948 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/bindAll.js @@ -0,0 +1,50 @@ +var baseFlatten = require('../internal/baseFlatten'), + createWrapper = require('../internal/createWrapper'), + functions = require('../object/functions'), + restParam = require('./restParam'); + +/** Used to compose bitmasks for wrapper metadata. */ +var BIND_FLAG = 1; + +/** + * Binds methods of an object to the object itself, overwriting the existing + * method. Method names may be specified as individual arguments or as arrays + * of method names. If no method names are provided all enumerable function + * properties, own and inherited, of `object` are bound. + * + * **Note:** This method does not set the "length" property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...(string|string[])} [methodNames] The object method names to bind, + * specified as individual method names or arrays of method names. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { + * console.log('clicked ' + this.label); + * } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => logs 'clicked docs' when the element is clicked + */ +var bindAll = restParam(function(object, methodNames) { + methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object); + + var index = -1, + length = methodNames.length; + + while (++index < length) { + var key = methodNames[index]; + object[key] = createWrapper(object[key], BIND_FLAG, object); + } + return object; +}); + +module.exports = bindAll; diff --git a/node_modules/express-validator/node_modules/lodash/function/bindKey.js b/node_modules/express-validator/node_modules/lodash/function/bindKey.js new file mode 100644 index 0000000..b787fe7 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/bindKey.js @@ -0,0 +1,66 @@ +var createWrapper = require('../internal/createWrapper'), + replaceHolders = require('../internal/replaceHolders'), + restParam = require('./restParam'); + +/** Used to compose bitmasks for wrapper metadata. */ +var BIND_FLAG = 1, + BIND_KEY_FLAG = 2, + PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes the method at `object[key]` and prepends + * any additional `_.bindKey` arguments to those provided to the bound function. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. + * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object the method belongs to. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // using placeholders + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ +var bindKey = restParam(function(object, key, partials) { + var bitmask = BIND_FLAG | BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, bindKey.placeholder); + bitmask |= PARTIAL_FLAG; + } + return createWrapper(key, bitmask, object, partials, holders); +}); + +// Assign default placeholders. +bindKey.placeholder = {}; + +module.exports = bindKey; diff --git a/node_modules/express-validator/node_modules/lodash/function/compose.js b/node_modules/express-validator/node_modules/lodash/function/compose.js new file mode 100644 index 0000000..1954e94 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/compose.js @@ -0,0 +1 @@ +module.exports = require('./flowRight'); diff --git a/node_modules/express-validator/node_modules/lodash/function/curry.js b/node_modules/express-validator/node_modules/lodash/function/curry.js new file mode 100644 index 0000000..b7db3fd --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/curry.js @@ -0,0 +1,51 @@ +var createCurry = require('../internal/createCurry'); + +/** Used to compose bitmasks for wrapper metadata. */ +var CURRY_FLAG = 8; + +/** + * Creates a function that accepts one or more arguments of `func` that when + * called either invokes `func` returning its result, if all `func` arguments + * have been provided, or returns a function that accepts one or more of the + * remaining `func` arguments, and so on. The arity of `func` may be specified + * if `func.length` is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ +var curry = createCurry(CURRY_FLAG); + +// Assign default placeholders. +curry.placeholder = {}; + +module.exports = curry; diff --git a/node_modules/express-validator/node_modules/lodash/function/curryRight.js b/node_modules/express-validator/node_modules/lodash/function/curryRight.js new file mode 100644 index 0000000..11c5403 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/curryRight.js @@ -0,0 +1,48 @@ +var createCurry = require('../internal/createCurry'); + +/** Used to compose bitmasks for wrapper metadata. */ +var CURRY_RIGHT_FLAG = 16; + +/** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ +var curryRight = createCurry(CURRY_RIGHT_FLAG); + +// Assign default placeholders. +curryRight.placeholder = {}; + +module.exports = curryRight; diff --git a/node_modules/express-validator/node_modules/lodash/function/debounce.js b/node_modules/express-validator/node_modules/lodash/function/debounce.js new file mode 100644 index 0000000..163af90 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/debounce.js @@ -0,0 +1,181 @@ +var isObject = require('../lang/isObject'), + now = require('../date/now'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed invocations. Provide an options object to indicate that `func` + * should be invoked on the leading and/or trailing edge of the `wait` timeout. + * Subsequent calls to the debounced function return the result of the last + * `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the debounced function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=false] Specify invoking on the leading + * edge of the timeout. + * @param {number} [options.maxWait] The maximum time `func` is allowed to be + * delayed before it's invoked. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // avoid costly calculations while the window size is in flux + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // invoke `sendMail` when the click event is fired, debouncing subsequent calls + * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // ensure `batchLog` is invoked once after 1 second of debounced calls + * var source = new EventSource('/stream'); + * jQuery(source).on('message', _.debounce(batchLog, 250, { + * 'maxWait': 1000 + * })); + * + * // cancel a debounced call + * var todoChanges = _.debounce(batchLog, 1000); + * Object.observe(models.todo, todoChanges); + * + * Object.observe(models, function(changes) { + * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { + * todoChanges.cancel(); + * } + * }, ['delete']); + * + * // ...at some point `models.todo` is changed + * models.todo.completed = true; + * + * // ...before 1 second has passed `models.todo` is deleted + * // which cancels the debounced `todoChanges` call + * delete models.todo; + */ +function debounce(func, wait, options) { + var args, + maxTimeoutId, + result, + stamp, + thisArg, + timeoutId, + trailingCall, + lastCalled = 0, + maxWait = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = wait < 0 ? 0 : (+wait || 0); + if (options === true) { + var leading = true; + trailing = false; + } else if (isObject(options)) { + leading = !!options.leading; + maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function cancel() { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + lastCalled = 0; + maxTimeoutId = timeoutId = trailingCall = undefined; + } + + function complete(isCalled, id) { + if (id) { + clearTimeout(id); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + if (isCalled) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = undefined; + } + } + } + + function delayed() { + var remaining = wait - (now() - stamp); + if (remaining <= 0 || remaining > wait) { + complete(trailingCall, maxTimeoutId); + } else { + timeoutId = setTimeout(delayed, remaining); + } + } + + function maxDelayed() { + complete(trailing, timeoutId); + } + + function debounced() { + args = arguments; + stamp = now(); + thisArg = this; + trailingCall = trailing && (timeoutId || !leading); + + if (maxWait === false) { + var leadingCall = leading && !timeoutId; + } else { + if (!maxTimeoutId && !leading) { + lastCalled = stamp; + } + var remaining = maxWait - (stamp - lastCalled), + isCalled = remaining <= 0 || remaining > maxWait; + + if (isCalled) { + if (maxTimeoutId) { + maxTimeoutId = clearTimeout(maxTimeoutId); + } + lastCalled = stamp; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (isCalled && timeoutId) { + timeoutId = clearTimeout(timeoutId); + } + else if (!timeoutId && wait !== maxWait) { + timeoutId = setTimeout(delayed, wait); + } + if (leadingCall) { + isCalled = true; + result = func.apply(thisArg, args); + } + if (isCalled && !timeoutId && !maxTimeoutId) { + args = thisArg = undefined; + } + return result; + } + debounced.cancel = cancel; + return debounced; +} + +module.exports = debounce; diff --git a/node_modules/express-validator/node_modules/lodash/function/defer.js b/node_modules/express-validator/node_modules/lodash/function/defer.js new file mode 100644 index 0000000..3accbf9 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/defer.js @@ -0,0 +1,25 @@ +var baseDelay = require('../internal/baseDelay'), + restParam = require('./restParam'); + +/** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // logs 'deferred' after one or more milliseconds + */ +var defer = restParam(function(func, args) { + return baseDelay(func, 1, args); +}); + +module.exports = defer; diff --git a/node_modules/express-validator/node_modules/lodash/function/delay.js b/node_modules/express-validator/node_modules/lodash/function/delay.js new file mode 100644 index 0000000..d5eef27 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/delay.js @@ -0,0 +1,26 @@ +var baseDelay = require('../internal/baseDelay'), + restParam = require('./restParam'); + +/** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => logs 'later' after one second + */ +var delay = restParam(function(func, wait, args) { + return baseDelay(func, wait, args); +}); + +module.exports = delay; diff --git a/node_modules/express-validator/node_modules/lodash/function/flow.js b/node_modules/express-validator/node_modules/lodash/function/flow.js new file mode 100644 index 0000000..a435a3d --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/flow.js @@ -0,0 +1,25 @@ +var createFlow = require('../internal/createFlow'); + +/** + * Creates a function that returns the result of invoking the provided + * functions with the `this` binding of the created function, where each + * successive invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow(_.add, square); + * addSquare(1, 2); + * // => 9 + */ +var flow = createFlow(); + +module.exports = flow; diff --git a/node_modules/express-validator/node_modules/lodash/function/flowRight.js b/node_modules/express-validator/node_modules/lodash/function/flowRight.js new file mode 100644 index 0000000..23b9d76 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/flowRight.js @@ -0,0 +1,25 @@ +var createFlow = require('../internal/createFlow'); + +/** + * This method is like `_.flow` except that it creates a function that + * invokes the provided functions from right to left. + * + * @static + * @memberOf _ + * @alias backflow, compose + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight(square, _.add); + * addSquare(1, 2); + * // => 9 + */ +var flowRight = createFlow(true); + +module.exports = flowRight; diff --git a/node_modules/express-validator/node_modules/lodash/function/memoize.js b/node_modules/express-validator/node_modules/lodash/function/memoize.js new file mode 100644 index 0000000..f3b8d69 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/memoize.js @@ -0,0 +1,80 @@ +var MapCache = require('../internal/MapCache'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is coerced to a string and used as the + * cache key. The `func` is invoked with the `this` binding of the memoized + * function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object) + * method interface of `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var upperCase = _.memoize(function(string) { + * return string.toUpperCase(); + * }); + * + * upperCase('fred'); + * // => 'FRED' + * + * // modifying the result cache + * upperCase.cache.set('fred', 'BARNEY'); + * upperCase('fred'); + * // => 'BARNEY' + * + * // replacing `_.memoize.Cache` + * var object = { 'user': 'fred' }; + * var other = { 'user': 'barney' }; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'fred' } + * + * _.memoize.Cache = WeakMap; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'barney' } + */ +function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result); + return result; + }; + memoized.cache = new memoize.Cache; + return memoized; +} + +// Assign cache to `_.memoize`. +memoize.Cache = MapCache; + +module.exports = memoize; diff --git a/node_modules/express-validator/node_modules/lodash/function/modArgs.js b/node_modules/express-validator/node_modules/lodash/function/modArgs.js new file mode 100644 index 0000000..49b9b5e --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/modArgs.js @@ -0,0 +1,58 @@ +var arrayEvery = require('../internal/arrayEvery'), + baseFlatten = require('../internal/baseFlatten'), + baseIsFunction = require('../internal/baseIsFunction'), + restParam = require('./restParam'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMin = Math.min; + +/** + * Creates a function that runs each argument through a corresponding + * transform function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms] The functions to transform + * arguments, specified as individual functions or arrays of functions. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var modded = _.modArgs(function(x, y) { + * return [x, y]; + * }, square, doubled); + * + * modded(1, 2); + * // => [1, 4] + * + * modded(5, 10); + * // => [25, 20] + */ +var modArgs = restParam(function(func, transforms) { + transforms = baseFlatten(transforms); + if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = transforms.length; + return restParam(function(args) { + var index = nativeMin(args.length, length); + while (index--) { + args[index] = transforms[index](args[index]); + } + return func.apply(this, args); + }); +}); + +module.exports = modArgs; diff --git a/node_modules/express-validator/node_modules/lodash/function/negate.js b/node_modules/express-validator/node_modules/lodash/function/negate.js new file mode 100644 index 0000000..8247939 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/negate.js @@ -0,0 +1,32 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ +function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + return !predicate.apply(this, arguments); + }; +} + +module.exports = negate; diff --git a/node_modules/express-validator/node_modules/lodash/function/once.js b/node_modules/express-validator/node_modules/lodash/function/once.js new file mode 100644 index 0000000..0b5bd85 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/once.js @@ -0,0 +1,24 @@ +var before = require('./before'); + +/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first call. The `func` is invoked + * with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` invokes `createApplication` once + */ +function once(func) { + return before(2, func); +} + +module.exports = once; diff --git a/node_modules/express-validator/node_modules/lodash/function/partial.js b/node_modules/express-validator/node_modules/lodash/function/partial.js new file mode 100644 index 0000000..fb1d04f --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/partial.js @@ -0,0 +1,43 @@ +var createPartial = require('../internal/createPartial'); + +/** Used to compose bitmasks for wrapper metadata. */ +var PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes `func` with `partial` arguments prepended + * to those provided to the new function. This method is like `_.bind` except + * it does **not** alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // using placeholders + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ +var partial = createPartial(PARTIAL_FLAG); + +// Assign default placeholders. +partial.placeholder = {}; + +module.exports = partial; diff --git a/node_modules/express-validator/node_modules/lodash/function/partialRight.js b/node_modules/express-validator/node_modules/lodash/function/partialRight.js new file mode 100644 index 0000000..634e6a4 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/partialRight.js @@ -0,0 +1,42 @@ +var createPartial = require('../internal/createPartial'); + +/** Used to compose bitmasks for wrapper metadata. */ +var PARTIAL_RIGHT_FLAG = 64; + +/** + * This method is like `_.partial` except that partially applied arguments + * are appended to those provided to the new function. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // using placeholders + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ +var partialRight = createPartial(PARTIAL_RIGHT_FLAG); + +// Assign default placeholders. +partialRight.placeholder = {}; + +module.exports = partialRight; diff --git a/node_modules/express-validator/node_modules/lodash/function/rearg.js b/node_modules/express-validator/node_modules/lodash/function/rearg.js new file mode 100644 index 0000000..f2bd9c4 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/rearg.js @@ -0,0 +1,40 @@ +var baseFlatten = require('../internal/baseFlatten'), + createWrapper = require('../internal/createWrapper'), + restParam = require('./restParam'); + +/** Used to compose bitmasks for wrapper metadata. */ +var REARG_FLAG = 256; + +/** + * Creates a function that invokes `func` with arguments arranged according + * to the specified indexes where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes, + * specified as individual indexes or arrays of indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, 2, 0, 1); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + * + * var map = _.rearg(_.map, [1, 0]); + * map(function(n) { + * return n * 3; + * }, [1, 2, 3]); + * // => [3, 6, 9] + */ +var rearg = restParam(function(func, indexes) { + return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes)); +}); + +module.exports = rearg; diff --git a/node_modules/express-validator/node_modules/lodash/function/restParam.js b/node_modules/express-validator/node_modules/lodash/function/restParam.js new file mode 100644 index 0000000..8852286 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/restParam.js @@ -0,0 +1,58 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Native method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as an array. + * + * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.restParam(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ +function restParam(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + rest = Array(length); + + while (++index < length) { + rest[index] = args[start + index]; + } + switch (start) { + case 0: return func.call(this, rest); + case 1: return func.call(this, args[0], rest); + case 2: return func.call(this, args[0], args[1], rest); + } + var otherArgs = Array(start + 1); + index = -1; + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = rest; + return func.apply(this, otherArgs); + }; +} + +module.exports = restParam; diff --git a/node_modules/express-validator/node_modules/lodash/function/spread.js b/node_modules/express-validator/node_modules/lodash/function/spread.js new file mode 100644 index 0000000..780f504 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/spread.js @@ -0,0 +1,44 @@ +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that invokes `func` with the `this` binding of the created + * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3). + * + * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/Web/JavaScript/Reference/Operators/Spread_operator). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to spread arguments over. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * // with a Promise + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ +function spread(func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function(array) { + return func.apply(this, array); + }; +} + +module.exports = spread; diff --git a/node_modules/express-validator/node_modules/lodash/function/throttle.js b/node_modules/express-validator/node_modules/lodash/function/throttle.js new file mode 100644 index 0000000..1dd00ea --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/throttle.js @@ -0,0 +1,62 @@ +var debounce = require('./debounce'), + isObject = require('../lang/isObject'); + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed invocations. Provide an options object to indicate + * that `func` should be invoked on the leading and/or trailing edge of the + * `wait` timeout. Subsequent calls to the throttled function return the + * result of the last `func` call. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the throttled function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=true] Specify invoking on the leading + * edge of the timeout. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // avoid excessively updating the position while scrolling + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes + * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { + * 'trailing': false + * })); + * + * // cancel a trailing throttled call + * jQuery(window).on('popstate', throttled.cancel); + */ +function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (options === false) { + leading = false; + } else if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing }); +} + +module.exports = throttle; diff --git a/node_modules/express-validator/node_modules/lodash/function/wrap.js b/node_modules/express-validator/node_modules/lodash/function/wrap.js new file mode 100644 index 0000000..6a33c5e --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/function/wrap.js @@ -0,0 +1,33 @@ +var createWrapper = require('../internal/createWrapper'), + identity = require('../utility/identity'); + +/** Used to compose bitmasks for wrapper metadata. */ +var PARTIAL_FLAG = 32; + +/** + * Creates a function that provides `value` to the wrapper function as its + * first argument. Any additional arguments provided to the function are + * appended to those provided to the wrapper function. The wrapper is invoked + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {*} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ +function wrap(value, wrapper) { + wrapper = wrapper == null ? identity : wrapper; + return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []); +} + +module.exports = wrap; diff --git a/node_modules/express-validator/node_modules/lodash/index.js b/node_modules/express-validator/node_modules/lodash/index.js new file mode 100644 index 0000000..5f17319 --- /dev/null +++ b/node_modules/express-validator/node_modules/lodash/index.js @@ -0,0 +1,12351 @@ +/** + * @license + * lodash 3.10.1 (Custom Build) + * Build: `lodash modern -d -o ./index.js` + * Copyright 2012-2015 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '3.10.1'; + + /** Used to compose bitmasks for wrapper metadata. */ + var BIND_FLAG = 1, + BIND_KEY_FLAG = 2, + CURRY_BOUND_FLAG = 4, + CURRY_FLAG = 8, + CURRY_RIGHT_FLAG = 16, + PARTIAL_FLAG = 32, + PARTIAL_RIGHT_FLAG = 64, + ARY_FLAG = 128, + REARG_FLAG = 256; + + /** Used as default options for `_.trunc`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect when a function becomes hot. */ + var HOT_COUNT = 150, + HOT_SPAN = 16; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2; + + /** Used as the `TypeError` message for "Functions" methods. */ + var FUNC_ERROR_TEXT = 'Expected a function'; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + + var arrayBufferTag = '[object ArrayBuffer]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g, + reUnescapedHtml = /[&<>"'`]/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; + + /** + * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns) + * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern). + */ + var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g, + reHasRegExpChars = RegExp(reRegExpChars.source); + + /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */ + var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect hexadecimal string values. */ + var reHasHexPrefix = /^0[xX]/; + + /** Used to detect host constructors (Safari > 5). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^\d+$/; + + /** Used to match latin-1 supplementary letters (excluding mathematical operators). */ + var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to match words to create compound words. */ + var reWords = (function() { + var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]', + lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+'; + + return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g'); + }()); + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number', + 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'isFinite', + 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dateTag] = typedArrayTags[errorTag] = + typedArrayTags[funcTag] = typedArrayTags[mapTag] = + typedArrayTags[numberTag] = typedArrayTags[objectTag] = + typedArrayTags[regexpTag] = typedArrayTags[setTag] = + typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = + cloneableTags[dateTag] = cloneableTags[float32Tag] = + cloneableTags[float64Tag] = cloneableTags[int8Tag] = + cloneableTags[int16Tag] = cloneableTags[int32Tag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[stringTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[mapTag] = cloneableTags[setTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map latin-1 supplementary letters to basic latin letters. */ + var deburredLetters = { + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '`': '`' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'", + '`': '`' + }; + + /** Used to determine if values are of the language type `Object`. */ + var objectTypes = { + 'function': true, + 'object': true + }; + + /** Used to escape characters for inclusion in compiled regexes. */ + var regexpEscapes = { + '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34', + '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39', + 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46', + 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66', + 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78' + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Detect free variable `exports`. */ + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; + + /** Detect free variable `self`. */ + var freeSelf = objectTypes[typeof self] && self && self.Object && self; + + /** Detect free variable `window`. */ + var freeWindow = objectTypes[typeof window] && window && window.Object && window; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; + + /** + * Used as a reference to the global object. + * + * The `this` value is used if it's the global object to avoid Greasemonkey's + * restricted `window` object, otherwise the `window` object is used. + */ + var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this; + + /*--------------------------------------------------------------------------*/ + + /** + * The base implementation of `compareAscending` which compares values and + * sorts them in ascending order without guaranteeing a stable sort. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function baseCompareAscending(value, other) { + if (value !== other) { + var valIsNull = value === null, + valIsUndef = value === undefined, + valIsReflexive = value === value; + + var othIsNull = other === null, + othIsUndef = other === undefined, + othIsReflexive = other === other; + + if ((value > other && !othIsNull) || !valIsReflexive || + (valIsNull && !othIsUndef && othIsReflexive) || + (valIsUndef && othIsReflexive)) { + return 1; + } + if ((value < other && !valIsNull) || !othIsReflexive || + (othIsNull && !valIsUndef && valIsReflexive) || + (othIsUndef && valIsReflexive)) { + return -1; + } + } + return 0; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to search. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without support for binary searches. + * + * @private + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return indexOfNaN(array, fromIndex); + } + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isFunction` without support for environments + * with incorrect `typeof` results. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + */ + function baseIsFunction(value) { + // Avoid a Chakra JIT bug in compatibility modes of IE 11. + // See https://github.com/jashkenas/underscore/issues/1621 for more details. + return typeof value == 'function' || false; + } + + /** + * Converts `value` to a string if it's not one. An empty string is returned + * for `null` or `undefined` values. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + return value == null ? '' : (value + ''); + } + + /** + * Used by `_.trim` and `_.trimLeft` to get the index of the first character + * of `string` that is not found in `chars`. + * + * @private + * @param {string} string The string to inspect. + * @param {string} chars The characters to find. + * @returns {number} Returns the index of the first character not found in `chars`. + */ + function charsLeftIndex(string, chars) { + var index = -1, + length = string.length; + + while (++index < length && chars.indexOf(string.charAt(index)) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimRight` to get the index of the last character + * of `string` that is not found in `chars`. + * + * @private + * @param {string} string The string to inspect. + * @param {string} chars The characters to find. + * @returns {number} Returns the index of the last character not found in `chars`. + */ + function charsRightIndex(string, chars) { + var index = string.length; + + while (index-- && chars.indexOf(string.charAt(index)) > -1) {} + return index; + } + + /** + * Used by `_.sortBy` to compare transformed elements of a collection and stable + * sort them in ascending order. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareAscending(object, other) { + return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index); + } + + /** + * Used by `_.sortByOrder` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise, + * a value is sorted in ascending order if its corresponding order is "asc", and + * descending if "desc". + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = baseCompareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * ((order === 'asc' || order === true) ? 1 : -1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://code.google.com/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + function deburrLetter(letter) { + return deburredLetters[letter]; + } + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeHtmlChar(chr) { + return htmlEscapes[chr]; + } + + /** + * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes. + * + * @private + * @param {string} chr The matched character to escape. + * @param {string} leadingChar The capture group for a leading character. + * @param {string} whitespaceChar The capture group for a whitespace character. + * @returns {string} Returns the escaped character. + */ + function escapeRegExpChar(chr, leadingChar, whitespaceChar) { + if (leadingChar) { + chr = regexpEscapes[chr]; + } else if (whitespaceChar) { + chr = stringEscapes[chr]; + } + return '\\' + chr; + } + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the index at which the first occurrence of `NaN` is found in `array`. + * + * @private + * @param {Array} array The array to search. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched `NaN`, else `-1`. + */ + function indexOfNaN(array, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 0 : -1); + + while ((fromRight ? index-- : ++index < length)) { + var other = array[index]; + if (other !== other) { + return index; + } + } + return -1; + } + + /** + * Checks if `value` is object-like. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + */ + function isObjectLike(value) { + return !!value && typeof value == 'object'; + } + + /** + * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a + * character code is whitespace. + * + * @private + * @param {number} charCode The character code to inspect. + * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`. + */ + function isSpace(charCode) { + return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 || + (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279))); + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + if (array[index] === placeholder) { + array[index] = PLACEHOLDER; + result[++resIndex] = index; + } + } + return result; + } + + /** + * An implementation of `_.uniq` optimized for sorted arrays without support + * for callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The function invoked per iteration. + * @returns {Array} Returns the new duplicate-value-free array. + */ + function sortedUniq(array, iteratee) { + var seen, + index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value, index, array) : value; + + if (!index || seen !== computed) { + seen = computed; + result[++resIndex] = value; + } + } + return result; + } + + /** + * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the first non-whitespace character. + */ + function trimmedLeftIndex(string) { + var index = -1, + length = string.length; + + while (++index < length && isSpace(string.charCodeAt(index))) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ + function trimmedRightIndex(string) { + var index = string.length; + + while (index-- && isSpace(string.charCodeAt(index))) {} + return index; + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + function unescapeHtmlChar(chr) { + return htmlUnescapes[chr]; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the given `context` object. + * + * @static + * @memberOf _ + * @category Utility + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // using `context` to mock `Date#getTime` use in `_.now` + * var mock = _.runInContext({ + * 'Date': function() { + * return { 'getTime': getTimeMock }; + * } + * }); + * + * // or creating a suped-up `defer` in Node.js + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + function runInContext(context) { + // Avoid issues with some ES3 environments that attempt to use values, named + // after built-in constructors like `Object`, for the creation of literals. + // ES5 clears this up by stating that literals must use built-in constructors. + // See https://es5.github.io/#x11.1.5 for more details. + context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; + + /** Native constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Number = context.Number, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for native method references. */ + var arrayProto = Array.prototype, + objectProto = Object.prototype, + stringProto = String.prototype; + + /** Used to resolve the decompiled source of functions. */ + var fnToString = Function.prototype.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ + var objToString = objectProto.toString; + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Native method references. */ + var ArrayBuffer = context.ArrayBuffer, + clearTimeout = context.clearTimeout, + parseFloat = context.parseFloat, + pow = Math.pow, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + Set = getNative(context, 'Set'), + setTimeout = context.setTimeout, + splice = arrayProto.splice, + Uint8Array = context.Uint8Array, + WeakMap = getNative(context, 'WeakMap'); + + /* Native method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeCreate = getNative(Object, 'create'), + nativeFloor = Math.floor, + nativeIsArray = getNative(Array, 'isArray'), + nativeIsFinite = context.isFinite, + nativeKeys = getNative(Object, 'keys'), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = getNative(Date, 'now'), + nativeParseInt = context.parseInt, + nativeRandom = Math.random; + + /** Used as references for `-Infinity` and `Infinity`. */ + var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY, + POSITIVE_INFINITY = Number.POSITIVE_INFINITY; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** + * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) + * of an array-like value. + */ + var MAX_SAFE_INTEGER = 9007199254740991; + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit chaining. + * Methods that operate on and return arrays, collections, and functions can + * be chained together. Methods that retrieve a single value or may return a + * primitive value will automatically end the chain returning the unwrapped + * value. Explicit chaining may be enabled using `_.chain`. The execution of + * chained methods is lazy, that is, execution is deferred until `_#value` + * is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. Shortcut + * fusion is an optimization strategy which merge iteratee calls; this can help + * to avoid the creation of intermediate data structures and greatly reduce the + * number of iteratee executions. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, + * `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, + * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, + * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, + * and `where` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, + * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, + * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`, + * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`, + * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, + * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, + * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, + * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, + * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`, + * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, + * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, + * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`, + * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, + * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`, + * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`, + * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`, + * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`, + * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, + * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, + * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`, + * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, + * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`, + * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`, + * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`, + * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`, + * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`, + * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`, + * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`, + * `unescape`, `uniqueId`, `value`, and `words` + * + * The wrapper method `sample` will return a wrapped value when `n` is provided, + * otherwise an unwrapped value is returned. + * + * @name _ + * @constructor + * @category Chain + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var wrapped = _([1, 2, 3]); + * + * // returns an unwrapped value + * wrapped.reduce(function(total, n) { + * return total + n; + * }); + * // => 6 + * + * // returns a wrapped value + * var squares = wrapped.map(function(n) { + * return n * n; + * }); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The function whose prototype all chaining wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable chaining for all wrapper methods. + * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value. + */ + function LodashWrapper(value, chainAll, actions) { + this.__wrapped__ = value; + this.__actions__ = actions || []; + this.__chain__ = !!chainAll; + } + + /** + * An object environment feature flags. + * + * @static + * @memberOf _ + * @type Object + */ + var support = lodash.support = {}; + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB). Change the following template settings to use + * alternative delimiters. + * + * @static + * @memberOf _ + * @type Object + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type string + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type Object + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type Function + */ + '_': lodash + } + }; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = POSITIVE_INFINITY; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = arrayCopy(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = arrayCopy(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = arrayCopy(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) { + return baseWrapperValue((isRight && isArr) ? array.reverse() : array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a cache object to store key/value pairs. + * + * @private + * @static + * @name Cache + * @memberOf _.memoize + */ + function MapCache() { + this.__data__ = {}; + } + + /** + * Removes `key` and its value from the cache. + * + * @private + * @name delete + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`. + */ + function mapDelete(key) { + return this.has(key) && delete this.__data__[key]; + } + + /** + * Gets the cached value for `key`. + * + * @private + * @name get + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to get. + * @returns {*} Returns the cached value. + */ + function mapGet(key) { + return key == '__proto__' ? undefined : this.__data__[key]; + } + + /** + * Checks if a cached value for `key` exists. + * + * @private + * @name has + * @memberOf _.memoize.Cache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapHas(key) { + return key != '__proto__' && hasOwnProperty.call(this.__data__, key); + } + + /** + * Sets `value` to `key` of the cache. + * + * @private + * @name set + * @memberOf _.memoize.Cache + * @param {string} key The key of the value to cache. + * @param {*} value The value to cache. + * @returns {Object} Returns the cache object. + */ + function mapSet(key, value) { + if (key != '__proto__') { + this.__data__[key] = value; + } + return this; + } + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates a cache object to store unique values. + * + * @private + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var length = values ? values.length : 0; + + this.data = { 'hash': nativeCreate(null), 'set': new Set }; + while (length--) { + this.push(values[length]); + } + } + + /** + * Checks if `value` is in `cache` mimicking the return signature of + * `_.indexOf` by returning `0` if the value is found, else `-1`. + * + * @private + * @param {Object} cache The cache to search. + * @param {*} value The value to search for. + * @returns {number} Returns `0` if `value` is found, else `-1`. + */ + function cacheIndexOf(cache, value) { + var data = cache.data, + result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value]; + + return result ? 0 : -1; + } + + /** + * Adds `value` to the cache. + * + * @private + * @name push + * @memberOf SetCache + * @param {*} value The value to cache. + */ + function cachePush(value) { + var data = this.data; + if (typeof value == 'string' || isObject(value)) { + data.set.add(value); + } else { + data.hash[value] = true; + } + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a new array joining `array` with `other`. + * + * @private + * @param {Array} array The array to join. + * @param {Array} other The other array to join. + * @returns {Array} Returns the new concatenated array. + */ + function arrayConcat(array, other) { + var index = -1, + length = array.length, + othIndex = -1, + othLength = other.length, + result = Array(length + othLength); + + while (++index < length) { + result[index] = array[index]; + } + while (++othIndex < othLength) { + result[index++] = other[othIndex]; + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function arrayCopy(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * A specialized version of `_.forEach` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `baseExtremum` for arrays which invokes `iteratee` + * with one argument: (value). + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} comparator The function used to compare values. + * @param {*} exValue The initial extremum value. + * @returns {*} Returns the extremum value. + */ + function arrayExtremum(array, iteratee, comparator, exValue) { + var index = -1, + length = array.length, + computed = exValue, + result = computed; + + while (++index < length) { + var value = array[index], + current = +iteratee(value); + + if (comparator(current, computed)) { + computed = current; + result = value; + } + } + return result; + } + + /** + * A specialized version of `_.filter` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array.length, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[++resIndex] = value; + } + } + return result; + } + + /** + * A specialized version of `_.map` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initFromArray] Specify using the first element of `array` + * as the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initFromArray) { + var index = -1, + length = array.length; + + if (initFromArray && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initFromArray] Specify using the last element of `array` + * as the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initFromArray) { + var length = array.length; + if (initFromArray && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.sum` for arrays without support for callback + * shorthands and `this` binding.. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function arraySum(array, iteratee) { + var length = array.length, + result = 0; + + while (length--) { + result += +iteratee(array[length]) || 0; + } + return result; + } + + /** + * Used by `_.defaults` to customize its `_.assign` use. + * + * @private + * @param {*} objectValue The destination object property value. + * @param {*} sourceValue The source object property value. + * @returns {*} Returns the value to assign to the destination object. + */ + function assignDefaults(objectValue, sourceValue) { + return objectValue === undefined ? sourceValue : objectValue; + } + + /** + * Used by `_.template` to customize its `_.assign` use. + * + * **Note:** This function is like `assignDefaults` except that it ignores + * inherited property values when checking if a property is `undefined`. + * + * @private + * @param {*} objectValue The destination object property value. + * @param {*} sourceValue The source object property value. + * @param {string} key The key associated with the object and source values. + * @param {Object} object The destination object. + * @returns {*} Returns the value to assign to the destination object. + */ + function assignOwnDefaults(objectValue, sourceValue, key, object) { + return (objectValue === undefined || !hasOwnProperty.call(object, key)) + ? sourceValue + : objectValue; + } + + /** + * A specialized version of `_.assign` for customizing assigned values without + * support for argument juggling, multiple sources, and `this` binding `customizer` + * functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + */ + function assignWith(object, source, customizer) { + var index = -1, + props = keys(source), + length = props.length; + + while (++index < length) { + var key = props[index], + value = object[key], + result = customizer(value, source[key], key, object, source); + + if ((result === result ? (result !== value) : (value === value)) || + (value === undefined && !(key in object))) { + object[key] = result; + } + } + return object; + } + + /** + * The base implementation of `_.assign` without support for argument juggling, + * multiple sources, and `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return source == null + ? object + : baseCopy(source, keys(source), object); + } + + /** + * The base implementation of `_.at` without support for string collections + * and individual key arguments. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {number[]|string[]} props The property names or indexes of elements to pick. + * @returns {Array} Returns the new array of picked elements. + */ + function baseAt(collection, props) { + var index = -1, + isNil = collection == null, + isArr = !isNil && isArrayLike(collection), + length = isArr ? collection.length : 0, + propsLength = props.length, + result = Array(propsLength); + + while(++index < propsLength) { + var key = props[index]; + if (isArr) { + result[index] = isIndex(key, length) ? collection[key] : undefined; + } else { + result[index] = isNil ? undefined : collection[key]; + } + } + return result; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property names to copy. + * @param {Object} [object={}] The object to copy properties to. + * @returns {Object} Returns `object`. + */ + function baseCopy(source, props, object) { + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + object[key] = source[key]; + } + return object; + } + + /** + * The base implementation of `_.callback` which supports specifying the + * number of arguments to provide to `func`. + * + * @private + * @param {*} [func=_.identity] The value to convert to a callback. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {number} [argCount] The number of arguments to provide to `func`. + * @returns {Function} Returns the callback. + */ + function baseCallback(func, thisArg, argCount) { + var type = typeof func; + if (type == 'function') { + return thisArg === undefined + ? func + : bindCallback(func, thisArg, argCount); + } + if (func == null) { + return identity; + } + if (type == 'object') { + return baseMatches(func); + } + return thisArg === undefined + ? property(func) + : baseMatchesProperty(func, thisArg); + } + + /** + * The base implementation of `_.clone` without support for argument juggling + * and `this` binding `customizer` functions. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {Function} [customizer] The function to customize cloning values. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The object `value` belongs to. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates clones with source counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { + var result; + if (customizer) { + result = object ? customizer(value, key, object) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return arrayCopy(value, result); + } + } else { + var tag = objToString.call(value), + isFunc = tag == funcTag; + + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = initCloneObject(isFunc ? {} : value); + if (!isDeep) { + return baseAssign(result, value); + } + } else { + return cloneableTags[tag] + ? initCloneByTag(value, tag, isDeep) + : (object ? value : {}); + } + } + // Check for circular references and return its corresponding clone. + stackA || (stackA = []); + stackB || (stackB = []); + + var length = stackA.length; + while (length--) { + if (stackA[length] == value) { + return stackB[length]; + } + } + // Add the source value to the stack of traversed objects and associate it with its clone. + stackA.push(value); + stackB.push(result); + + // Recursively populate clone (susceptible to call stack limits). + (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { + result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); + }); + return result; + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} prototype The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(prototype) { + if (isObject(prototype)) { + object.prototype = prototype; + var result = new object; + object.prototype = undefined; + } + return result || {}; + }; + }()); + + /** + * The base implementation of `_.delay` and `_.defer` which accepts an index + * of where to slice the arguments to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Object} args The arguments provide to `func`. + * @returns {number} Returns the timer id. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of `_.difference` which accepts a single array + * of values to exclude. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values) { + var length = array ? array.length : 0, + result = []; + + if (!length) { + return result; + } + var index = -1, + indexOf = getIndexOf(), + isCommon = indexOf == baseIndexOf, + cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null, + valuesLength = values.length; + + if (cache) { + indexOf = cacheIndexOf; + isCommon = false; + values = cache; + } + outer: + while (++index < length) { + var value = array[index]; + + if (isCommon && value === value) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === value) { + continue outer; + } + } + result.push(value); + } + else if (indexOf(values, value, 0) < 0) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object|string} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object|string} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * Gets the extremum value of `collection` invoking `iteratee` for each value + * in `collection` to generate the criterion by which the value is ranked. + * The `iteratee` is invoked with three arguments: (value, index|key, collection). + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} comparator The function used to compare values. + * @param {*} exValue The initial extremum value. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(collection, iteratee, comparator, exValue) { + var computed = exValue, + result = computed; + + baseEach(collection, function(value, index, collection) { + var current = +iteratee(value, index, collection); + if (comparator(current, computed) || (current === exValue && current === result)) { + computed = current; + result = value; + } + }); + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = start == null ? 0 : (+start || 0); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : (+end || 0); + if (end < 0) { + end += length; + } + length = start > end ? 0 : (end >>> 0); + start >>>= 0; + + while (start < length) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`, + * without support for callback shorthands and `this` binding, which iterates + * over `collection` using the provided `eachFunc`. + * + * @private + * @param {Array|Object|string} collection The collection to search. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @param {boolean} [retKey] Specify returning the key of the found element + * instead of the element itself. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFind(collection, predicate, eachFunc, retKey) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = retKey ? key : value; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with added support for restricting + * flattening and specifying the start index. + * + * @private + * @param {Array} array The array to flatten. + * @param {boolean} [isDeep] Specify a deep flatten. + * @param {boolean} [isStrict] Restrict flattening to arrays-like objects. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, isDeep, isStrict, result) { + result || (result = []); + + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index]; + if (isObjectLike(value) && isArrayLike(value) && + (isStrict || isArray(value) || isArguments(value))) { + if (isDeep) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, isDeep, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForIn` and `baseForOwn` which iterates + * over `object` properties returned by `keysFunc` invoking `iteratee` for + * each property. Iteratee functions may exit iteration early by explicitly + * returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forIn` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForIn(object, iteratee) { + return baseFor(object, iteratee, keysIn); + } + + /** + * The base implementation of `_.forOwn` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from those provided. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the new array of filtered property names. + */ + function baseFunctions(object, props) { + var index = -1, + length = props.length, + resIndex = -1, + result = []; + + while (++index < length) { + var key = props[index]; + if (isFunction(object[key])) { + result[++resIndex] = key; + } + } + return result; + } + + /** + * The base implementation of `get` without support for string paths + * and default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path of the property to get. + * @param {string} [pathKey] The key representation of path. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path, pathKey) { + if (object == null) { + return; + } + if (pathKey !== undefined && pathKey in toObject(object)) { + path = [pathKey]; + } + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[path[index++]]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `_.isEqual` without support for `this` binding + * `customizer` functions. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparing values. + * @param {boolean} [isLoose] Specify performing partial comparisons. + * @param {Array} [stackA] Tracks traversed `value` objects. + * @param {Array} [stackB] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparing objects. + * @param {boolean} [isLoose] Specify performing partial comparisons. + * @param {Array} [stackA=[]] Tracks traversed `value` objects. + * @param {Array} [stackB=[]] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = arrayTag, + othTag = arrayTag; + + if (!objIsArr) { + objTag = objToString.call(object); + if (objTag == argsTag) { + objTag = objectTag; + } else if (objTag != objectTag) { + objIsArr = isTypedArray(object); + } + } + if (!othIsArr) { + othTag = objToString.call(other); + if (othTag == argsTag) { + othTag = objectTag; + } else if (othTag != objectTag) { + othIsArr = isTypedArray(other); + } + } + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && !(objIsArr || objIsObj)) { + return equalByTag(object, other, objTag); + } + if (!isLoose) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); + } + } + if (!isSameTag) { + return false; + } + // Assume cyclic values are equal. + // For more information on detecting circular references see https://es5.github.io/#JO. + stackA || (stackA = []); + stackB || (stackB = []); + + var length = stackA.length; + while (length--) { + if (stackA[length] == object) { + return stackB[length] == other; + } + } + // Add `object` and `other` to the stack of traversed objects. + stackA.push(object); + stackB.push(other); + + var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); + + stackA.pop(); + stackB.pop(); + + return result; + } + + /** + * The base implementation of `_.isMatch` without support for callback + * shorthands and `this` binding. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} matchData The propery names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparing objects. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = toObject(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var result = customizer ? customizer(objValue, srcValue, key) : undefined; + if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.map` without support for callback shorthands + * and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which does not clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + var key = matchData[0][0], + value = matchData[0][1]; + + return function(object) { + if (object == null) { + return false; + } + return object[key] === value && (value !== undefined || (key in toObject(object))); + }; + } + return function(object) { + return baseIsMatch(object, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which does not clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to compare. + * @returns {Function} Returns the new function. + */ + function baseMatchesProperty(path, srcValue) { + var isArr = isArray(path), + isCommon = isKey(path) && isStrictComparable(srcValue), + pathKey = (path + ''); + + path = toPath(path); + return function(object) { + if (object == null) { + return false; + } + var key = pathKey; + object = toObject(object); + if ((isArr || !isCommon) && !(key in object)) { + object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + if (object == null) { + return false; + } + key = last(path); + object = toObject(object); + } + return object[key] === srcValue + ? (srcValue !== undefined || (key in object)) + : baseIsEqual(srcValue, object[key], undefined, true); + }; + } + + /** + * The base implementation of `_.merge` without support for argument juggling, + * multiple sources, and `this` binding `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {Function} [customizer] The function to customize merged values. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + * @returns {Object} Returns `object`. + */ + function baseMerge(object, source, customizer, stackA, stackB) { + if (!isObject(object)) { + return object; + } + var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), + props = isSrcArr ? undefined : keys(source); + + arrayEach(props || source, function(srcValue, key) { + if (props) { + key = srcValue; + srcValue = source[key]; + } + if (isObjectLike(srcValue)) { + stackA || (stackA = []); + stackB || (stackB = []); + baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); + } + else { + var value = object[key], + result = customizer ? customizer(value, srcValue, key, object, source) : undefined, + isCommon = result === undefined; + + if (isCommon) { + result = srcValue; + } + if ((result !== undefined || (isSrcArr && !(key in object))) && + (isCommon || (result === result ? (result !== value) : (value === value)))) { + object[key] = result; + } + } + }); + return object; + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize merged values. + * @param {Array} [stackA=[]] Tracks traversed source objects. + * @param {Array} [stackB=[]] Associates values with source counterparts. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { + var length = stackA.length, + srcValue = source[key]; + + while (length--) { + if (stackA[length] == srcValue) { + object[key] = stackB[length]; + return; + } + } + var value = object[key], + result = customizer ? customizer(value, srcValue, key, object, source) : undefined, + isCommon = result === undefined; + + if (isCommon) { + result = srcValue; + if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { + result = isArray(value) + ? value + : (isArrayLike(value) ? arrayCopy(value) : []); + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + result = isArguments(value) + ? toPlainObject(value) + : (isPlainObject(value) ? value : {}); + } + else { + isCommon = false; + } + } + // Add the source value to the stack of traversed objects and associate + // it with its merged value. + stackA.push(srcValue); + stackB.push(result); + + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); + } else if (result === result ? (result !== value) : (value === value)) { + object[key] = result; + } + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new function. + */ + function basePropertyDeep(path) { + var pathKey = (path + ''); + path = toPath(path); + return function(object) { + return baseGet(object, path, pathKey); + }; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * index arguments and capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0; + while (length--) { + var index = indexes[length]; + if (index != previous && isIndex(index)) { + var previous = index; + splice.call(array, index, 1); + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for argument juggling + * and returning floating-point numbers. + * + * @private + * @param {number} min The minimum possible value. + * @param {number} max The maximum possible value. + * @returns {number} Returns the random number. + */ + function baseRandom(min, max) { + return min + nativeFloor(nativeRandom() * (max - min + 1)); + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight` without support + * for callback shorthands and `this` binding, which iterates over `collection` + * using the provided `eachFunc`. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initFromCollection Specify using the first or last element + * of `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initFromCollection + ? (initFromCollection = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `setData` without support for hot loop detection. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + start = start == null ? 0 : (+start || 0); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : (+end || 0); + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for callback shorthands + * and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define + * the sort order of `array` and replaces criteria objects with their + * corresponding values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sortByOrder` without param guards. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {boolean[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseSortByOrder(collection, iteratees, orders) { + var callback = getCallback(), + index = -1; + + iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); }); + + var result = baseMap(collection, function(value) { + var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.sum` without support for callback shorthands + * and `this` binding. + * + * @private + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(collection, iteratee) { + var result = 0; + baseEach(collection, function(value, index, collection) { + result += +iteratee(value, index, collection) || 0; + }); + return result; + } + + /** + * The base implementation of `_.uniq` without support for callback shorthands + * and `this` binding. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The function invoked per iteration. + * @returns {Array} Returns the new duplicate-value-free array. + */ + function baseUniq(array, iteratee) { + var index = -1, + indexOf = getIndexOf(), + length = array.length, + isCommon = indexOf == baseIndexOf, + isLarge = isCommon && length >= LARGE_ARRAY_SIZE, + seen = isLarge ? createCache() : null, + result = []; + + if (seen) { + indexOf = cacheIndexOf; + isCommon = false; + } else { + isLarge = false; + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value, index, array) : value; + + if (isCommon && value === value) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (indexOf(seen, computed, 0) < 0) { + if (iteratee || isLarge) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + var index = -1, + length = props.length, + result = Array(length); + + while (++index < length) { + result[index] = object[props[index]]; + } + return result; + } + + /** + * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`, + * and `_.takeWhile` without support for callback shorthands and `this` binding. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to peform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + var index = -1, + length = actions.length; + + while (++index < length) { + var action = actions[index]; + result = action.func.apply(action.thisArg, arrayPush([result], action.args)); + } + return result; + } + + /** + * Performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function binaryIndex(array, value, retHighest) { + var low = 0, + high = array ? array.length : low; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return binaryIndexBy(array, value, identity, retHighest); + } + + /** + * This function is like `binaryIndex` except that it invokes `iteratee` for + * `value` and each element of `array` to compute their sort ranking. The + * iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The function invoked per iteration. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function binaryIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array ? array.length : 0, + valIsNaN = value !== value, + valIsNull = value === null, + valIsUndef = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + isDef = computed !== undefined, + isReflexive = computed === computed; + + if (valIsNaN) { + var setLow = isReflexive || retHighest; + } else if (valIsNull) { + setLow = isReflexive && isDef && (retHighest || computed != null); + } else if (valIsUndef) { + setLow = isReflexive && (retHighest || isDef); + } else if (computed == null) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * A specialized version of `baseCallback` which only supports `this` binding + * and specifying the number of arguments to provide to `func`. + * + * @private + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {number} [argCount] The number of arguments to provide to `func`. + * @returns {Function} Returns the callback. + */ + function bindCallback(func, thisArg, argCount) { + if (typeof func != 'function') { + return identity; + } + if (thisArg === undefined) { + return func; + } + switch (argCount) { + case 1: return function(value) { + return func.call(thisArg, value); + }; + case 3: return function(value, index, collection) { + return func.call(thisArg, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(thisArg, accumulator, value, index, collection); + }; + case 5: return function(value, other, key, object, source) { + return func.call(thisArg, value, other, key, object, source); + }; + } + return function() { + return func.apply(thisArg, arguments); + }; + } + + /** + * Creates a clone of the given array buffer. + * + * @private + * @param {ArrayBuffer} buffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function bufferClone(buffer) { + var result = new ArrayBuffer(buffer.byteLength), + view = new Uint8Array(result); + + view.set(new Uint8Array(buffer)); + return result; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array|Object} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders) { + var holdersLength = holders.length, + argsIndex = -1, + argsLength = nativeMax(args.length - holdersLength, 0), + leftIndex = -1, + leftLength = partials.length, + result = Array(leftLength + argsLength); + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + while (argsLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array|Object} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders) { + var holdersIndex = -1, + holdersLength = holders.length, + argsIndex = -1, + argsLength = nativeMax(args.length - holdersLength, 0), + rightIndex = -1, + rightLength = partials.length, + result = Array(argsLength + rightLength); + + while (++argsIndex < argsLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + return result; + } + + /** + * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function. + * + * @private + * @param {Function} setter The function to set keys and values of the accumulator object. + * @param {Function} [initializer] The function to initialize the accumulator object. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee, thisArg) { + var result = initializer ? initializer() : {}; + iteratee = getCallback(iteratee, thisArg, 3); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + setter(result, value, iteratee(value, index, collection), collection); + } + } else { + baseEach(collection, function(value, key, collection) { + setter(result, value, iteratee(value, key, collection), collection); + }); + } + return result; + }; + } + + /** + * Creates a `_.assign`, `_.defaults`, or `_.merge` function. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return restParam(function(object, sources) { + var index = -1, + length = object == null ? 0 : sources.length, + customizer = length > 2 ? sources[length - 2] : undefined, + guard = length > 2 ? sources[2] : undefined, + thisArg = length > 1 ? sources[length - 1] : undefined; + + if (typeof customizer == 'function') { + customizer = bindCallback(customizer, thisArg, 5); + length -= 2; + } else { + customizer = typeof thisArg == 'function' ? thisArg : undefined; + length -= (customizer ? 1 : 0); + } + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + var length = collection ? getLength(collection) : 0; + if (!isLength(length)) { + return eachFunc(collection, iteratee); + } + var index = fromRight ? length : -1, + iterable = toObject(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for `_.forIn` or `_.forInRight`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var iterable = toObject(object), + props = keysFunc(object), + length = props.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length)) { + var key = props[index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` and invokes it with the `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to bind. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new bound function. + */ + function createBindWrapper(func, thisArg) { + var Ctor = createCtorWrapper(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(thisArg, arguments); + } + return wrapper; + } + + /** + * Creates a `Set` cache object to optimize linear searches of large arrays. + * + * @private + * @param {Array} [values] The values to cache. + * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`. + */ + function createCache(values) { + return (nativeCreate && Set) ? new SetCache(values) : null; + } + + /** + * Creates a function that produces compound words out of the words in a + * given string. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + var index = -1, + array = words(deburr(string)), + length = array.length, + result = ''; + + while (++index < length) { + result = callback(result, array[index], index); + } + return result; + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtorWrapper(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. + // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a `_.curry` or `_.curryRight` function. + * + * @private + * @param {boolean} flag The curry bit flag. + * @returns {Function} Returns the new curry function. + */ + function createCurry(flag) { + function curryFunc(func, arity, guard) { + if (guard && isIterateeCall(func, arity, guard)) { + arity = undefined; + } + var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryFunc.placeholder; + return result; + } + return curryFunc; + } + + /** + * Creates a `_.defaults` or `_.defaultsDeep` function. + * + * @private + * @param {Function} assigner The function to assign values. + * @param {Function} customizer The function to customize assigned values. + * @returns {Function} Returns the new defaults function. + */ + function createDefaults(assigner, customizer) { + return restParam(function(args) { + var object = args[0]; + if (object == null) { + return object; + } + args.push(customizer); + return assigner.apply(undefined, args); + }); + } + + /** + * Creates a `_.max` or `_.min` function. + * + * @private + * @param {Function} comparator The function used to compare values. + * @param {*} exValue The initial extremum value. + * @returns {Function} Returns the new extremum function. + */ + function createExtremum(comparator, exValue) { + return function(collection, iteratee, thisArg) { + if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { + iteratee = undefined; + } + iteratee = getCallback(iteratee, thisArg, 3); + if (iteratee.length == 1) { + collection = isArray(collection) ? collection : toIterable(collection); + var result = arrayExtremum(collection, iteratee, comparator, exValue); + if (!(collection.length && result === exValue)) { + return result; + } + } + return baseExtremum(collection, iteratee, comparator, exValue); + }; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new find function. + */ + function createFind(eachFunc, fromRight) { + return function(collection, predicate, thisArg) { + predicate = getCallback(predicate, thisArg, 3); + if (isArray(collection)) { + var index = baseFindIndex(collection, predicate, fromRight); + return index > -1 ? collection[index] : undefined; + } + return baseFind(collection, predicate, eachFunc); + }; + } + + /** + * Creates a `_.findIndex` or `_.findLastIndex` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new find function. + */ + function createFindIndex(fromRight) { + return function(array, predicate, thisArg) { + if (!(array && array.length)) { + return -1; + } + predicate = getCallback(predicate, thisArg, 3); + return baseFindIndex(array, predicate, fromRight); + }; + } + + /** + * Creates a `_.findKey` or `_.findLastKey` function. + * + * @private + * @param {Function} objectFunc The function to iterate over an object. + * @returns {Function} Returns the new find function. + */ + function createFindKey(objectFunc) { + return function(object, predicate, thisArg) { + predicate = getCallback(predicate, thisArg, 3); + return baseFind(object, predicate, objectFunc, true); + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return function() { + var wrapper, + length = arguments.length, + index = fromRight ? length : -1, + leftIndex = 0, + funcs = Array(length); + + while ((fromRight ? index-- : ++index < length)) { + var func = funcs[leftIndex++] = arguments[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') { + wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? -1 : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }; + } + + /** + * Creates a function for `_.forEach` or `_.forEachRight`. + * + * @private + * @param {Function} arrayFunc The function to iterate over an array. + * @param {Function} eachFunc The function to iterate over a collection. + * @returns {Function} Returns the new each function. + */ + function createForEach(arrayFunc, eachFunc) { + return function(collection, iteratee, thisArg) { + return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) + ? arrayFunc(collection, iteratee) + : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); + }; + } + + /** + * Creates a function for `_.forIn` or `_.forInRight`. + * + * @private + * @param {Function} objectFunc The function to iterate over an object. + * @returns {Function} Returns the new each function. + */ + function createForIn(objectFunc) { + return function(object, iteratee, thisArg) { + if (typeof iteratee != 'function' || thisArg !== undefined) { + iteratee = bindCallback(iteratee, thisArg, 3); + } + return objectFunc(object, iteratee, keysIn); + }; + } + + /** + * Creates a function for `_.forOwn` or `_.forOwnRight`. + * + * @private + * @param {Function} objectFunc The function to iterate over an object. + * @returns {Function} Returns the new each function. + */ + function createForOwn(objectFunc) { + return function(object, iteratee, thisArg) { + if (typeof iteratee != 'function' || thisArg !== undefined) { + iteratee = bindCallback(iteratee, thisArg, 3); + } + return objectFunc(object, iteratee); + }; + } + + /** + * Creates a function for `_.mapKeys` or `_.mapValues`. + * + * @private + * @param {boolean} [isMapKeys] Specify mapping keys instead of values. + * @returns {Function} Returns the new map function. + */ + function createObjectMapper(isMapKeys) { + return function(object, iteratee, thisArg) { + var result = {}; + iteratee = getCallback(iteratee, thisArg, 3); + + baseForOwn(object, function(value, key, object) { + var mapped = iteratee(value, key, object); + key = isMapKeys ? mapped : key; + value = isMapKeys ? value : mapped; + result[key] = value; + }); + return result; + }; + } + + /** + * Creates a function for `_.padLeft` or `_.padRight`. + * + * @private + * @param {boolean} [fromRight] Specify padding from the right. + * @returns {Function} Returns the new pad function. + */ + function createPadDir(fromRight) { + return function(string, length, chars) { + string = baseToString(string); + return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string); + }; + } + + /** + * Creates a `_.partial` or `_.partialRight` function. + * + * @private + * @param {boolean} flag The partial bit flag. + * @returns {Function} Returns the new partial function. + */ + function createPartial(flag) { + var partialFunc = restParam(function(func, partials) { + var holders = replaceHolders(partials, partialFunc.placeholder); + return createWrapper(func, flag, undefined, partials, holders); + }); + return partialFunc; + } + + /** + * Creates a function for `_.reduce` or `_.reduceRight`. + * + * @private + * @param {Function} arrayFunc The function to iterate over an array. + * @param {Function} eachFunc The function to iterate over a collection. + * @returns {Function} Returns the new each function. + */ + function createReduce(arrayFunc, eachFunc) { + return function(collection, iteratee, accumulator, thisArg) { + var initFromArray = arguments.length < 3; + return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) + ? arrayFunc(collection, iteratee, accumulator, initFromArray) + : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc); + }; + } + + /** + * Creates a function that wraps `func` and invokes it with optional `this` + * binding of, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & ARY_FLAG, + isBind = bitmask & BIND_FLAG, + isBindKey = bitmask & BIND_KEY_FLAG, + isCurry = bitmask & CURRY_FLAG, + isCurryBound = bitmask & CURRY_BOUND_FLAG, + isCurryRight = bitmask & CURRY_RIGHT_FLAG, + Ctor = isBindKey ? undefined : createCtorWrapper(func); + + function wrapper() { + // Avoid `arguments` object use disqualifying optimizations by + // converting it to an array before providing it to other functions. + var length = arguments.length, + index = length, + args = Array(length); + + while (index--) { + args[index] = arguments[index]; + } + if (partials) { + args = composeArgs(args, partials, holders); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight); + } + if (isCurry || isCurryRight) { + var placeholder = wrapper.placeholder, + argsHolders = replaceHolders(args, placeholder); + + length -= argsHolders.length; + if (length < arity) { + var newArgPos = argPos ? arrayCopy(argPos) : undefined, + newArity = nativeMax(arity - length, 0), + newsHolders = isCurry ? argsHolders : undefined, + newHoldersRight = isCurry ? undefined : argsHolders, + newPartials = isCurry ? args : undefined, + newPartialsRight = isCurry ? undefined : args; + + bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG); + + if (!isCurryBound) { + bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); + } + var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity], + result = createHybridWrapper.apply(undefined, newData); + + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return result; + } + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + if (argPos) { + args = reorder(args, argPos); + } + if (isAry && ary < args.length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtorWrapper(func); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates the padding required for `string` based on the given `length`. + * The `chars` string is truncated if the number of characters exceeds `length`. + * + * @private + * @param {string} string The string to create padding for. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the pad for `string`. + */ + function createPadding(string, length, chars) { + var strLength = string.length; + length = +length; + + if (strLength >= length || !nativeIsFinite(length)) { + return ''; + } + var padLength = length - strLength; + chars = chars == null ? ' ' : (chars + ''); + return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength); + } + + /** + * Creates a function that wraps `func` and invokes it with the optional `this` + * binding of `thisArg` and the `partials` prepended to those provided to + * the wrapper. + * + * @private + * @param {Function} func The function to partially apply arguments to. + * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to the new function. + * @returns {Function} Returns the new bound function. + */ + function createPartialWrapper(func, bitmask, thisArg, partials) { + var isBind = bitmask & BIND_FLAG, + Ctor = createCtorWrapper(func); + + function wrapper() { + // Avoid `arguments` object use disqualifying optimizations by + // converting it to an array before providing it `func`. + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength); + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.ceil`, `_.floor`, or `_.round` function. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + precision = precision === undefined ? 0 : (+precision || 0); + if (precision) { + precision = pow(10, precision); + return func(number * precision) / precision; + } + return func(number); + }; + } + + /** + * Creates a `_.sortedIndex` or `_.sortedLastIndex` function. + * + * @private + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {Function} Returns the new index function. + */ + function createSortedIndex(retHighest) { + return function(array, value, iteratee, thisArg) { + var callback = getCallback(iteratee); + return (iteratee == null && callback === baseCallback) + ? binaryIndex(array, value, retHighest) + : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to reference. + * @param {number} bitmask The bitmask of flags. + * The bitmask may be composed of the following flags: + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + length -= (holders ? holders.length : 0); + if (bitmask & PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func), + newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity]; + + if (data) { + mergeData(newData, data); + bitmask = newData[1]; + arity = newData[9]; + } + newData[9] = arity == null + ? (isBindKey ? 0 : func.length) + : (nativeMax(arity - length, 0) || 0); + + if (bitmask == BIND_FLAG) { + var result = createBindWrapper(newData[0], newData[2]); + } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) { + result = createPartialWrapper.apply(undefined, newData); + } else { + result = createHybridWrapper.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setter(result, newData); + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparing arrays. + * @param {boolean} [isLoose] Specify performing partial comparisons. + * @param {Array} [stackA] Tracks traversed `value` objects. + * @param {Array} [stackB] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { + var index = -1, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isLoose && othLength > arrLength)) { + return false; + } + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index], + result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined; + + if (result !== undefined) { + if (result) { + continue; + } + return false; + } + // Recursively compare arrays (susceptible to call stack limits). + if (isLoose) { + if (!arraySome(other, function(othValue) { + return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); + })) { + return false; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) { + return false; + } + } + return true; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag) { + switch (tag) { + case boolTag: + case dateTag: + // Coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0` treating invalid dates coerced to `NaN` as not equal. + return +object == +other; + + case errorTag: + return object.name == other.name && object.message == other.message; + + case numberTag: + // Treat `NaN` vs. `NaN` as equal. + return (object != +object) + ? other != +other + : object == +other; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings primitives and string + // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details. + return object == (other + ''); + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Function} [customizer] The function to customize comparing values. + * @param {boolean} [isLoose] Specify performing partial comparisons. + * @param {Array} [stackA] Tracks traversed `value` objects. + * @param {Array} [stackB] Tracks traversed `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { + var objProps = keys(object), + objLength = objProps.length, + othProps = keys(other), + othLength = othProps.length; + + if (objLength != othLength && !isLoose) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + var skipCtor = isLoose; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key], + result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined; + + // Recursively compare objects (susceptible to call stack limits). + if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) { + return false; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (!skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + return false; + } + } + return true; + } + + /** + * Gets the appropriate "callback" function. If the `_.callback` method is + * customized this function returns the custom method, otherwise it returns + * the `baseCallback` function. If arguments are provided the chosen function + * is invoked with them and its result is returned. + * + * @private + * @returns {Function} Returns the chosen function or its result. + */ + function getCallback(func, thisArg, argCount) { + var result = lodash.callback || callback; + result = result === callback ? baseCallback : result; + return argCount ? result(func, thisArg, argCount) : result; + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = func.name, + array = realNames[result], + length = array ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the appropriate "indexOf" function. If the `_.indexOf` method is + * customized this function returns the custom method, otherwise it returns + * the `baseIndexOf` function. If arguments are provided the chosen function + * is invoked with them and its result is returned. + * + * @private + * @returns {Function|number} Returns the chosen function or its result. + */ + function getIndexOf(collection, target, fromIndex) { + var result = lodash.indexOf || indexOf; + result = result === indexOf ? baseIndexOf : result; + return collection ? result(collection, target, fromIndex) : result; + } + + /** + * Gets the "length" property value of `object`. + * + * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) + * that affects Safari on at least iOS 8.1-8.3 ARM64. + * + * @private + * @param {Object} object The object to query. + * @returns {*} Returns the "length" value. + */ + var getLength = baseProperty('length'); + + /** + * Gets the propery names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = pairs(object), + length = result.length; + + while (length--) { + result[length][2] = isStrictComparable(result[length][1]); + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = object == null ? undefined : object[key]; + return isNative(value) ? value : undefined; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add array properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + var Ctor = object.constructor; + if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { + Ctor = Object; + } + return new Ctor; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return bufferClone(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + var buffer = object.buffer; + return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + var result = new Ctor(object.source, reFlags.exec(object)); + result.lastIndex = object.lastIndex; + } + return result; + } + + /** + * Invokes the method at `path` on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function invokePath(object, path, args) { + if (object != null && !isKey(path, object)) { + path = toPath(path); + object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + path = last(path); + } + var func = object == null ? object : object[path]; + return func == null ? undefined : func.apply(object, args); + } + + /** + * Checks if `value` is array-like. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + */ + function isArrayLike(value) { + return value != null && isLength(getLength(value)); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; + length = length == null ? MAX_SAFE_INTEGER : length; + return value > -1 && value % 1 == 0 && value < length; + } + + /** + * Checks if the provided arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object)) { + var other = object[index]; + return value === value ? (value === other) : (other !== other); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + var type = typeof value; + if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { + return true; + } + if (isArray(value)) { + return false; + } + var result = !reIsDeepProp.test(value); + return result || (object != null && value in toObject(object)); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func); + if (!(funcName in LazyWrapper.prototype)) { + return false; + } + var other = lodash[funcName]; + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + */ + function isLength(value) { + return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers required to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg` + * augment function arguments, making the order in which they are executed important, + * preventing the merging of metadata. However, we make an exception for a safe + * common case where curried functions have `_.ary` and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < ARY_FLAG; + + var isCombo = + (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) || + (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) || + (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value); + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]); + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value); + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]); + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = arrayCopy(value); + } + // Use source `ary` if it's smaller. + if (srcBitmask & ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use. + * + * @private + * @param {*} objectValue The destination object property value. + * @param {*} sourceValue The source object property value. + * @returns {*} Returns the value to assign to the destination object. + */ + function mergeDefaults(objectValue, sourceValue) { + return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults); + } + + /** + * A specialized version of `_.pick` which picks `object` properties specified + * by `props`. + * + * @private + * @param {Object} object The source object. + * @param {string[]} props The property names to pick. + * @returns {Object} Returns the new object. + */ + function pickByArray(object, props) { + object = toObject(object); + + var index = -1, + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index]; + if (key in object) { + result[key] = object[key]; + } + } + return result; + } + + /** + * A specialized version of `_.pick` which picks `object` properties `predicate` + * returns truthy for. + * + * @private + * @param {Object} object The source object. + * @param {Function} predicate The function invoked per iteration. + * @returns {Object} Returns the new object. + */ + function pickByCallback(object, predicate) { + var result = {}; + baseForIn(object, function(value, key, object) { + if (predicate(value, key, object)) { + result[key] = value; + } + }); + return result; + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = arrayCopy(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity function + * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = (function() { + var count = 0, + lastCalled = 0; + + return function(key, value) { + var stamp = now(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return key; + } + } else { + count = 0; + } + return baseSetData(key, value); + }; + }()); + + /** + * A fallback implementation of `Object.keys` which creates an array of the + * own enumerable property names of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function shimKeys(object) { + var props = keysIn(object), + propsLength = props.length, + length = propsLength && object.length; + + var allowIndexes = !!length && isLength(length) && + (isArray(object) || isArguments(object)); + + var index = -1, + result = []; + + while (++index < propsLength) { + var key = props[index]; + if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to an array-like object if it's not one. + * + * @private + * @param {*} value The value to process. + * @returns {Array|Object} Returns the array-like object. + */ + function toIterable(value) { + if (value == null) { + return []; + } + if (!isArrayLike(value)) { + return values(value); + } + return isObject(value) ? value : Object(value); + } + + /** + * Converts `value` to an object if it's not one. + * + * @private + * @param {*} value The value to process. + * @returns {Object} Returns the object. + */ + function toObject(value) { + return isObject(value) ? value : Object(value); + } + + /** + * Converts `value` to property path array if it's not one. + * + * @private + * @param {*} value The value to process. + * @returns {Array} Returns the property path array. + */ + function toPath(value) { + if (isArray(value)) { + return value; + } + var result = []; + baseToString(value).replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + return wrapper instanceof LazyWrapper + ? wrapper.clone() + : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `collection` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new array containing chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if (guard ? isIterateeCall(array, size, guard) : size == null) { + size = 1; + } else { + size = nativeMax(nativeFloor(size) || 1, 1); + } + var index = 0, + length = array ? array.length : 0, + resIndex = -1, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[++resIndex] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + resIndex = -1, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[++resIndex] = value; + } + } + return result; + } + + /** + * Creates an array of unique `array` values not included in the other + * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The arrays of values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.difference([1, 2, 3], [4, 2]); + * // => [1, 3] + */ + var difference = restParam(function(array, values) { + return (isObjectLike(array) && isArrayLike(array)) + ? baseDifference(array, baseFlatten(values, false, true)) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that match the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRightWhile([1, 2, 3], function(n) { + * return n > 1; + * }); + * // => [1] + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); + * // => ['barney', 'fred'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.dropRightWhile(users, 'active', false), 'user'); + * // => ['barney'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.dropRightWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropWhile([1, 2, 3], function(n) { + * return n < 3; + * }); + * // => [3] + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.dropWhile(users, 'active', false), 'user'); + * // => ['pebbles'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.dropWhile(users, 'active'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, getCallback(predicate, thisArg, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8], '*', 1, 2); + * // => [4, '*', 8] + */ + function fill(array, value, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(chr) { + * return chr.user == 'barney'; + * }); + * // => 0 + * + * // using the `_.matches` callback shorthand + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // using the `_.matchesProperty` callback shorthand + * _.findIndex(users, 'active', false); + * // => 0 + * + * // using the `_.property` callback shorthand + * _.findIndex(users, 'active'); + * // => 2 + */ + var findIndex = createFindIndex(); + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(chr) { + * return chr.user == 'pebbles'; + * }); + * // => 2 + * + * // using the `_.matches` callback shorthand + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // using the `_.matchesProperty` callback shorthand + * _.findLastIndex(users, 'active', false); + * // => 2 + * + * // using the `_.property` callback shorthand + * _.findLastIndex(users, 'active'); + * // => 0 + */ + var findLastIndex = createFindIndex(true); + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @alias head + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([]); + * // => undefined + */ + function first(array) { + return array ? array[0] : undefined; + } + + /** + * Flattens a nested array. If `isDeep` is `true` the array is recursively + * flattened, otherwise it is only flattened a single level. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to flatten. + * @param {boolean} [isDeep] Specify a deep flatten. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, 3, [4]]]); + * // => [1, 2, 3, [4]] + * + * // using `isDeep` + * _.flatten([1, [2, 3, [4]]], true); + * // => [1, 2, 3, 4] + */ + function flatten(array, isDeep, guard) { + var length = array ? array.length : 0; + if (guard && isIterateeCall(array, isDeep, guard)) { + isDeep = false; + } + return length ? baseFlatten(array, isDeep) : []; + } + + /** + * Recursively flattens a nested array. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to recursively flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, 3, [4]]]); + * // => [1, 2, 3, 4] + */ + function flattenDeep(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, true) : []; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it is used as the offset + * from the end of `array`. If `array` is sorted providing `true` for `fromIndex` + * performs a faster binary search. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=0] The index to search from or `true` + * to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // using `fromIndex` + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + * + * // performing a binary search + * _.indexOf([1, 1, 2, 2], 2, true); + * // => 2 + */ + function indexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + if (typeof fromIndex == 'number') { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; + } else if (fromIndex) { + var index = binaryIndex(array, value); + if (index < length && + (value === value ? (value === array[index]) : (array[index] !== array[index]))) { + return index; + } + return -1; + } + return baseIndexOf(array, value, fromIndex || 0); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + return dropRight(array, 1); + } + + /** + * Creates an array of unique values that are included in all of the provided + * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of shared values. + * @example + * _.intersection([1, 2], [4, 2], [2, 1]); + * // => [2] + */ + var intersection = restParam(function(arrays) { + var othLength = arrays.length, + othIndex = othLength, + caches = Array(length), + indexOf = getIndexOf(), + isCommon = indexOf == baseIndexOf, + result = []; + + while (othIndex--) { + var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : []; + caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null; + } + var array = arrays[0], + index = -1, + length = array ? array.length : 0, + seen = caches[0]; + + outer: + while (++index < length) { + value = array[index]; + if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) { + var othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) { + continue outer; + } + } + if (seen) { + seen.push(value); + } + result.push(value); + } + } + return result; + }); + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array ? array.length : 0; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to search. + * @param {*} value The value to search for. + * @param {boolean|number} [fromIndex=array.length-1] The index to search from + * or `true` to perform a binary search on a sorted array. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // using `fromIndex` + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + * + * // performing a binary search + * _.lastIndexOf([1, 1, 2, 2], 2, true); + * // => 3 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array ? array.length : 0; + if (!length) { + return -1; + } + var index = length; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1; + } else if (fromIndex) { + index = binaryIndex(array, value, true) - 1; + var other = array[index]; + if (value === value ? (value === other) : (other !== other)) { + return index; + } + return -1; + } + if (value !== value) { + return indexOfNaN(array, index, true); + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Removes all provided values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3, 1, 2, 3]; + * + * _.pull(array, 2, 3); + * console.log(array); + * // => [1, 1] + */ + function pull() { + var args = arguments, + array = args[0]; + + if (!(array && array.length)) { + return array; + } + var index = 0, + indexOf = getIndexOf(), + length = args.length; + + while (++index < length) { + var fromIndex = 0, + value = args[index]; + + while ((fromIndex = indexOf(array, value, fromIndex)) > -1) { + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * Removes elements from `array` corresponding to the given indexes and returns + * an array of the removed elements. Indexes may be specified as an array of + * indexes or as individual arguments. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove, + * specified as individual indexes or arrays of indexes. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [5, 10, 15, 20]; + * var evens = _.pullAt(array, 1, 3); + * + * console.log(array); + * // => [5, 15] + * + * console.log(evens); + * // => [10, 20] + */ + var pullAt = restParam(function(array, indexes) { + indexes = baseFlatten(indexes); + + var result = baseAt(array, indexes); + basePullAt(array, indexes.sort(baseCompareAscending)); + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is bound to + * `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * **Note:** Unlike `_.filter`, this method mutates `array`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to modify. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate, thisArg) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getCallback(predicate, thisArg, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @alias tail + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + */ + function rest(array) { + return drop(array, 1); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of `Array#slice` to support node + * lists in IE < 9 and to ensure dense arrays are returned. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` should + * be inserted into `array` in order to maintain its sort order. If an iteratee + * function is provided it is invoked for `value` and each element of `array` + * to compute their sort ranking. The iteratee is bound to `thisArg` and + * invoked with one argument; (value). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + * + * _.sortedIndex([4, 4, 5, 5], 5); + * // => 2 + * + * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } }; + * + * // using an iteratee function + * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) { + * return this.data[word]; + * }, dict); + * // => 1 + * + * // using the `_.property` callback shorthand + * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 1 + */ + var sortedIndex = createSortedIndex(); + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 4, 5, 5], 5); + * // => 4 + */ + var sortedLastIndex = createSortedIndex(true); + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (guard ? isIterateeCall(array, n, guard) : n == null) { + n = 1; + } + n = length - (+n || 0); + return baseSlice(array, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is bound to `thisArg` + * and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRightWhile([1, 2, 3], function(n) { + * return n > 1; + * }); + * // => [2, 3] + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user'); + * // => ['pebbles'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.takeRightWhile(users, 'active', false), 'user'); + * // => ['fred', 'pebbles'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.takeRightWhile(users, 'active'), 'user'); + * // => [] + */ + function takeRightWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is bound to + * `thisArg` and invoked with three arguments: (value, index, array). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to query. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeWhile([1, 2, 3], function(n) { + * return n < 3; + * }); + * // => [1, 2] + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false}, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.takeWhile(users, 'active', false), 'user'); + * // => ['barney', 'fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.takeWhile(users, 'active'), 'user'); + * // => [] + */ + function takeWhile(array, predicate, thisArg) { + return (array && array.length) + ? baseWhile(array, getCallback(predicate, thisArg, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all of the provided arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([1, 2], [4, 2], [2, 1]); + * // => [1, 2, 4] + */ + var union = restParam(function(arrays) { + return baseUniq(baseFlatten(arrays, false, true)); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurence of each element + * is kept. Providing `true` for `isSorted` performs a faster search algorithm + * for sorted arrays. If an iteratee function is provided it is invoked for + * each element in the array to generate the criterion by which uniqueness + * is computed. The `iteratee` is bound to `thisArg` and invoked with three + * arguments: (value, index, array). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias unique + * @category Array + * @param {Array} array The array to inspect. + * @param {boolean} [isSorted] Specify the array is sorted. + * @param {Function|Object|string} [iteratee] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new duplicate-value-free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + * + * // using `isSorted` + * _.uniq([1, 1, 2], true); + * // => [1, 2] + * + * // using an iteratee function + * _.uniq([1, 2.5, 1.5, 2], function(n) { + * return this.floor(n); + * }, Math); + * // => [1, 2.5] + * + * // using the `_.property` callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniq(array, isSorted, iteratee, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + if (isSorted != null && typeof isSorted != 'boolean') { + thisArg = iteratee; + iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted; + isSorted = false; + } + var callback = getCallback(); + if (!(iteratee == null && callback === baseCallback)) { + iteratee = callback(iteratee, thisArg, 3); + } + return (isSorted && getIndexOf() == baseIndexOf) + ? sortedUniq(array, iteratee) + : baseUniq(array, iteratee); + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + * + * _.unzip(zipped); + * // => [['fred', 'barney'], [30, 40], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var index = -1, + length = 0; + + array = arrayFilter(array, function(group) { + if (isArrayLike(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + var result = Array(length); + while (++index < length) { + result[index] = arrayMap(array, baseProperty(index)); + } + return result; + } + + /** + * This method is like `_.unzip` except that it accepts an iteratee to specify + * how regrouped values should be combined. The `iteratee` is bound to `thisArg` + * and invoked with four arguments: (accumulator, value, index, group). + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee] The function to combine regrouped values. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee, thisArg) { + var length = array ? array.length : 0; + if (!length) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + iteratee = bindCallback(iteratee, thisArg, 4); + return arrayMap(result, function(group) { + return arrayReduce(group, iteratee, undefined, true); + }); + } + + /** + * Creates an array excluding all provided values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @category Array + * @param {Array} array The array to filter. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.without([1, 2, 1, 3], 1, 2); + * // => [3] + */ + var without = restParam(function(array, values) { + return isArrayLike(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the provided arrays. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of values. + * @example + * + * _.xor([1, 2], [4, 2]); + * // => [1, 4] + */ + function xor() { + var index = -1, + length = arguments.length; + + while (++index < length) { + var array = arguments[index]; + if (isArrayLike(array)) { + var result = result + ? arrayPush(baseDifference(result, array), baseDifference(array, result)) + : array; + } + } + return result ? baseUniq(result) : []; + } + + /** + * Creates an array of grouped elements, the first of which contains the first + * elements of the given arrays, the second of which contains the second elements + * of the given arrays, and so on. + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['fred', 'barney'], [30, 40], [true, false]); + * // => [['fred', 30, true], ['barney', 40, false]] + */ + var zip = restParam(unzip); + + /** + * The inverse of `_.pairs`; this method returns an object composed from arrays + * of property names and values. Provide either a single two dimensional array, + * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names + * and one of corresponding values. + * + * @static + * @memberOf _ + * @alias object + * @category Array + * @param {Array} props The property names. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject([['fred', 30], ['barney', 40]]); + * // => { 'fred': 30, 'barney': 40 } + * + * _.zipObject(['fred', 'barney'], [30, 40]); + * // => { 'fred': 30, 'barney': 40 } + */ + function zipObject(props, values) { + var index = -1, + length = props ? props.length : 0, + result = {}; + + if (length && !values && !isArray(props[0])) { + values = []; + } + while (++index < length) { + var key = props[index]; + if (values) { + result[key] = values[index]; + } else if (key) { + result[key[0]] = key[1]; + } + } + return result; + } + + /** + * This method is like `_.zip` except that it accepts an iteratee to specify + * how grouped values should be combined. The `iteratee` is bound to `thisArg` + * and invoked with four arguments: (accumulator, value, index, group). + * + * @static + * @memberOf _ + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee] The function to combine grouped values. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], _.add); + * // => [111, 222] + */ + var zipWith = restParam(function(arrays) { + var length = arrays.length, + iteratee = length > 2 ? arrays[length - 2] : undefined, + thisArg = length > 1 ? arrays[length - 1] : undefined; + + if (length > 2 && typeof iteratee == 'function') { + length -= 2; + } else { + iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined; + thisArg = undefined; + } + arrays.length = length; + return unzipWith(arrays, iteratee, thisArg); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object that wraps `value` with explicit method + * chaining enabled. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _.chain(users) + * .sortBy('age') + * .map(function(chr) { + * return chr.user + ' is ' + chr.age; + * }) + * .first() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor is + * bound to `thisArg` and invoked with one argument; (value). The purpose of + * this method is to "tap into" a method chain in order to perform operations + * on intermediate results within the chain. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor, thisArg) { + interceptor.call(thisArg, value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * + * @static + * @memberOf _ + * @category Chain + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @param {*} [thisArg] The `this` binding of `interceptor`. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor, thisArg) { + return interceptor.call(thisArg, value); + } + + /** + * Enables explicit method chaining on the wrapper object. + * + * @name chain + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // without explicit chaining + * _(users).first(); + * // => { 'user': 'barney', 'age': 36 } + * + * // with explicit chaining + * _(users).chain() + * .first() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chained sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Creates a new array joining a wrapped array with any additional arrays + * and/or values. + * + * @name concat + * @memberOf _ + * @category Chain + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var wrapped = _(array).concat(2, [3], [[4]]); + * + * console.log(wrapped.value()); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + var wrapperConcat = restParam(function(values) { + values = baseFlatten(values); + return this.thru(function(array) { + return arrayConcat(isArray(array) ? array : [toObject(array)], values); + }); + }); + + /** + * Creates a clone of the chained sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).map(function(value) { + * return Math.pow(value, 2); + * }); + * + * var other = [3, 4]; + * var otherWrapped = wrapped.plant(other); + * + * otherWrapped.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * Reverses the wrapped array so the first element becomes the last, the + * second element becomes the second to last, and so on. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @category Chain + * @returns {Object} Returns the new reversed `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + + var interceptor = function(value) { + return (wrapped && wrapped.__dir__ < 0) ? value : value.reverse(); + }; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(interceptor); + } + + /** + * Produces the result of coercing the unwrapped value to a string. + * + * @name toString + * @memberOf _ + * @category Chain + * @returns {string} Returns the coerced string value. + * @example + * + * _([1, 2, 3]).toString(); + * // => '1,2,3' + */ + function wrapperToString() { + return (this.value() + ''); + } + + /** + * Executes the chained sequence to extract the unwrapped value. + * + * @name value + * @memberOf _ + * @alias run, toJSON, valueOf + * @category Chain + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements corresponding to the given keys, or indexes, + * of `collection`. Keys may be specified as individual arguments or as arrays + * of keys. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(number|number[]|string|string[])} [props] The property names + * or indexes of elements to pick, specified individually or in arrays. + * @returns {Array} Returns the new array of picked elements. + * @example + * + * _.at(['a', 'b', 'c'], [0, 2]); + * // => ['a', 'c'] + * + * _.at(['barney', 'fred', 'pebbles'], 0, 2); + * // => ['barney', 'pebbles'] + */ + var at = restParam(function(collection, props) { + return baseAt(collection, baseFlatten(props)); + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the number of times the key was returned by `iteratee`. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(n) { + * return Math.floor(n); + * }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(n) { + * return this.floor(n); + * }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1); + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * The predicate is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // using the `_.matchesProperty` callback shorthand + * _.every(users, 'active', false); + * // => true + * + * // using the `_.property` callback shorthand + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (thisArg && isIterateeCall(collection, predicate, thisArg)) { + predicate = undefined; + } + if (typeof predicate != 'function' || thisArg !== undefined) { + predicate = getCallback(predicate, thisArg, 3); + } + return func(collection, predicate); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * _.filter([4, 5, 6], function(n) { + * return n % 2 == 0; + * }); + * // => [4, 6] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.filter(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.filter(users, 'active'), 'user'); + * // => ['barney'] + */ + function filter(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = getCallback(predicate, thisArg, 3); + return func(collection, predicate); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is bound to `thisArg` and + * invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias detect + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.result(_.find(users, function(chr) { + * return chr.age < 40; + * }), 'user'); + * // => 'barney' + * + * // using the `_.matches` callback shorthand + * _.result(_.find(users, { 'age': 1, 'active': true }), 'user'); + * // => 'pebbles' + * + * // using the `_.matchesProperty` callback shorthand + * _.result(_.find(users, 'active', false), 'user'); + * // => 'fred' + * + * // using the `_.property` callback shorthand + * _.result(_.find(users, 'active'), 'user'); + * // => 'barney' + */ + var find = createFind(baseEach); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(baseEachRight, true); + + /** + * Performs a deep comparison between each element in `collection` and the + * source object, returning the first element that has equivalent property + * values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user'); + * // => 'barney' + * + * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user'); + * // => 'fred' + */ + function findWhere(collection, source) { + return find(collection, baseMatches(source)); + } + + /** + * Iterates over elements of `collection` invoking `iteratee` for each element. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). Iteratee functions may exit iteration early + * by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" property + * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` + * may be used for object iteration. + * + * @static + * @memberOf _ + * @alias each + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2]).forEach(function(n) { + * console.log(n); + * }).value(); + * // => logs each value from left to right and returns the array + * + * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) { + * console.log(n, key); + * }); + * // => logs each value-key pair and returns the object (iteration order is not guaranteed) + */ + var forEach = createForEach(arrayEach, baseEach); + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias eachRight + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array|Object|string} Returns `collection`. + * @example + * + * _([1, 2]).forEachRight(function(n) { + * console.log(n); + * }).value(); + * // => logs each value from right to left and returns the array + */ + var forEachRight = createForEach(arrayEachRight, baseEachRight); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is an array of the elements responsible for generating the key. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { + * return Math.floor(n); + * }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(n) { + * return this.floor(n); + * }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using the `_.property` callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + result[key] = [value]; + } + }); + + /** + * Checks if `value` is in `collection` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it is used as the offset + * from the end of `collection`. + * + * @static + * @memberOf _ + * @alias contains, include + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {*} target The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. + * @returns {boolean} Returns `true` if a matching element is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'user': 'fred', 'age': 40 }, 'fred'); + * // => true + * + * _.includes('pebbles', 'eb'); + * // => true + */ + function includes(collection, target, fromIndex, guard) { + var length = collection ? getLength(collection) : 0; + if (!isLength(length)) { + collection = values(collection); + length = collection.length; + } + if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) { + fromIndex = 0; + } else { + fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); + } + return (typeof collection == 'string' || !isArray(collection) && isString(collection)) + ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1) + : (!!length && getIndexOf(collection, target, fromIndex) > -1); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` through `iteratee`. The corresponding value + * of each key is the last element responsible for generating the key. The + * iteratee function is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var keyData = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.indexBy(keyData, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { + * return String.fromCharCode(object.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.indexBy(keyData, function(object) { + * return this.fromCharCode(object.code); + * }, String); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + */ + var indexBy = createAggregator(function(result, value, key) { + result[key] = value; + }); + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `methodName` is a function it is + * invoked for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invoke = restParam(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + isProp = isKey(path), + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined); + result[++index] = func ? func.apply(value, args) : invokePath(value, path, args); + }); + return result; + }); + + /** + * Creates an array of values by running each element in `collection` through + * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three + * arguments: (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, + * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`, + * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`, + * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`, + * `sum`, `uniq`, and `words` + * + * @static + * @memberOf _ + * @alias collect + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new mapped array. + * @example + * + * function timesThree(n) { + * return n * 3; + * } + * + * _.map([1, 2], timesThree); + * // => [3, 6] + * + * _.map({ 'a': 1, 'b': 2 }, timesThree); + * // => [3, 6] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // using the `_.property` callback shorthand + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee, thisArg) { + var func = isArray(collection) ? arrayMap : baseMap; + iteratee = getCallback(iteratee, thisArg, 3); + return func(collection, iteratee); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, while the second of which + * contains elements `predicate` returns falsey for. The predicate is bound + * to `thisArg` and invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * _.partition([1, 2, 3], function(n) { + * return n % 2; + * }); + * // => [[1, 3], [2]] + * + * _.partition([1.2, 2.3, 3.4], function(n) { + * return this.floor(n) % 2; + * }, Math); + * // => [[1.2, 3.4], [2.3]] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * var mapper = function(array) { + * return _.pluck(array, 'user'); + * }; + * + * // using the `_.matches` callback shorthand + * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper); + * // => [['pebbles'], ['barney', 'fred']] + * + * // using the `_.matchesProperty` callback shorthand + * _.map(_.partition(users, 'active', false), mapper); + * // => [['barney', 'pebbles'], ['fred']] + * + * // using the `_.property` callback shorthand + * _.map(_.partition(users, 'active'), mapper); + * // => [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Gets the property value of `path` from all elements in `collection`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Array|string} path The path of the property to pluck. + * @returns {Array} Returns the property values. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * _.pluck(users, 'user'); + * // => ['barney', 'fred'] + * + * var userIndex = _.indexBy(users, 'user'); + * _.pluck(userIndex, 'age'); + * // => [36, 40] (iteration order is not guaranteed) + */ + function pluck(collection, path) { + return map(collection, property(path)); + } + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` through `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not provided the first element of `collection` is used as the initial + * value. The `iteratee` is bound to `thisArg` and invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`, + * and `sortByOrder` + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * _.reduce([1, 2], function(total, n) { + * return total + n; + * }); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) { + * result[key] = n * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed) + */ + var reduce = createReduce(arrayReduce, baseEach); + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + var reduceRight = createReduce(arrayReduceRight, baseEachRight); + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Array} Returns the new filtered array. + * @example + * + * _.reject([1, 2, 3, 4], function(n) { + * return n % 2 == 0; + * }); + * // => [1, 3] + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * // using the `_.matches` callback shorthand + * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user'); + * // => ['barney'] + * + * // using the `_.matchesProperty` callback shorthand + * _.pluck(_.reject(users, 'active', false), 'user'); + * // => ['fred'] + * + * // using the `_.property` callback shorthand + * _.pluck(_.reject(users, 'active'), 'user'); + * // => ['barney'] + */ + function reject(collection, predicate, thisArg) { + var func = isArray(collection) ? arrayFilter : baseFilter; + predicate = getCallback(predicate, thisArg, 3); + return func(collection, function(value, index, collection) { + return !predicate(value, index, collection); + }); + } + + /** + * Gets a random element or `n` random elements from a collection. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to sample. + * @param {number} [n] The number of elements to sample. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {*} Returns the random sample(s). + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + * + * _.sample([1, 2, 3, 4], 2); + * // => [3, 1] + */ + function sample(collection, n, guard) { + if (guard ? isIterateeCall(collection, n, guard) : n == null) { + collection = toIterable(collection); + var length = collection.length; + return length > 0 ? collection[baseRandom(0, length - 1)] : undefined; + } + var index = -1, + result = toArray(collection), + length = result.length, + lastIndex = length - 1; + + n = nativeMin(n < 0 ? 0 : (+n || 0), length); + while (++index < n) { + var rand = baseRandom(index, lastIndex), + value = result[rand]; + + result[rand] = result[index]; + result[index] = value; + } + result.length = n; + return result; + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + return sample(collection, POSITIVE_INFINITY); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the size of `collection`. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + var length = collection ? getLength(collection) : 0; + return isLength(length) ? length : keys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * The function returns as soon as it finds a passing value and does not iterate + * over the entire collection. The predicate is bound to `thisArg` and invoked + * with three arguments: (value, index|key, collection). + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // using the `_.matches` callback shorthand + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // using the `_.matchesProperty` callback shorthand + * _.some(users, 'active', false); + * // => true + * + * // using the `_.property` callback shorthand + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, thisArg) { + var func = isArray(collection) ? arraySome : baseSome; + if (thisArg && isIterateeCall(collection, predicate, thisArg)) { + predicate = undefined; + } + if (typeof predicate != 'function' || thisArg !== undefined) { + predicate = getCallback(predicate, thisArg, 3); + } + return func(collection, predicate); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection through `iteratee`. This method performs + * a stable sort, that is, it preserves the original sort order of equal elements. + * The `iteratee` is bound to `thisArg` and invoked with three arguments: + * (value, index|key, collection). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Array} Returns the new sorted array. + * @example + * + * _.sortBy([1, 2, 3], function(n) { + * return Math.sin(n); + * }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(n) { + * return this.sin(n); + * }, Math); + * // => [3, 1, 2] + * + * var users = [ + * { 'user': 'fred' }, + * { 'user': 'pebbles' }, + * { 'user': 'barney' } + * ]; + * + * // using the `_.property` callback shorthand + * _.pluck(_.sortBy(users, 'user'), 'user'); + * // => ['barney', 'fred', 'pebbles'] + */ + function sortBy(collection, iteratee, thisArg) { + if (collection == null) { + return []; + } + if (thisArg && isIterateeCall(collection, iteratee, thisArg)) { + iteratee = undefined; + } + var index = -1; + iteratee = getCallback(iteratee, thisArg, 3); + + var result = baseMap(collection, function(value, key, collection) { + return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value }; + }); + return baseSortBy(result, compareAscending); + } + + /** + * This method is like `_.sortBy` except that it can sort by multiple iteratees + * or property names. + * + * If a property name is provided for an iteratee the created `_.property` + * style callback returns the property value of the given element. + * + * If an object is provided for an iteratee the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees + * The iteratees to sort by, specified as individual values or arrays of values. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.map(_.sortByAll(users, ['user', 'age']), _.values); + * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]] + * + * _.map(_.sortByAll(users, 'user', function(chr) { + * return Math.floor(chr.age / 10); + * }), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ + var sortByAll = restParam(function(collection, iteratees) { + if (collection == null) { + return []; + } + var guard = iteratees[2]; + if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) { + iteratees.length = 1; + } + return baseSortByOrder(collection, baseFlatten(iteratees), []); + }); + + /** + * This method is like `_.sortByAll` except that it allows specifying the + * sort orders of the iteratees to sort by. If `orders` is unspecified, all + * values are sorted in ascending order. Otherwise, a value is sorted in + * ascending order if its corresponding order is "asc", and descending if "desc". + * + * If a property name is provided for an iteratee the created `_.property` + * style callback returns the property value of the given element. + * + * If an object is provided for an iteratee the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {boolean[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 42 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // sort by `user` in ascending order and by `age` in descending order + * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values); + * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]] + */ + function sortByOrder(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (guard && isIterateeCall(iteratees, orders, guard)) { + orders = undefined; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseSortByOrder(collection, iteratees, orders); + } + + /** + * Performs a deep comparison between each element in `collection` and the + * source object, returning an array of all elements that have equivalent + * property values. + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. For comparing a single + * own or inherited property value see `_.matchesProperty`. + * + * @static + * @memberOf _ + * @category Collection + * @param {Array|Object|string} collection The collection to search. + * @param {Object} source The object of property values to match. + * @returns {Array} Returns the new filtered array. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] }, + * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] } + * ]; + * + * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user'); + * // => ['barney'] + * + * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user'); + * // => ['fred'] + */ + function where(collection, source) { + return filter(collection, baseMatches(source)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Gets the number of milliseconds that have elapsed since the Unix epoch + * (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @category Date + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => logs the number of milliseconds it took for the deferred function to be invoked + */ + var now = nativeNow || function() { + return new Date().getTime(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it is called `n` or more times. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => logs 'done saving!' after the two async saves have completed + */ + function after(n, func) { + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + n = nativeIsFinite(n = +n) ? n : 0; + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that accepts up to `n` arguments ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + if (guard && isIterateeCall(func, n, guard)) { + n = undefined; + } + n = (func && n == null) ? func.length : nativeMax(+n || 0, 0); + return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it is called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery('#add').on('click', _.before(5, addContactToList)); + * // => allows adding up to 4 contacts to the list + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + if (typeof n == 'function') { + var temp = n; + n = func; + func = temp; + } else { + throw new TypeError(FUNC_ERROR_TEXT); + } + } + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and prepends any additional `_.bind` arguments to those provided to the + * bound function. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind` this method does not set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var greet = function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * }; + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // using placeholders + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = restParam(function(func, thisArg, partials) { + var bitmask = BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, bind.placeholder); + bitmask |= PARTIAL_FLAG; + } + return createWrapper(func, bitmask, thisArg, partials, holders); + }); + + /** + * Binds methods of an object to the object itself, overwriting the existing + * method. Method names may be specified as individual arguments or as arrays + * of method names. If no method names are provided all enumerable function + * properties, own and inherited, of `object` are bound. + * + * **Note:** This method does not set the "length" property of bound functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...(string|string[])} [methodNames] The object method names to bind, + * specified as individual method names or arrays of method names. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { + * console.log('clicked ' + this.label); + * } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => logs 'clicked docs' when the element is clicked + */ + var bindAll = restParam(function(object, methodNames) { + methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object); + + var index = -1, + length = methodNames.length; + + while (++index < length) { + var key = methodNames[index]; + object[key] = createWrapper(object[key], BIND_FLAG, object); + } + return object; + }); + + /** + * Creates a function that invokes the method at `object[key]` and prepends + * any additional `_.bindKey` arguments to those provided to the bound function. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. + * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @category Function + * @param {Object} object The object the method belongs to. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // using placeholders + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = restParam(function(object, key, partials) { + var bitmask = BIND_FLAG | BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, bindKey.placeholder); + bitmask |= PARTIAL_FLAG; + } + return createWrapper(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts one or more arguments of `func` that when + * called either invokes `func` returning its result, if all `func` arguments + * have been provided, or returns a function that accepts one or more of the + * remaining `func` arguments, and so on. The arity of `func` may be specified + * if `func.length` is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + var curry = createCurry(CURRY_FLAG); + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method does not set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // using placeholders + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + var curryRight = createCurry(CURRY_RIGHT_FLAG); + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed invocations. Provide an options object to indicate that `func` + * should be invoked on the leading and/or trailing edge of the `wait` timeout. + * Subsequent calls to the debounced function return the result of the last + * `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the debounced function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=false] Specify invoking on the leading + * edge of the timeout. + * @param {number} [options.maxWait] The maximum time `func` is allowed to be + * delayed before it is invoked. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // avoid costly calculations while the window size is in flux + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // invoke `sendMail` when the click event is fired, debouncing subsequent calls + * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // ensure `batchLog` is invoked once after 1 second of debounced calls + * var source = new EventSource('/stream'); + * jQuery(source).on('message', _.debounce(batchLog, 250, { + * 'maxWait': 1000 + * })); + * + * // cancel a debounced call + * var todoChanges = _.debounce(batchLog, 1000); + * Object.observe(models.todo, todoChanges); + * + * Object.observe(models, function(changes) { + * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { + * todoChanges.cancel(); + * } + * }, ['delete']); + * + * // ...at some point `models.todo` is changed + * models.todo.completed = true; + * + * // ...before 1 second has passed `models.todo` is deleted + * // which cancels the debounced `todoChanges` call + * delete models.todo; + */ + function debounce(func, wait, options) { + var args, + maxTimeoutId, + result, + stamp, + thisArg, + timeoutId, + trailingCall, + lastCalled = 0, + maxWait = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = wait < 0 ? 0 : (+wait || 0); + if (options === true) { + var leading = true; + trailing = false; + } else if (isObject(options)) { + leading = !!options.leading; + maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function cancel() { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (maxTimeoutId) { + clearTimeout(maxTimeoutId); + } + lastCalled = 0; + maxTimeoutId = timeoutId = trailingCall = undefined; + } + + function complete(isCalled, id) { + if (id) { + clearTimeout(id); + } + maxTimeoutId = timeoutId = trailingCall = undefined; + if (isCalled) { + lastCalled = now(); + result = func.apply(thisArg, args); + if (!timeoutId && !maxTimeoutId) { + args = thisArg = undefined; + } + } + } + + function delayed() { + var remaining = wait - (now() - stamp); + if (remaining <= 0 || remaining > wait) { + complete(trailingCall, maxTimeoutId); + } else { + timeoutId = setTimeout(delayed, remaining); + } + } + + function maxDelayed() { + complete(trailing, timeoutId); + } + + function debounced() { + args = arguments; + stamp = now(); + thisArg = this; + trailingCall = trailing && (timeoutId || !leading); + + if (maxWait === false) { + var leadingCall = leading && !timeoutId; + } else { + if (!maxTimeoutId && !leading) { + lastCalled = stamp; + } + var remaining = maxWait - (stamp - lastCalled), + isCalled = remaining <= 0 || remaining > maxWait; + + if (isCalled) { + if (maxTimeoutId) { + maxTimeoutId = clearTimeout(maxTimeoutId); + } + lastCalled = stamp; + result = func.apply(thisArg, args); + } + else if (!maxTimeoutId) { + maxTimeoutId = setTimeout(maxDelayed, remaining); + } + } + if (isCalled && timeoutId) { + timeoutId = clearTimeout(timeoutId); + } + else if (!timeoutId && wait !== maxWait) { + timeoutId = setTimeout(delayed, wait); + } + if (leadingCall) { + isCalled = true; + result = func.apply(thisArg, args); + } + if (isCalled && !timeoutId && !maxTimeoutId) { + args = thisArg = undefined; + } + return result; + } + debounced.cancel = cancel; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // logs 'deferred' after one or more milliseconds + */ + var defer = restParam(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke the function with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => logs 'later' after one second + */ + var delay = restParam(function(func, wait, args) { + return baseDelay(func, wait, args); + }); + + /** + * Creates a function that returns the result of invoking the provided + * functions with the `this` binding of the created function, where each + * successive invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow(_.add, square); + * addSquare(1, 2); + * // => 9 + */ + var flow = createFlow(); + + /** + * This method is like `_.flow` except that it creates a function that + * invokes the provided functions from right to left. + * + * @static + * @memberOf _ + * @alias backflow, compose + * @category Function + * @param {...Function} [funcs] Functions to invoke. + * @returns {Function} Returns the new function. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight(square, _.add); + * addSquare(1, 2); + * // => 9 + */ + var flowRight = createFlow(true); + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is coerced to a string and used as the + * cache key. The `func` is invoked with the `this` binding of the memoized + * function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object) + * method interface of `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var upperCase = _.memoize(function(string) { + * return string.toUpperCase(); + * }); + * + * upperCase('fred'); + * // => 'FRED' + * + * // modifying the result cache + * upperCase.cache.set('fred', 'BARNEY'); + * upperCase('fred'); + * // => 'BARNEY' + * + * // replacing `_.memoize.Cache` + * var object = { 'user': 'fred' }; + * var other = { 'user': 'barney' }; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'fred' } + * + * _.memoize.Cache = WeakMap; + * var identity = _.memoize(_.identity); + * + * identity(object); + * // => { 'user': 'fred' } + * identity(other); + * // => { 'user': 'barney' } + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result); + return result; + }; + memoized.cache = new memoize.Cache; + return memoized; + } + + /** + * Creates a function that runs each argument through a corresponding + * transform function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms] The functions to transform + * arguments, specified as individual functions or arrays of functions. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var modded = _.modArgs(function(x, y) { + * return [x, y]; + * }, square, doubled); + * + * modded(1, 2); + * // => [1, 4] + * + * modded(5, 10); + * // => [25, 20] + */ + var modArgs = restParam(function(func, transforms) { + transforms = baseFlatten(transforms); + if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = transforms.length; + return restParam(function(args) { + var index = nativeMin(args.length, length); + while (index--) { + args[index] = transforms[index](args[index]); + } + return func.apply(this, args); + }); + }); + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + return !predicate.apply(this, arguments); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first call. The `func` is invoked + * with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` invokes `createApplication` once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with `partial` arguments prepended + * to those provided to the new function. This method is like `_.bind` except + * it does **not** alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // using placeholders + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = createPartial(PARTIAL_FLAG); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to those provided to the new function. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method does not set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { + * return greeting + ' ' + name; + * }; + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // using placeholders + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = createPartial(PARTIAL_RIGHT_FLAG); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified indexes where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes, + * specified as individual indexes or arrays of indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, 2, 0, 1); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + * + * var map = _.rearg(_.map, [1, 0]); + * map(function(n) { + * return n * 3; + * }, [1, 2, 3]); + * // => [3, 6, 9] + */ + var rearg = restParam(function(func, indexes) { + return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes)); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as an array. + * + * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.restParam(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function restParam(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + rest = Array(length); + + while (++index < length) { + rest[index] = args[start + index]; + } + switch (start) { + case 0: return func.call(this, rest); + case 1: return func.call(this, args[0], rest); + case 2: return func.call(this, args[0], args[1], rest); + } + var otherArgs = Array(start + 1); + index = -1; + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = rest; + return func.apply(this, otherArgs); + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of the created + * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3). + * + * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to spread arguments over. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * // with a Promise + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function(array) { + return func.apply(this, array); + }; + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed invocations. Provide an options object to indicate + * that `func` should be invoked on the leading and/or trailing edge of the + * `wait` timeout. Subsequent calls to the throttled function return the + * result of the last `func` call. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked + * on the trailing edge of the timeout only if the the throttled function is + * invoked more than once during the `wait` timeout. + * + * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options] The options object. + * @param {boolean} [options.leading=true] Specify invoking on the leading + * edge of the timeout. + * @param {boolean} [options.trailing=true] Specify invoking on the trailing + * edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // avoid excessively updating the position while scrolling + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes + * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { + * 'trailing': false + * })); + * + * // cancel a trailing throttled call + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (options === false) { + leading = false; + } else if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing }); + } + + /** + * Creates a function that provides `value` to the wrapper function as its + * first argument. Any additional arguments provided to the function are + * appended to those provided to the wrapper function. The wrapper is invoked + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Function + * @param {*} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + wrapper = wrapper == null ? identity : wrapper; + return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned, + * otherwise they are assigned by reference. If `customizer` is provided it is + * invoked to produce the cloned values. If `customizer` returns `undefined` + * cloning is handled by the method instead. The `customizer` is bound to + * `thisArg` and invoked with two argument; (value [, index|key, object]). + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). + * The enumerable properties of `arguments` objects and objects created by + * constructors other than `Object` are cloned to plain `Object` objects. An + * empty object is returned for uncloneable values such as functions, DOM nodes, + * Maps, Sets, and WeakMaps. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @param {Function} [customizer] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {*} Returns the cloned value. + * @example + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * var shallow = _.clone(users); + * shallow[0] === users[0]; + * // => true + * + * var deep = _.clone(users, true); + * deep[0] === users[0]; + * // => false + * + * // using a customizer callback + * var el = _.clone(document.body, function(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * }); + * + * el === document.body + * // => false + * el.nodeName + * // => BODY + * el.childNodes.length; + * // => 0 + */ + function clone(value, isDeep, customizer, thisArg) { + if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) { + isDeep = false; + } + else if (typeof isDeep == 'function') { + thisArg = customizer; + customizer = isDeep; + isDeep = false; + } + return typeof customizer == 'function' + ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1)) + : baseClone(value, isDeep); + } + + /** + * Creates a deep clone of `value`. If `customizer` is provided it is invoked + * to produce the cloned values. If `customizer` returns `undefined` cloning + * is handled by the method instead. The `customizer` is bound to `thisArg` + * and invoked with two argument; (value [, index|key, object]). + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm). + * The enumerable properties of `arguments` objects and objects created by + * constructors other than `Object` are cloned to plain `Object` objects. An + * empty object is returned for uncloneable values such as functions, DOM nodes, + * Maps, Sets, and WeakMaps. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to deep clone. + * @param {Function} [customizer] The function to customize cloning values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {*} Returns the deep cloned value. + * @example + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * var deep = _.cloneDeep(users); + * deep[0] === users[0]; + * // => false + * + * // using a customizer callback + * var el = _.cloneDeep(document.body, function(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * }); + * + * el === document.body + * // => false + * el.nodeName + * // => BODY + * el.childNodes.length; + * // => 20 + */ + function cloneDeep(value, customizer, thisArg) { + return typeof customizer == 'function' + ? baseClone(value, true, bindCallback(customizer, thisArg, 1)) + : baseClone(value, true); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`. + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + function gt(value, other) { + return value > other; + } + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`. + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + function gte(value, other) { + return value >= other; + } + + /** + * Checks if `value` is classified as an `arguments` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return isObjectLike(value) && isArrayLike(value) && + hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); + } + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(function() { return arguments; }()); + * // => false + */ + var isArray = nativeIsArray || function(value) { + return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; + }; + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag); + } + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + function isDate(value) { + return isObjectLike(value) && objToString.call(value) == dateTag; + } + + /** + * Checks if `value` is a DOM element. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value); + } + + /** + * Checks if `value` is empty. A value is considered empty unless it is an + * `arguments` object, array, string, or jQuery-like collection with a length + * greater than `0` or an object with own enumerable properties. + * + * @static + * @memberOf _ + * @category Lang + * @param {Array|Object|string} value The value to inspect. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) || + (isObjectLike(value) && isFunction(value.splice)))) { + return !value.length; + } + return !keys(value).length; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. If `customizer` is provided it is invoked to compare values. + * If `customizer` returns `undefined` comparisons are handled by the method + * instead. The `customizer` is bound to `thisArg` and invoked with three + * arguments: (value, other [, index|key]). + * + * **Note:** This method supports comparing arrays, booleans, `Date` objects, + * numbers, `Object` objects, regexes, and strings. Objects are compared by + * their own, not inherited, enumerable properties. Functions and DOM nodes + * are **not** supported. Provide a customizer function to extend support + * for comparing other values. + * + * @static + * @memberOf _ + * @alias eq + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize value comparisons. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'user': 'fred' }; + * var other = { 'user': 'fred' }; + * + * object == other; + * // => false + * + * _.isEqual(object, other); + * // => true + * + * // using a customizer callback + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqual(array, other, function(value, other) { + * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) { + * return true; + * } + * }); + * // => true + */ + function isEqual(value, other, customizer, thisArg) { + customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag; + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite). + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(10); + * // => true + * + * _.isFinite('10'); + * // => false + * + * _.isFinite(true); + * // => false + * + * _.isFinite(Object(10)); + * // => false + * + * _.isFinite(Infinity); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in older versions of Chrome and Safari which return 'function' for regexes + // and Safari 8 equivalents which return 'object' for typed array constructors. + return isObject(value) && objToString.call(value) == funcTag; + } + + /** + * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // Avoid a V8 JIT bug in Chrome 19-20. + // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); + } + + /** + * Performs a deep comparison between `object` and `source` to determine if + * `object` contains equivalent property values. If `customizer` is provided + * it is invoked to compare values. If `customizer` returns `undefined` + * comparisons are handled by the method instead. The `customizer` is bound + * to `thisArg` and invoked with three arguments: (value, other, index|key). + * + * **Note:** This method supports comparing properties of arrays, booleans, + * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions + * and DOM nodes are **not** supported. Provide a customizer function to extend + * support for comparing other values. + * + * @static + * @memberOf _ + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize value comparisons. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.isMatch(object, { 'age': 40 }); + * // => true + * + * _.isMatch(object, { 'age': 36 }); + * // => false + * + * // using a customizer callback + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatch(object, source, function(value, other) { + * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined; + * }); + * // => true + */ + function isMatch(object, source, customizer, thisArg) { + customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined; + return baseIsMatch(object, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4) + * which returns `true` for `undefined` and other non-numeric values. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some host objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a native function. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (value == null) { + return false; + } + if (isFunction(value)) { + return reIsNative.test(fnToString.call(value)); + } + return isObjectLike(value) && reIsHostCtor.test(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified + * as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(8.4); + * // => true + * + * _.isNumber(NaN); + * // => true + * + * _.isNumber('8.4'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * **Note:** This method assumes objects created by the `Object` constructor + * have no inherited enumerable properties. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + var Ctor; + + // Exit early for non `Object` objects. + if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) || + (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { + return false; + } + // IE < 9 iterates inherited properties before own properties. If the first + // iterated property is an object's own property then there are no inherited + // enumerable properties. + var result; + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + baseForIn(value, function(subValue, key) { + result = key; + }); + return result === undefined || hasOwnProperty.call(value, result); + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + function isRegExp(value) { + return isObject(value) && objToString.call(value) == regexpTag; + } + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + function isTypedArray(value) { + return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`. + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + function lt(value, other) { + return value < other; + } + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`. + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + function lte(value, other) { + return value <= other; + } + + /** + * Converts `value` to an array. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * (function() { + * return _.toArray(arguments).slice(1); + * }(1, 2, 3)); + * // => [2, 3] + */ + function toArray(value) { + var length = value ? getLength(value) : 0; + if (!isLength(length)) { + return values(value); + } + if (!length) { + return []; + } + return arrayCopy(value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable + * properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return baseCopy(value, keysIn(value)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Recursively merges own enumerable properties of the source object(s), that + * don't resolve to `undefined` into the destination object. Subsequent sources + * overwrite property assignments of previous sources. If `customizer` is + * provided it is invoked to produce the merged values of the destination and + * source properties. If `customizer` returns `undefined` merging is handled + * by the method instead. The `customizer` is bound to `thisArg` and invoked + * with five arguments: (objectValue, sourceValue, key, object, source). + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {Object} Returns `object`. + * @example + * + * var users = { + * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] + * }; + * + * var ages = { + * 'data': [{ 'age': 36 }, { 'age': 40 }] + * }; + * + * _.merge(users, ages); + * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } + * + * // using a customizer callback + * var object = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var other = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(object, other, function(a, b) { + * if (_.isArray(a)) { + * return a.concat(b); + * } + * }); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } + */ + var merge = createAssigner(baseMerge); + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources overwrite property assignments of previous sources. + * If `customizer` is provided it is invoked to produce the assigned values. + * The `customizer` is bound to `thisArg` and invoked with five arguments: + * (objectValue, sourceValue, key, object, source). + * + * **Note:** This method mutates `object` and is based on + * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign). + * + * @static + * @memberOf _ + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @param {*} [thisArg] The `this` binding of `customizer`. + * @returns {Object} Returns `object`. + * @example + * + * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' }); + * // => { 'user': 'fred', 'age': 40 } + * + * // using a customizer callback + * var defaults = _.partialRight(_.assign, function(value, other) { + * return _.isUndefined(value) ? other : value; + * }); + * + * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); + * // => { 'user': 'barney', 'age': 36 } + */ + var assign = createAssigner(function(object, source, customizer) { + return customizer + ? assignWith(object, source, customizer) + : baseAssign(object, source); + }); + + /** + * Creates an object that inherits from the given `prototype` object. If a + * `properties` object is provided its own enumerable properties are assigned + * to the created object. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties, guard) { + var result = baseCreate(prototype); + if (guard && isIterateeCall(prototype, properties, guard)) { + properties = undefined; + } + return properties ? baseAssign(result, properties) : result; + } + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object for all destination properties that resolve to `undefined`. Once a + * property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' }); + * // => { 'user': 'barney', 'age': 36 } + */ + var defaults = createDefaults(assign, assignDefaults); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } }); + * // => { 'user': { 'name': 'barney', 'age': 36 } } + * + */ + var defaultsDeep = createDefaults(merge, mergeDefaults); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {string|undefined} Returns the key of the matched element, else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(chr) { + * return chr.age < 40; + * }); + * // => 'barney' (iteration order is not guaranteed) + * + * // using the `_.matches` callback shorthand + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // using the `_.matchesProperty` callback shorthand + * _.findKey(users, 'active', false); + * // => 'fred' + * + * // using the `_.property` callback shorthand + * _.findKey(users, 'active'); + * // => 'barney' + */ + var findKey = createFindKey(baseForOwn); + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * If a property name is provided for `predicate` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `predicate` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to search. + * @param {Function|Object|string} [predicate=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {string|undefined} Returns the key of the matched element, else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(chr) { + * return chr.age < 40; + * }); + * // => returns `pebbles` assuming `_.findKey` returns `barney` + * + * // using the `_.matches` callback shorthand + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // using the `_.matchesProperty` callback shorthand + * _.findLastKey(users, 'active', false); + * // => 'fred' + * + * // using the `_.property` callback shorthand + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + var findLastKey = createFindKey(baseForOwnRight); + + /** + * Iterates over own and inherited enumerable properties of an object invoking + * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed) + */ + var forIn = createForIn(baseFor); + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c' + */ + var forInRight = createForIn(baseForRight); + + /** + * Iterates over own enumerable properties of an object invoking `iteratee` + * for each property. The `iteratee` is bound to `thisArg` and invoked with + * three arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'a' and 'b' (iteration order is not guaranteed) + */ + var forOwn = createForOwn(baseForOwn); + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns `object`. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b' + */ + var forOwnRight = createForOwn(baseForOwnRight); + + /** + * Creates an array of function property names from all enumerable properties, + * own and inherited, of `object`. + * + * @static + * @memberOf _ + * @alias methods + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the new array of property names. + * @example + * + * _.functions(_); + * // => ['after', 'ary', 'assign', ...] + */ + function functions(object) { + return baseFunctions(object, keysIn(object)); + } + + /** + * Gets the property value at `path` of `object`. If the resolved value is + * `undefined` the `defaultValue` is used in its place. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, toPath(path), path + ''); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` is a direct property, else `false`. + * @example + * + * var object = { 'a': { 'b': { 'c': 3 } } }; + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b.c'); + * // => true + * + * _.has(object, ['a', 'b', 'c']); + * // => true + */ + function has(object, path) { + if (object == null) { + return false; + } + var result = hasOwnProperty.call(object, path); + if (!result && !isKey(path)) { + path = toPath(path); + object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + if (object == null) { + return false; + } + path = last(path); + result = hasOwnProperty.call(object, path); + } + return result || (isLength(object.length) && isIndex(path, object.length) && + (isArray(object) || isArguments(object))); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite property + * assignments of previous values unless `multiValue` is `true`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to invert. + * @param {boolean} [multiValue] Allow multiple values per key. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + * + * // with `multiValue` + * _.invert(object, true); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function invert(object, multiValue, guard) { + if (guard && isIterateeCall(object, multiValue, guard)) { + multiValue = undefined; + } + var index = -1, + props = keys(object), + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index], + value = object[key]; + + if (multiValue) { + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + } + else { + result[value] = key; + } + } + return result; + } + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) + * for more details. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + var keys = !nativeKeys ? shimKeys : function(object) { + var Ctor = object == null ? undefined : object.constructor; + if ((typeof Ctor == 'function' && Ctor.prototype === object) || + (typeof object != 'function' && isArrayLike(object))) { + return shimKeys(object); + } + return isObject(object) ? nativeKeys(object) : []; + }; + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + if (object == null) { + return []; + } + if (!isObject(object)) { + object = Object(object); + } + var length = object.length; + length = (length && isLength(length) && + (isArray(object) || isArguments(object)) && length) || 0; + + var Ctor = object.constructor, + index = -1, + isProto = typeof Ctor == 'function' && Ctor.prototype === object, + result = Array(length), + skipIndexes = length > 0; + + while (++index < length) { + result[index] = (index + ''); + } + for (var key in object) { + if (!(skipIndexes && isIndex(key, length)) && + !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * property of `object` through `iteratee`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the new mapped object. + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + var mapKeys = createObjectMapper(true); + + /** + * Creates an object with the same keys as `object` and values generated by + * running each own enumerable property of `object` through `iteratee`. The + * iteratee function is bound to `thisArg` and invoked with three arguments: + * (value, key, object). + * + * If a property name is provided for `iteratee` the created `_.property` + * style callback returns the property value of the given element. + * + * If a value is also provided for `thisArg` the created `_.matchesProperty` + * style callback returns `true` for elements that have a matching property + * value, else `false`. + * + * If an object is provided for `iteratee` the created `_.matches` style + * callback returns `true` for elements that have the properties of the given + * object, else `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function|Object|string} [iteratee=_.identity] The function invoked + * per iteration. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {Object} Returns the new mapped object. + * @example + * + * _.mapValues({ 'a': 1, 'b': 2 }, function(n) { + * return n * 3; + * }); + * // => { 'a': 3, 'b': 6 } + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * // using the `_.property` callback shorthand + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + var mapValues = createObjectMapper(); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable properties of `object` that are not omitted. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {Function|...(string|string[])} [predicate] The function invoked per + * iteration or property names to omit, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.omit(object, 'age'); + * // => { 'user': 'fred' } + * + * _.omit(object, _.isNumber); + * // => { 'user': 'fred' } + */ + var omit = restParam(function(object, props) { + if (object == null) { + return {}; + } + if (typeof props[0] != 'function') { + var props = arrayMap(baseFlatten(props), String); + return pickByArray(object, baseDifference(keysIn(object), props)); + } + var predicate = bindCallback(props[0], props[1], 3); + return pickByCallback(object, function(value, key, object) { + return !predicate(value, key, object); + }); + }); + + /** + * Creates a two dimensional array of the key-value pairs for `object`, + * e.g. `[[key1, value1], [key2, value2]]`. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the new array of key-value pairs. + * @example + * + * _.pairs({ 'barney': 36, 'fred': 40 }); + * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed) + */ + function pairs(object) { + object = toObject(object); + + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + var key = props[index]; + result[index] = [key, object[key]]; + } + return result; + } + + /** + * Creates an object composed of the picked `object` properties. Property + * names may be specified as individual arguments or as arrays of property + * names. If `predicate` is provided it is invoked for each property of `object` + * picking the properties `predicate` returns truthy for. The predicate is + * bound to `thisArg` and invoked with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {Function|...(string|string[])} [predicate] The function invoked per + * iteration or property names to pick, specified as individual property + * names or arrays of property names. + * @param {*} [thisArg] The `this` binding of `predicate`. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'user': 'fred', 'age': 40 }; + * + * _.pick(object, 'user'); + * // => { 'user': 'fred' } + * + * _.pick(object, _.isString); + * // => { 'user': 'fred' } + */ + var pick = restParam(function(object, props) { + if (object == null) { + return {}; + } + return typeof props[0] == 'function' + ? pickByCallback(object, bindCallback(props[0], props[1], 3)) + : pickByArray(object, baseFlatten(props)); + }); + + /** + * This method is like `_.get` except that if the resolved value is a function + * it is invoked with the `this` binding of its parent object and its result + * is returned. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned if the resolved value is `undefined`. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a.b.c', 'default'); + * // => 'default' + * + * _.result(object, 'a.b.c', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + var result = object == null ? undefined : object[path]; + if (result === undefined) { + if (object != null && !isKey(path, object)) { + path = toPath(path); + object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); + result = object == null ? undefined : object[last(path)]; + } + result = result === undefined ? defaultValue : result; + } + return isFunction(result) ? result.call(object) : result; + } + + /** + * Sets the property value of `path` on `object`. If a portion of `path` + * does not exist it is created. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to augment. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, 'x[0].y.z', 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + if (object == null) { + return object; + } + var pathKey = (path + ''); + path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = path[index]; + if (isObject(nested)) { + if (index == lastIndex) { + nested[key] = value; + } else if (nested[key] == null) { + nested[key] = isIndex(path[index + 1]) ? [] : {}; + } + } + nested = nested[key]; + } + return object; + } + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own enumerable + * properties through `iteratee`, with each invocation potentially mutating + * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked + * with four arguments: (accumulator, value, key, object). Iteratee functions + * may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @category Object + * @param {Array|Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @param {*} [thisArg] The `this` binding of `iteratee`. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) { + * result[key] = n * 3; + * }); + * // => { 'a': 3, 'b': 6 } + */ + function transform(object, iteratee, accumulator, thisArg) { + var isArr = isArray(object) || isTypedArray(object); + iteratee = getCallback(iteratee, thisArg, 4); + + if (accumulator == null) { + if (isArr || isObject(object)) { + var Ctor = object.constructor; + if (isArr) { + accumulator = isArray(object) ? new Ctor : []; + } else { + accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined); + } + } else { + accumulator = {}; + } + } + (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Creates an array of the own enumerable property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable property values + * of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Checks if `n` is between `start` and up to but not including, `end`. If + * `end` is not specified it is set to `start` with `start` then set to `0`. + * + * @static + * @memberOf _ + * @category Number + * @param {number} n The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `n` is in the range, else `false`. + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + */ + function inRange(value, start, end) { + start = +start || 0; + if (end === undefined) { + end = start; + start = 0; + } else { + end = +end || 0; + } + return value >= nativeMin(start, end) && value < nativeMax(start, end); + } + + /** + * Produces a random number between `min` and `max` (inclusive). If only one + * argument is provided a number between `0` and the given number is returned. + * If `floating` is `true`, or either `min` or `max` are floats, a floating-point + * number is returned instead of an integer. + * + * @static + * @memberOf _ + * @category Number + * @param {number} [min=0] The minimum possible value. + * @param {number} [max=1] The maximum possible value. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(min, max, floating) { + if (floating && isIterateeCall(min, max, floating)) { + max = floating = undefined; + } + var noMin = min == null, + noMax = max == null; + + if (floating == null) { + if (noMax && typeof min == 'boolean') { + floating = min; + min = 1; + } + else if (typeof max == 'boolean') { + floating = max; + noMax = true; + } + } + if (noMin && noMax) { + max = 1; + noMax = false; + } + min = +min || 0; + if (noMax) { + max = min; + min = 0; + } else { + max = +max || 0; + } + if (floating || min % 1 || max % 1) { + var rand = nativeRandom(); + return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max); + } + return baseRandom(min, max); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar'); + * // => 'fooBar' + * + * _.camelCase('__foo_bar__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word); + }); + + /** + * Capitalizes the first character of `string`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('fred'); + * // => 'Fred' + */ + function capitalize(string) { + string = baseToString(string); + return string && (string.charAt(0).toUpperCase() + string.slice(1)); + } + + /** + * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = baseToString(string); + return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to search. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search from. + * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = baseToString(string); + target = (target + ''); + + var length = string.length; + position = position === undefined + ? length + : nativeMin(position < 0 ? 0 : (+position || 0), length); + + position -= target.length; + return position >= 0 && string.indexOf(target, position) == position; + } + + /** + * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to + * their corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional characters + * use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. + * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * Backticks are escaped because in Internet Explorer < 9, they can break out + * of attribute values or HTML comments. See [#59](https://html5sec.org/#59), + * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and + * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/) + * for more details. + * + * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping) + * to reduce XSS vectors. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + // Reset `lastIndex` because in IE < 9 `String#replace` does not. + string = baseToString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?", + * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https:\/\/lodash\.com\/\)' + */ + function escapeRegExp(string) { + string = baseToString(string); + return (string && reHasRegExpChars.test(string)) + ? string.replace(reRegExpChars, escapeRegExpChar) + : (string || '(?:)'); + } + + /** + * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__foo_bar__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = baseToString(string); + length = +length; + + var strLength = string.length; + if (strLength >= length || !nativeIsFinite(length)) { + return string; + } + var mid = (length - strLength) / 2, + leftLength = nativeFloor(mid), + rightLength = nativeCeil(mid); + + chars = createPadding('', rightLength, chars); + return chars.slice(0, leftLength) + string + chars; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padLeft('abc', 6); + * // => ' abc' + * + * _.padLeft('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padLeft('abc', 3); + * // => 'abc' + */ + var padLeft = createPadDir(); + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padRight('abc', 6); + * // => 'abc ' + * + * _.padRight('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padRight('abc', 3); + * // => 'abc' + */ + var padRight = createPadDir(true); + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal, + * in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E) + * of `parseInt`. + * + * @static + * @memberOf _ + * @category String + * @param {string} string The string to convert. + * @param {number} [radix] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as a callback for functions like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`. + // Chrome fails to trim leading whitespace characters. + // See https://code.google.com/p/v8/issues/detail?id=3109 for more details. + if (guard ? isIterateeCall(string, radix, guard) : radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + string = trim(string); + return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10)); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=0] The number of times to repeat the string. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n) { + var result = ''; + string = baseToString(string); + n = +n; + if (n < 1 || !string || !nativeIsFinite(n)) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + string += string; + } while (n); + + return result; + } + + /** + * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--foo-bar'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__foo_bar__'); + * // => 'Foo Bar' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1)); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The string to search. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = baseToString(string); + position = position == null + ? 0 + : nativeMin(position < 0 ? 0 : (+position || 0), string.length); + + return string.lastIndexOf(target, position) == position; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is provided it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options] The options object. + * @param {RegExp} [options.escape] The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate] The "evaluate" delimiter. + * @param {Object} [options.imports] An object to import into the template as free variables. + * @param {RegExp} [options.interpolate] The "interpolate" delimiter. + * @param {string} [options.sourceURL] The sourceURL of the template's compiled source. + * @param {string} [options.variable] The data object variable name. + * @param- {Object} [otherOptions] Enables the legacy `options` param signature. + * @returns {Function} Returns the compiled template function. + * @example + * + * // using the "interpolate" delimiter to create a compiled template + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // using the HTML "escape" delimiter to escape data property values + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': ' + +``` + +The library can also be installed through [bower][bower] + +```bash +$ bower install validator-js +``` + +### Validators + +- **contains(str, seed)** - check if the string contains the seed. +- **equals(str, comparison)** - check if the string matches the comparison. +- **isAfter(str [, date])** - check if the string is a date that's after the specified date (defaults to now). +- **isAlpha(str)** - check if the string contains only letters (a-zA-Z). +- **isAlphanumeric(str)** - check if the string contains only letters and numbers. +- **isAscii(str)** - check if the string contains ASCII chars only. +- **isBase64(str)** - check if a string is base64 encoded. +- **isBefore(str [, date])** - check if the string is a date that's before the specified date. +- **isBoolean(str)** - check if a string is a boolean. +- **isByteLength(str, min [, max])** - check if the string's length (in bytes) falls in a range. +- **isCreditCard(str)** - check if the string is a credit card. +- **isCurrency(str, options)** - check if the string is a valid currency amount. `options` is an object which defaults to `{symbol: '$', require_symbol: false, allow_space_after_symbol: false, symbol_after_digits: false, allow_negatives: true, parens_for_negatives: false, negative_sign_before_digits: false, negative_sign_after_digits: false, allow_negative_sign_placeholder: false, thousands_separator: ',', decimal_separator: '.', allow_space_after_digits: false }`. +- **isDate(str)** - check if the string is a date. +- **isDecimal(str)** - check if the string represents a decimal number, such as 0.1, .3, 1.1, 1.00003, 4.0, etc. +- **isDivisibleBy(str, number)** - check if the string is a number that's divisible by another. +- **isEmail(str [, options])** - check if the string is an email. `options` is an object which defaults to `{ allow_display_name: false, allow_utf8_local_part: true, require_tld: true }`. If `allow_display_name` is set to true, the validator will also match `Display Name `. If `allow_utf8_local_part` is set to false, the validator will not allow any non-English UTF8 character in email address' local part. If `require_tld` is set to false, e-mail addresses without having TLD in their domain will also be matched. +- **isFQDN(str [, options])** - check if the string is a fully qualified domain name (e.g. domain.com). `options` is an object which defaults to `{ require_tld: true, allow_underscores: false, allow_trailing_dot: false }`. +- **isFloat(str [, options])** - check if the string is a float. `options` is an object which can contain the keys `min` and/or `max` to validate the float is within boundaries (e.g. `{ min: 7.22, max: 9.55 }`). +- **isFullWidth(str)** - check if the string contains any full-width chars. +- **isHalfWidth(str)** - check if the string contains any half-width chars. +- **isHexColor(str)** - check if the string is a hexadecimal color. +- **isHexadecimal(str)** - check if the string is a hexadecimal number. +- **isIP(str [, version])** - check if the string is an IP (version 4 or 6). +- **isISBN(str [, version])** - check if the string is an ISBN (version 10 or 13). +- **isISIN(str)** - check if the string is an [ISIN][ISIN] (stock/security identifier). +- **isISO8601(str)** - check if the string is a valid [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date. +- **isIn(str, values)** - check if the string is in a array of allowed values. +- **isInt(str [, options])** - check if the string is an integer. `options` is an object which can contain the keys `min` and/or `max` to check the integer is within boundaries (e.g. `{ min: 10, max: 99 }`). +- **isJSON(str)** - check if the string is valid JSON (note: uses JSON.parse). +- **isLength(str, min [, max])** - check if the string's length falls in a range. Note: this function takes into account surrogate pairs. +- **isLowercase(str)** - check if the string is lowercase. +- **isMobilePhone(str, locale)** - check if the string is a mobile phone number, (locale is one of `['zh-CN', 'zh-TW', 'en-ZA', 'en-AU', 'en-HK', 'pt-PT', 'fr-FR', 'el-GR', 'en-GB', 'en-US', 'en-ZM', 'ru-RU', 'nb-NO', 'nn-NO']`). +- **isMongoId(str)** - check if the string is a valid hex-encoded representation of a [MongoDB ObjectId][mongoid]. +- **isMultibyte(str)** - check if the string contains one or more multibyte chars. +- **isNull(str)** - check if the string is null. +- **isNumeric(str)** - check if the string contains only numbers. +- **isSurrogatePair(str)** - check if the string contains any surrogate pairs chars. +- **isURL(str [, options])** - check if the string is an URL. `options` is an object which defaults to `{ protocols: ['http','https','ftp'], require_tld: true, require_protocol: false, require_valid_protocol: true, allow_underscores: false, host_whitelist: false, host_blacklist: false, allow_trailing_dot: false, allow_protocol_relative_urls: false }`. +- **isUUID(str [, version])** - check if the string is a UUID (version 3, 4 or 5). +- **isUppercase(str)** - check if the string is uppercase. +- **isVariableWidth(str)** - check if the string contains a mixture of full and half-width chars. +- **matches(str, pattern [, modifiers])** - check if string matches the pattern. Either `matches('foo', /foo/i)` or `matches('foo', 'foo', 'i')`. + +### Sanitizers + +- **blacklist(input, chars)** - remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `blacklist(input, '\\[\\]')`. +- **escape(input)** - replace `<`, `>`, `&`, `'`, `"` and `/` with HTML entities. +- **ltrim(input [, chars])** - trim characters from the left-side of the input. +- **normalizeEmail(email [, options])** - canonicalize an email address. `options` is an object which defaults to `{ lowercase: true }`. With `lowercase` set to `true`, the local part of the email address is lowercased for all domains; the hostname is always lowercased and the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail). Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and are stripped of tags (e.g. `some.one+tag@gmail.com` becomes `someone@gmail.com`) and all `@googlemail.com` addresses are normalized to `@gmail.com`. +- **rtrim(input [, chars])** - trim characters from the right-side of the input. +- **stripLow(input [, keep_new_lines])** - remove characters with a numerical value < 32 and 127, mostly control characters. If `keep_new_lines` is `true`, newline characters are preserved (`\n` and `\r`, hex `0xA` and `0xD`). Unicode-safe in JavaScript. +- **toBoolean(input [, strict])** - convert the input to a boolean. Everything except for `'0'`, `'false'` and `''` returns `true`. In strict mode only `'1'` and `'true'` return `true`. +- **toDate(input)** - convert the input to a date, or `null` if the input is not a date. +- **toFloat(input)** - convert the input to a float, or `NaN` if the input is not a float. +- **toInt(input [, radix])** - convert the input to an integer, or `NaN` if the input is not an integer. +- **toString(input)** - convert the input to a string. +- **trim(input [, chars])** - trim characters (whitespace by default) from both sides of the input. +- **whitelist(input, chars)** - remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will need to escape some chars, e.g. `whitelist(input, '\\[\\]')`. + +### XSS Sanitization + +XSS sanitization was removed from the library in [2d5d6999](https://github.com/chriso/validator.js/commit/2d5d6999541add350fb396ef02dc42ca3215049e). + +For an alternative, look at Yahoo's [xss-filters library](https://github.com/yahoo/xss-filters). + +### Strings only + +This library validates and sanitizes **strings** only. All input will be coerced to a string using the following rules + +- Call the `toString` property if available. +- Replace `null`, `undefined` or `NaN` with an empty string. +- Everything else is coerced with `input + ''`. + +### Extensions + +You can add your own validators using `validator.extend(name, fn)` + +```javascript +validator.extend('isWhitespace', function (str) { + return /^\s+$/.test(str); +}); +``` + +Note that the first argument will be automatically coerced to a string. + +```javascript +validator.isWhitespace(' \t\r\n'); +// => true + +validator.isWhitespace('foo bar'); +// => false +``` + +### Tests + +Tests require node v4.0+. + +- `make test` - run the test suite. +- `make test V=1` - run the test suite with added verbosity. +- `make test TEST=pattern` - run tests that match a pattern. +- `make coverage` - run a coverage analysis tool. +- `make lint` - run a lint tool. + +### License (MIT) + +``` +Copyright (c) 2015 Chris O'Hara + +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. +``` + +[downloads-image]: http://img.shields.io/npm/dm/validator.svg + +[npm-url]: https://npmjs.org/package/validator +[npm-image]: http://img.shields.io/npm/v/validator.svg + +[travis-url]: https://travis-ci.org/chriso/validator.js +[travis-image]: http://img.shields.io/travis/chriso/validator.js.svg + +[coveralls-url]: https://coveralls.io/r/chriso/validator.js +[coveralls-image]: http://img.shields.io/coveralls/chriso/validator.js/master.svg + +[amd]: http://requirejs.org/docs/whyamd.html +[bower]: http://bower.io/ + +[mongoid]: http://docs.mongodb.org/manual/reference/object-id/ +[ISIN]: https://en.wikipedia.org/wiki/International_Securities_Identification_Number diff --git a/node_modules/validator/bower.json b/node_modules/validator/bower.json new file mode 100644 index 0000000..99717c8 --- /dev/null +++ b/node_modules/validator/bower.json @@ -0,0 +1,19 @@ +{ + "name": "validator-js", + "main": "validator.js", + "homepage": "https://github.com/chriso/validator.js", + "authors": [ + "Chris O'Hara " + ], + "description": "String validation and sanitization", + "license": "MIT", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests", + "Makefile", + "package.json" + ] +} diff --git a/node_modules/validator/package.json b/node_modules/validator/package.json new file mode 100644 index 0000000..7a480c6 --- /dev/null +++ b/node_modules/validator/package.json @@ -0,0 +1,92 @@ +{ + "_args": [ + [ + "validator@4.2.x", + "/Users/akira/src/biomedjs/node_modules/express-validator" + ] + ], + "_from": "validator@>=4.2.0 <4.3.0", + "_id": "validator@4.2.1", + "_inCache": true, + "_installable": true, + "_location": "/validator", + "_nodeVersion": "4.2.1", + "_npmUser": { + "email": "cohara87@gmail.com", + "name": "cohara87" + }, + "_npmVersion": "2.14.7", + "_phantomChildren": {}, + "_requested": { + "name": "validator", + "raw": "validator@4.2.x", + "rawSpec": "4.2.x", + "scope": null, + "spec": ">=4.2.0 <4.3.0", + "type": "range" + }, + "_requiredBy": [ + "/express-validator" + ], + "_resolved": "https://registry.npmjs.org/validator/-/validator-4.2.1.tgz", + "_shasum": "c4a8316242e515cd784171986296f8f81fc2ab35", + "_shrinkwrap": null, + "_spec": "validator@4.2.x", + "_where": "/Users/akira/src/biomedjs/node_modules/express-validator", + "author": { + "email": "cohara87@gmail.com", + "name": "Chris O'Hara" + }, + "bugs": { + "url": "http://github.com/chriso/validator.js/issues" + }, + "dependencies": {}, + "description": "String validation and sanitization", + "devDependencies": { + "coveralls": "latest", + "istanbul": "latest", + "jshint": "latest", + "mocha": "latest", + "uglify-js": "latest" + }, + "directories": {}, + "dist": { + "shasum": "c4a8316242e515cd784171986296f8f81fc2ab35", + "tarball": "http://registry.npmjs.org/validator/-/validator-4.2.1.tgz" + }, + "engines": { + "node": ">= 0.10" + }, + "gitHead": "7b0c73d26decc20aa3bed3b7a15d09dc3d1b71ec", + "homepage": "http://github.com/chriso/validator.js", + "keywords": [ + "assert", + "sanitisation", + "sanitise", + "sanitization", + "sanitize", + "validate", + "validation", + "validator" + ], + "license": "MIT", + "main": "validator.js", + "maintainers": [ + { + "name": "cohara87", + "email": "cohara87@gmail.com" + } + ], + "name": "validator", + "optionalDependencies": {}, + "readme": "ERROR: No README data found!", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/chriso/validator.js.git" + }, + "scripts": { + "coveralls": "istanbul cover _mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | coveralls && rm -rf ./coverage", + "test": "node ./node_modules/.bin/_mocha --reporter spec" + }, + "version": "4.2.1" +} diff --git a/node_modules/validator/test/client-side.js b/node_modules/validator/test/client-side.js new file mode 100644 index 0000000..b33d389 --- /dev/null +++ b/node_modules/validator/test/client-side.js @@ -0,0 +1,26 @@ +var assert = require('assert') + , validator = require('../validator') + , min = require('../validator.min'); + +describe('Minified version', function () { + + it('should export the same things as the server-side version', function () { + for (var key in validator) { + assert.equal(typeof validator[key], typeof min[key], 'Minified version did not export ' + key); + } + }); + + it('should be up to date', function () { + assert.equal(min.version, validator.version, 'Minified version mismatch. Run `make min`'); + }); + + it('should validate strings', function () { + assert.equal(min.isEmail('foo@bar.com'), true); + assert.equal(min.isEmail('foo'), false); + }); + + it('should sanitize strings', function () { + assert.equal(min.toBoolean('1'), true); + }); + +}); diff --git a/node_modules/validator/test/exports.js b/node_modules/validator/test/exports.js new file mode 100644 index 0000000..befb70d --- /dev/null +++ b/node_modules/validator/test/exports.js @@ -0,0 +1,21 @@ +var assert = require('assert') + , validator = require('../validator'); + +describe('Exports', function () { + + it('should export validators', function () { + assert.equal(typeof validator.isEmail, 'function'); + assert.equal(typeof validator.isAlpha, 'function'); + }); + + it('should export sanitizers', function () { + assert.equal(typeof validator.toBoolean, 'function'); + assert.equal(typeof validator.toFloat, 'function'); + }); + + it('should export the version number', function () { + assert.equal(validator.version, require('../package.json').version, + 'Version number mismatch in "package.json" vs. "validator.js"'); + }); + +}); diff --git a/node_modules/validator/test/sanitizers.js b/node_modules/validator/test/sanitizers.js new file mode 100644 index 0000000..e24c9f8 --- /dev/null +++ b/node_modules/validator/test/sanitizers.js @@ -0,0 +1,223 @@ +var validator = require('../validator') + , format = require('util').format; + +function test(options) { + var args = options.args || []; + args.unshift(null); + Object.keys(options.expect).forEach(function (input) { + args[0] = input; + var result = validator[options.sanitizer].apply(validator, args) + , expected = options.expect[input]; + if (isNaN(result) && !result.length && isNaN(expected)) { + return; + } + if (result !== expected) { + var warning = format('validator.%s(%s) returned "%s" but should have returned "%s"', + options.sanitizer, args.join(', '), result, expected); + throw new Error(warning); + } + }); +} + +describe('Sanitizers', function () { + + it('should sanitize boolean strings', function () { + test({ + sanitizer: 'toBoolean' + , expect: { + '0': false + , '': false + , '1': true + , 'true': true + , 'foobar': true + , ' ': true + } + }); + test({ + sanitizer: 'toBoolean' + , args: [ true ] //strict + , expect: { + '0': false + , '': false + , '1': true + , 'true': true + , 'foobar': false + , ' ': false + } + }); + }); + + it('should trim whitespace', function () { + test({ + sanitizer: 'trim' + , expect: { ' \r\n\tfoo \r\n\t ': 'foo' } + }); + test({ + sanitizer: 'ltrim' + , expect: { ' \r\n\tfoo \r\n\t ': 'foo \r\n\t ' } + }); + test({ + sanitizer: 'rtrim' + , expect: { ' \r\n\tfoo \r\n\t ': ' \r\n\tfoo' } + }); + }); + + it('should trim custom characters', function () { + test({ + sanitizer: 'trim' + , args: [ '01' ] + , expect: { '010100201000': '2' } + }); + test({ + sanitizer: 'ltrim' + , args: [ '01' ] + , expect: { '010100201000': '201000' } + }); + test({ + sanitizer: 'rtrim' + , args: [ '01' ] + , expect: { '010100201000': '0101002' } + }); + }); + + it('should convert strings to integers', function () { + test({ + sanitizer: 'toInt' + , expect: { + '3': 3 + , ' 3 ': 3 + , '2.4': 2 + , 'foo': NaN + } + }); + test({ + sanitizer: 'toInt' + , args: [ 16 ] + , expect: { 'ff': 255 } + }); + }); + + it('should convert strings to floats', function () { + test({ + sanitizer: 'toFloat' + , expect: { + '2': 2.0 + , '2.': 2.0 + , '-2.5': -2.5 + , '.5': 0.5 + , 'foo': NaN + } + }); + }); + + it('should escape HTML', function () { + test({ + sanitizer: 'escape' + , expect: { + '': '<script> alert("xss&fun"); </script>' + , "": '<script> alert('xss&fun'); </script>' + , 'Backtick: `': 'Backtick: `' + } + }); + }); + + it('should remove control characters (<32 and 127)', function () { + // Check basic functionality + test({ + sanitizer: 'stripLow' + , expect: { + "foo\x00": "foo" + , "\x7Ffoo\x02": "foo" + , "\x01\x09": "" + , "foo\x0A\x0D": "foo" + } + }); + // Unicode safety + test({ + sanitizer: 'stripLow' + , expect: { + "perch\u00e9": "perch\u00e9" + , "\u20ac": "\u20ac" + , "\u2206\x0A": "\u2206" + , "\ud83d\ude04": "\ud83d\ude04" + } + }); + // Preserve newlines + test({ + sanitizer: 'stripLow' + , args: [ true ] //keep_new_lines + , expect: { + "foo\x0A\x0D": "foo\x0A\x0D" + , "\x03foo\x0A\x0D": "foo\x0A\x0D" + } + }); + }); + + + it('should sanitize a string based on a whitelist', function () { + test({ + sanitizer: 'whitelist' + , args: [ 'abc' ] + , expect: { + 'abcdef': 'abc' + , 'aaaaaaaaaabbbbbbbbbb': 'aaaaaaaaaabbbbbbbbbb' + , 'a1b2c3': 'abc' + , ' ': '' + } + }); + }); + + it('should sanitize a string based on a blacklist', function () { + test({ + sanitizer: 'blacklist' + , args: [ 'abc' ] + , expect: { + 'abcdef': 'def' + , 'aaaaaaaaaabbbbbbbbbb': '' + , 'a1b2c3': '123' + , ' ': ' ' + } + }); + }); + + it('should normalize an email based on domain', function () { + test({ + sanitizer: 'normalizeEmail' + , expect: { + 'test@me.com': 'test@me.com' + , 'some.name@gmail.com': 'somename@gmail.com' + , 'some.name@googleMail.com': 'somename@gmail.com' + , 'some.name+extension@gmail.com': 'somename@gmail.com' + , 'some.Name+extension@GoogleMail.com': 'somename@gmail.com' + , 'some.name.middleName+extension@gmail.com': 'somenamemiddlename@gmail.com' + , 'some.name.middleName+extension@GoogleMail.com': 'somenamemiddlename@gmail.com' + , 'some.name.midd.leNa.me.+extension@gmail.com': 'somenamemiddlename@gmail.com' + , 'some.name.midd.leNa.me.+extension@GoogleMail.com': 'somenamemiddlename@gmail.com' + , 'some.name+extension@unknown.com': 'some.name+extension@unknown.com' + , 'hans@m端ller.com': 'hans@m端ller.com' + , 'an invalid email address': false + , '': false + , '+extension@gmail.com': false + // some.name.midd..leNa...me...+extension@GoogleMail.com was removed from test cases because of a bug with validator.isEmail. See issue #258 + } + }); + test({ + sanitizer: 'normalizeEmail' + , args: [{lowercase: false}] + , expect: { + 'test@me.com': 'test@me.com' + , 'hans@m端ller.com': 'hans@m端ller.com' + , 'test@ME.COM': 'test@me.com' // Hostname is always lowercased + , 'TEST@me.com': 'TEST@me.com' + , 'TEST@ME.COM': 'TEST@me.com' + , 'blAH@x.com': 'blAH@x.com' + + // Domains that are known for being case-insensitive are always lowercased + , 'SOME.name@GMAIL.com': 'somename@gmail.com' + , 'SOME.name.middleName+extension@GoogleMail.com': 'somenamemiddlename@gmail.com' + , 'SOME.name.midd.leNa.me.+extension@gmail.com': 'somenamemiddlename@gmail.com' + } + }); + }); + +}); diff --git a/node_modules/validator/test/validators.js b/node_modules/validator/test/validators.js new file mode 100644 index 0000000..6750b19 --- /dev/null +++ b/node_modules/validator/test/validators.js @@ -0,0 +1,2342 @@ +var validator = require('../validator') + , format = require('util').format + , assert = require('assert') + , path = require('path') + , fs = require('fs') + , vm = require('vm'); + +var validator_js = fs.readFileSync(path.join(__dirname, '../validator.js')).toString(); + +function test(options) { + var args = options.args || []; + args.unshift(null); + if (options.valid) { + options.valid.forEach(function (valid) { + args[0] = valid; + if (validator[options.validator].apply(validator, args) !== true) { + var warning = format('validator.%s(%s) failed but should have passed', + options.validator, args.join(', ')); + throw new Error(warning); + } + }); + } + if (options.invalid) { + options.invalid.forEach(function (invalid) { + args[0] = invalid; + if (validator[options.validator].apply(validator, args) !== false) { + var warning = format('validator.%s(%s) passed but should have failed', + options.validator, args.join(', ')); + throw new Error(warning); + } + }); + } +} + +function repeat(str, count) { + var result = ''; + while (count--) { + result += str; + } + return result; +} + +describe('Validators', function () { + + it('should validate email addresses', function () { + test({ + validator: 'isEmail' + , valid: [ + 'foo@bar.com' + , 'x@x.au' + , 'foo@bar.com.au' + , 'foo+bar@bar.com' + , 'hans.m端ller@test.com' + , 'hans@m端ller.com' + , 'test|123@m端ller.com' + , 'test+ext@gmail.com' + , 'some.name.midd.leNa.me.+extension@GoogleMail.com' + , 'gmail...ignores...dots...@gmail.com' + , '"foobar"@example.com' + , '" foo m端ller "@example.com' + , '"foo\\@bar"@example.com' + , repeat('a', 64) + '@' + repeat('a', 252) + '.com' + ] + , invalid: [ + 'invalidemail@' + , 'invalid.com' + , '@invalid.com' + , 'foo@bar.com.' + , 'somename@gmail.com' + , 'foo@bar.co.uk.' + , 'z@co.c' + , 'gmailgmailgmailgmailgmail@gmail.com' + , repeat('a', 64) + '@' + repeat('a', 253) + '.com' + , repeat('a', 65) + '@' + repeat('a', 252) + '.com' + ] + }); + }); + + it('should validate email addresses without UTF8 characters in local part', function () { + test({ + validator: 'isEmail' + , args: [{ allow_utf8_local_part: false }] + , valid: [ + 'foo@bar.com' + , 'x@x.au' + , 'foo@bar.com.au' + , 'foo+bar@bar.com' + , 'hans@m端ller.com' + , 'test|123@m端ller.com' + , 'test+ext@gmail.com' + , 'some.name.midd.leNa.me.+extension@GoogleMail.com' + , '"foobar"@example.com' + , '"foo\\@bar"@example.com' + , '" foo bar "@example.com' + ] + , invalid: [ + 'invalidemail@' + , 'invalid.com' + , '@invalid.com' + , 'foo@bar.com.' + , 'foo@bar.co.uk.' + , 'somename@gmail.com' + , 'hans.m端ller@test.com' + , 'z@co.c' + ] + }); + }); + + it('should validate email addresses with display names', function () { + test({ + validator: 'isEmail' + , args: [{ allow_display_name: true }] + , valid: [ + 'foo@bar.com' + , 'x@x.au' + , 'foo@bar.com.au' + , 'foo+bar@bar.com' + , 'hans.m端ller@test.com' + , 'hans@m端ller.com' + , 'test|123@m端ller.com' + , 'test+ext@gmail.com' + , 'some.name.midd.leNa.me.+extension@GoogleMail.com' + , 'Some Name ' + , 'Some Name ' + , 'Some Name ' + , 'Some Name ' + , 'Some Name ' + , 'Some Name ' + , 'Some Name ' + , 'Some Name ' + , 'Some Name ' + , 'Some Middle Name ' + , 'Name ' + , 'Name' + ] + , invalid: [ + 'invalidemail@' + , 'invalid.com' + , '@invalid.com' + , 'foo@bar.com.' + , 'foo@bar.co.uk.' + , 'Some Name ' + , 'Some Name ' + , 'Some Name <@invalid.com>' + , 'Some Name ' + , 'Some Name ' + , 'Some Name foo@bar.co.uk.>' + , 'Some Name ' + , 'Name foo@bar.co.uk' + ] + }); + }); + + it('should validate URLs', function () { + test({ + validator: 'isURL' + , valid: [ + 'foobar.com' + , 'www.foobar.com' + , 'foobar.com/' + , 'valid.au' + , 'http://www.foobar.com/' + , 'http://www.foobar.com:23/' + , 'http://www.foobar.com:65535/' + , 'http://www.foobar.com:5/' + , 'https://www.foobar.com/' + , 'ftp://www.foobar.com/' + , 'http://www.foobar.com/~foobar' + , 'http://user:pass@www.foobar.com/' + , 'http://user:@www.foobar.com/' + , 'http://127.0.0.1/' + , 'http://10.0.0.0/' + , 'http://189.123.14.13/' + , 'http://duckduckgo.com/?q=%2F' + , 'http://foobar.com/t$-_.+!*\'(),' + , 'http://localhost:3000/' + , 'http://foobar.com/?foo=bar#baz=qux' + , 'http://foobar.com?foo=bar' + , 'http://foobar.com#baz=qux' + , 'http://www.xn--froschgrn-x9a.net/' + , 'http://xn--froschgrn-x9a.com/' + , 'http://foo--bar.com' + , 'http://høyfjellet.no' + , 'http://xn--j1aac5a4g.xn--j1amh' + , 'http://кулік.укр' + ] + , invalid: [ + 'xyz://foobar.com' + , 'invalid/' + , 'invalid.x' + , 'invalid.' + , '.com' + , 'http://com/' + , 'http://300.0.0.1/' + , 'mailto:foo@bar.com' + , 'rtmp://foobar.com' + , 'http://www.xn--.com/' + , 'http://xn--.com/' + , 'http://www.foobar.com:0/' + , 'http://www.foobar.com:70000/' + , 'http://www.foobar.com:99999/' + , 'http://www.-foobar.com/' + , 'http://www.foobar-.com/' + , 'http://www.foo---bar.com/' + , 'http://foobar/# lol' + , 'http://foobar/? lol' + , 'http://foobar/ lol/' + , 'http://lol @foobar.com/' + , 'http://lol:lol @foobar.com/' + , 'http://lol:lol:lol@foobar.com/' + , 'http://lol: @foobar.com/' + , 'http://www.foo_bar.com/' + , 'http://www.foobar.com/\t' + , 'http://\n@www.foobar.com/' + , '' + , 'http://foobar.com/' + new Array(2083).join('f') + , 'http://*.foo.com' + , '*.foo.com' + , '!.foo.com' + , 'http://example.com.' + , 'http://localhost:61500this is an invalid url!!!!' + , '////foobar.com' + , 'http:////foobar.com' + ] + }); + }); + + it('should validate URLs with custom protocols', function () { + test({ + validator: 'isURL' + , args: [{ + protocols: [ 'rtmp' ] + }] + , valid: [ + 'rtmp://foobar.com' + ] + , invalid: [ + 'http://foobar.com' + ] + }); + }); + + it('should validate URLs with any protocol', function () { + test({ + validator: 'isURL' + , args: [{ + require_valid_protocol: false + }] + , valid: [ + 'rtmp://foobar.com', + 'http://foobar.com', + 'test://foobar.com' + ] + , invalid: [ + 'mailto:test@example.com' + ] + }); + }); + + it('should validate URLs with underscores', function () { + test({ + validator: 'isURL' + , args: [{ + allow_underscores: true + }] + , valid: [ + 'http://foo_bar.com' + , 'http://pr.example_com.294.example.com/' + ] + , invalid: [ + 'http://foo__bar.com' + ] + }); + }); + + it('should validate URLs that do not have a TLD', function () { + test({ + validator: 'isURL' + , args: [{ + require_tld: false + }] + , valid: [ + 'http://foobar.com/' + , 'http://foobar/' + , 'foobar/' + , 'foobar' + ] + , invalid: [ + ] + }); + }); + + it('should validate URLs with a trailing dot option', function () { + test({ + validator: 'isURL' + , args: [{ + allow_trailing_dot: true + , require_tld: false + }] + , valid: [ + 'http://example.com.' + , 'foobar.' + ] + }); + }); + + it('should validate protocol relative URLs', function () { + test({ + validator: 'isURL' + , args: [{ + allow_protocol_relative_urls: true + }] + , valid: [ + '//foobar.com' + , 'http://foobar.com' + , 'foobar.com' + ] + , invalid: [ + '://foobar.com' + , '/foobar.com' + , '////foobar.com' + , 'http:////foobar.com' + ] + }); + }); + + it('should not validate protocol relative URLs when require protocol is true', function () { + test({ + validator: 'isURL' + , args: [{ + allow_protocol_relative_urls: true, + require_protocol: true + }] + , valid: [ + 'http://foobar.com' + ] + , invalid: [ + '//foobar.com' + , '://foobar.com' + , '/foobar.com' + , 'foobar.com' + ] + }); + }); + + it('should let users specify whether URLs require a protocol', function () { + test({ + validator: 'isURL' + , args: [{ + require_protocol: true + }] + , valid: [ + 'http://foobar.com/' + , 'http://localhost/' + ] + , invalid: [ + 'foobar.com' + , 'foobar' + ] + }); + }); + + it('should let users specify a host whitelist', function () { + test({ + validator: 'isURL' + , args: [{ + host_whitelist: ['foo.com', 'bar.com'] + }] + , valid: [ + 'http://bar.com/' + , 'http://foo.com/' + ] + , invalid: [ + 'http://foobar.com' + , 'http://foo.bar.com/' + , 'http://qux.com' + ] + }); + }); + + it('should let users specify a host blacklist', function () { + test({ + validator: 'isURL' + , args: [{ + host_blacklist: ['foo.com', 'bar.com'] + }] + , valid: [ + 'http://foobar.com' + , 'http://foo.bar.com/' + , 'http://qux.com' + ] + , invalid: [ + 'http://bar.com/' + , 'http://foo.com/' + ] + }); + }); + + it('should validate IP addresses', function () { + test({ + validator: 'isIP' + , valid: [ + '127.0.0.1' + , '0.0.0.0' + , '255.255.255.255' + , '1.2.3.4' + , '::1' + , '2001:db8:0000:1:1:1:1:1' + , '2001:41d0:2:a141::1' + , '::ffff:127.0.0.1' + , '::0000' + , '0000::' + , '1::' + , '1111:1:1:1:1:1:1:1' + , 'fe80::a6db:30ff:fe98:e946' + , '::' + , '::ffff:127.0.0.1' + , '0:0:0:0:0:ffff:127.0.0.1' + ] + , invalid: [ + 'abc' + , '256.0.0.0' + , '0.0.0.256' + , '26.0.0.256' + , '::banana' + , 'banana::' + , '::1banana' + , '::1::' + , '1:' + , ':1' + , ':1:1:1::2' + , '1:1:1:1:1:1:1:1:1:1:1:1:1:1:1:1' + , '::11111' + , '11111:1:1:1:1:1:1:1' + , '2001:db8:0000:1:1:1:1::1' + , '0:0:0:0:0:0:ffff:127.0.0.1' + , '0:0:0:0:ffff:127.0.0.1' + ] + }); + test({ + validator: 'isIP' + , args: [ 4 ] + , valid: [ + '127.0.0.1' + , '0.0.0.0' + , '255.255.255.255' + , '1.2.3.4' + ] + , invalid: [ + '::1' + , '2001:db8:0000:1:1:1:1:1' + , '::ffff:127.0.0.1' + ] + }); + test({ + validator: 'isIP' + , args: [ 6 ] + , valid: [ + '::1' + , '2001:db8:0000:1:1:1:1:1' + , '::ffff:127.0.0.1' + ] + , invalid: [ + '127.0.0.1' + , '0.0.0.0' + , '255.255.255.255' + , '1.2.3.4' + , '::ffff:287.0.0.1' + ] + }); + test({ + validator: 'isIP' + , args: [ 10 ] + , valid: [ + ] + , invalid: [ + '127.0.0.1' + , '0.0.0.0' + , '255.255.255.255' + , '1.2.3.4' + , '::1' + , '2001:db8:0000:1:1:1:1:1' + ] + }); + }); + + it('should validate FQDN', function () { + test({ + validator: 'isFQDN' + , valid: [ + 'domain.com' + , 'dom.plato' + , 'a.domain.co' + , 'foo--bar.com' + , 'xn--froschgrn-x9a.com' + , 'rebecca.blackfriday' + ] + , invalid: [ + 'abc' + , '256.0.0.0' + , '_.com' + , '*.some.com' + , 's!ome.com' + , 'domain.com/' + , '/more.com' + ] + }); + }); + it('should validate FQDN with trailing dot option', function() { + test({ + validator: 'isFQDN' + , args: [ + {allow_trailing_dot:true} + ] + , valid: [ + 'example.com.' + ] + }); + }); + + it('should validate alpha strings', function () { + test({ + validator: 'isAlpha' + , valid: [ + 'abc' + , 'ABC' + , 'FoObar' + ] + , invalid: [ + 'abc1' + , ' foo ' + , '' + ] + }); + }); + + it('should validate alphanumeric strings', function () { + test({ + validator: 'isAlphanumeric' + , valid: [ + 'abc123' + , 'ABC11' + ] + , invalid: [ + 'abc ' + , 'foo!!' + ] + }); + }); + + it('should validate numeric strings', function () { + test({ + validator: 'isNumeric' + , valid: [ + '123' + , '00123' + , '-00123' + , '0' + , '-0' + , '+123' + ] + , invalid: [ + '123.123' + , ' ' + , '.' + ] + }); + }); + + it('should validate decimal numbers', function () { + test({ + validator: 'isDecimal' + , valid: [ + '123' + , '00123' + , '-00123' + , '0' + , '-0' + , '+123' + , '0.01' + , '.1' + , '1.0' + , '-.25' + , '-0' + , '0.0000000000001' + ] + , invalid: [ + '....' + , ' ' + , '' + , '-' + , '+' + , '.' + , '0.1a' + , 'a' + , '\n' + ] + }); + }); + + it('should validate lowercase strings', function () { + test({ + validator: 'isLowercase' + , valid: [ + 'abc' + , 'abc123' + , 'this is lowercase.' + , 'tr竪s 端ber' + ] + , invalid: [ + 'fooBar' + , '123A' + ] + }); + }); + + it('should validate uppercase strings', function () { + test({ + validator: 'isUppercase' + , valid: [ + 'ABC' + , 'ABC123' + , 'ALL CAPS IS FUN.' + , ' .' + ] + , invalid: [ + 'fooBar' + , '123abc' + ] + }); + }); + + it('should validate integers', function () { + test({ + validator: 'isInt' + , valid: [ + '13' + , '123' + , '0' + , '123' + , '-0' + , '+1' + ] + , invalid: [ + '01' + , '-01' + , '000' + , '100e10' + , '123.123' + , ' ' + , '' + ] + }); + + test({ validator: 'isInt', args: [{ min: 10 }], valid: [15, 80, 99], invalid: [9, 6, 3.2, 'a'] } ); + test({ validator: 'isInt', args: [{ min: 10, max: 15 }], valid: [15, 11, 13], invalid: [9, 2, 17, 3.2, 33, 'a'] } ); + }); + + it('should validate floats', function () { + test({ + validator: 'isFloat' + , valid: [ + '123' + , '123.' + , '123.123' + , '-123.123' + , '-0.123' + , '+0.123' + , '0.123' + , '.0' + , '01.123' + , '-0.22250738585072011e-307' + ] + , invalid: [ + '-.123' + , ' ' + , '' + , '.' + , 'foo' + ] + }); + + test({ validator: 'isFloat', args: [{ min: 3.7 }], valid: [3.888, 3.92, 4.5, 50, 3.7, 3.71], invalid: [3.6, 3.69, 3, 1.5, 'a'] } ); + test({ validator: 'isFloat', args: [{ min: 0.1, max: 1.0 }], valid: [0.1, 1.0, 0.15, 0.33, 0.57, 0.7], invalid: [0, 0.0, 'a', 1.3, 0.05, 5] } ); + }); + + it('should validate hexadecimal strings', function () { + test({ + validator: 'isHexadecimal' + , valid: [ + 'deadBEEF' + , 'ff0044' + ] + , invalid: [ + 'abcdefg' + , '' + , '..' + ] + }); + }); + + it('should validate hexadecimal color strings', function () { + test({ + validator: 'isHexColor' + , valid: [ + '#ff0034' + , '#CCCCCC' + , 'fff' + , '#f00' + ] + , invalid: [ + '#ff' + , 'fff0' + , '#ff12FG' + ] + }); + }); + + it('should validate null strings', function () { + test({ + validator: 'isNull' + , valid: [ + '' + , NaN + , [] + , undefined + , null + ] + , invalid: [ + ' ' + , 'foo' + ] + }); + }); + + it('should validate strings against an expected value', function () { + test({ validator: 'equals', args: ['abc'], valid: ['abc'], invalid: ['Abc', '123'] }); + }); + + it('should validate strings contain another string', function () { + test({ validator: 'contains', args: ['foo'], valid: ['foo', 'foobar', 'bazfoo'], + invalid: ['bar', 'fobar'] }); + }); + + it('should validate strings against a pattern', function () { + test({ validator: 'matches', args: [/abc/], valid: ['abc', 'abcdef', '123abc'], + invalid: ['acb', 'Abc'] }); + test({ validator: 'matches', args: ['abc'], valid: ['abc', 'abcdef', '123abc'], + invalid: ['acb', 'Abc'] }); + test({ validator: 'matches', args: ['abc', 'i'], valid: ['abc', 'abcdef', '123abc', 'AbC'], + invalid: ['acb'] }); + }); + + it('should validate strings by length', function () { + test({ validator: 'isLength', args: [2], valid: ['abc', 'de', 'abcd'], invalid: [ '', 'a' ] }); + test({ validator: 'isLength', args: [2, 3], valid: ['abc', 'de'], invalid: [ '', 'a', 'abcd' ] }); + test({ validator: 'isLength', args: [2, 3], valid: ['干𩸽', '𠮷野家'], invalid: [ '', '𠀋', '千竈通り' ] }); + }); + + it('should validate strings by byte length', function () { + test({ validator: 'isByteLength', args: [2], valid: ['abc', 'de', 'abcd', 'gmail'], invalid: [ '', 'a' ] }); + test({ validator: 'isByteLength', args: [2, 3], valid: ['abc', 'de', 'g'], invalid: [ '', 'a', 'abcd', 'gm' ] }); + }); + + it('should validate UUIDs', function () { + test({ + validator: 'isUUID' + , valid: [ + 'A987FBC9-4BED-3078-CF07-9141BA07C9F3' + , 'A987FBC9-4BED-4078-8F07-9141BA07C9F3' + , 'A987FBC9-4BED-5078-AF07-9141BA07C9F3' + ] + , invalid: [ + '' + , 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3' + , 'A987FBC9-4BED-3078-CF07-9141BA07C9F3xxx' + , 'A987FBC94BED3078CF079141BA07C9F3' + , '934859' + , '987FBC9-4BED-3078-CF07A-9141BA07C9F3' + , 'AAAAAAAA-1111-1111-AAAG-111111111111' + ] + }); + test({ + validator: 'isUUID' + , args: [ 3 ] + , valid: [ + 'A987FBC9-4BED-3078-CF07-9141BA07C9F3' + ] + , invalid: [ + '' + , 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3' + , '934859' + , 'AAAAAAAA-1111-1111-AAAG-111111111111' + , 'A987FBC9-4BED-4078-8F07-9141BA07C9F3' + , 'A987FBC9-4BED-5078-AF07-9141BA07C9F3' + ] + }); + test({ + validator: 'isUUID' + , args: [ 4 ] + , valid: [ + '713ae7e3-cb32-45f9-adcb-7c4fa86b90c1' + , '625e63f3-58f5-40b7-83a1-a72ad31acffb' + , '57b73598-8764-4ad0-a76a-679bb6640eb1' + , '9c858901-8a57-4791-81fe-4c455b099bc9' + ] + , invalid: [ + '' + , 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3' + , '934859' + , 'AAAAAAAA-1111-1111-AAAG-111111111111' + , 'A987FBC9-4BED-5078-AF07-9141BA07C9F3' + , 'A987FBC9-4BED-3078-CF07-9141BA07C9F3' + ] + }); + test({ + validator: 'isUUID' + , args: [ 5 ] + , valid: [ + '987FBC97-4BED-5078-AF07-9141BA07C9F3' + , '987FBC97-4BED-5078-BF07-9141BA07C9F3' + , '987FBC97-4BED-5078-8F07-9141BA07C9F3' + , '987FBC97-4BED-5078-9F07-9141BA07C9F3' + ] + , invalid: [ + '' + , 'xxxA987FBC9-4BED-3078-CF07-9141BA07C9F3' + , '934859' + , 'AAAAAAAA-1111-1111-AAAG-111111111111' + , '9c858901-8a57-4791-81fe-4c455b099bc9' + , 'A987FBC9-4BED-3078-CF07-9141BA07C9F3' + ] + }); + }); + + it('should validate a string that is in another string or array', function () { + test({ validator: 'isIn', args: ['foobar'], valid: ['foo', 'bar', 'foobar', ''], + invalid: ['foobarbaz', 'barfoo'] }); + test({ validator: 'isIn', args: [['foo', 'bar']], valid: ['foo', 'bar'], + invalid: ['foobar', 'barfoo', ''] }); + test({ validator: 'isIn', args: [[1, 2, 3]], valid: ['1', '2', '3'], + invalid: ['4', ''] }); + test({ validator: 'isIn', invalid: ['foo', ''] }); + }); + + it('should validate a string that is in another object', function () { + test({ validator: 'isIn', args: [{'foo':1, 'bar':2, 'foobar':3}], valid: ['foo', 'bar', 'foobar'], + invalid: ['foobarbaz', 'barfoo', ''] }); + test({ validator: 'isIn', args: [{1:3, 2:0, 3:1}], valid: ['1', '2', '3'], + invalid: ['4', ''] }); + }); + + it('should validate dates', function () { + test({ + validator: 'isDate' + , valid: [ + '2011-08-04' + , '2011-09-30' + , '04. 08. 2011.' + , '08/04/2011' + , '08/31/2011' + , '2011.08.04' + , '2/29/24' + , '2-29-24' + , '4. 8. 2011. GMT' + , '2. 28. 2011. GMT' + , '2. 29. 2008. GMT' + , '2011-08-04 12:00' + , '2/22/23' + , '2-23-22' + , '12' + , '11/2/23 12:24' + , new Date() + , 'Mon Aug 17 2015 00:24:56 GMT-0500 (CDT)' + , '2/22/23 23:24:26' + // valid ISO 8601 dates below + , '2009-12T12:34' + , '2009' + , '2009-05-19' + , '2009-05-19' + , '2009-05' + , '2009-001' + , '2009-05-19' + , '2009-05-19 00:00' + , '2009-05-19 14:31' + , '2009-05-19 14:39:22' + , '2009-05-19T14:39Z' + , '2009-05-19 14:39:22-06:00' + , '2009-05-19 14:39:22+0600' + , '2009-05-19 14:39:22-01' + , '2015-10-20T00:53:09+08:00' + , '2015-10-20T00:53:09+09:00' + , '2015-10-20T00:53:09+10:00' + , '2015-10-20T00:53:09+11:00' + , '2015-10-20T00:53:09+12:00' + , '2007-04-06T00:00' + , '2010-02-18T16:23:48.5' + , '200905' + , '2009-' + , '2009-05-19 14:' + , '200912-01' + // RFC 2882 tests below borrowed from the timerep package in Hackage: + // https://hackage.haskell.org/package/timerep-1.0.3/docs/src/Data-Time-RFC2822.html + , 'Fri, 21 Nov 1997 09:55:06 -0600' + , 'Tue, 15 Nov 1994 12:45:26 GMT' + , 'Tue, 1 Jul 2003 10:52:37 +0200' + , 'Thu, 13 Feb 1969 23:32:54 -0330' + , 'Mon, 24 Nov 1997 14:22:01 -0800' + , 'Mon Sep 28 1964 00:05:49 GMT+1100 (AEDST)' + , 'Mon Sep 28 1964 00:05:49 +1100 (AEDST)' + , 'Mon Sep 28 1964 00:05:49 +1100' + , 'Mon Sep 28 1964 00:05:49 \nGMT\n+1100\n' + , 'Mon Sep 28 1964 00:05:49 \nGMT\n+1100\n(AEDST)' + , 'Thu, 13\n Feb\n 1969\n 23:32\n -0330' + , 'Thu, 13\n Feb\n 1969\n 23:32\n -0330 (Newfoundland Time)' + ,'24 Nov 1997 14:22:01 -0800' + // slight variations of the above with end-of-month + , 'Thu, 29\n Feb\n 1968\n 13:32\n -0330' + , 'Fri, 30 Nov 1997 09:55:06 -0600' + // more RFC 2882 tests borrowed from libgit2: + // https://github.com/libgit2/libgit2/blob/master/tests/date/rfc2822.c + , 'Wed, 10 Apr 2014 08:21:03 +0000' + , 'Wed, 9 Apr 2014 10:21:03 +0200' + , 'Wed, 9 Apr 2014 06:21:03 -0200' + , 'Wed, 9 Apr 2014 08:21:03 +0000' + ] + , invalid: [ + 'foo' + , '2011-foo-04' + , '2011-09-31' + , '2. 29. 1987. GMT' + , '2. 29. 2011. GMT' + , '2/29/25' + , '2-29-25' + , 'GMT' + //invalid ISO 8601 dates below + , '2009367' + , '2007-04-05T24:50' + , '2009-000' + , '2009-M511' + , '2009M511' + , '2009-05-19T14a39r' + , '2009-05-19T14:3924' + , '2009-0519' + , '2009-05-1914:39' + , '2009-05-19r14:39' + , '2009-05-19 14a39a22' + , '2009-05-19 14:39:22+06a00' + , '2009-05-19 146922.500' + , '2010-02-18T16.5:23.35:48' + , '2010-02-18T16:23.35:48' + , '2010-02-18T16:23.35:48.45' + , '2009-05-19 14.5.44' + , '2010-02-18T16:23.33.600' + , '2010-02-18T16,25:23:48,444' + , '2009-02-30 14:' + , '200912-32' + // hackage RFC2822 variants with invalid end-of-month + , 'Thu, 29\n Feb\n 1969\n 13:32\n -0330' + , 'Fri, 31 Nov 1997 09:55:06 -0600' + ] + }); + }); + + it('should validate dates against a start date', function () { + test({ validator: 'isAfter', args: ['2011-08-03'], + valid: [ '2011-08-04', new Date(2011, 8, 10) ], + invalid: [ '2010-07-02', '2011-08-03', new Date(0), 'foo'] }); + test({ validator: 'isAfter', + valid: [ '2100-08-04', new Date(Date.now() + 86400000) ], + invalid: [ '2010-07-02', new Date(0) ] }); + test({ validator: 'isAfter', args: ['2011-08-03'], + valid: [ '2015-09-17' ], + invalid: [ 'invalid date' ] }); + test({ validator: 'isAfter', args: ['invalid date'], + invalid: [ 'invalid date', '2015-09-17' ] }); + }); + + it('should validate dates against an end date', function () { + test({ validator: 'isBefore', args: ['08/04/2011'], + valid: [ '2010-07-02', '2010-08-04', new Date(0) ], + invalid: [ '08/04/2011', new Date(2011, 9, 10) ] }); + test({ validator: 'isBefore', args: [ new Date(2011, 7, 4) ], + valid: [ '2010-07-02', '2010-08-04', new Date(0) ], + invalid: [ '08/04/2011', new Date(2011, 9, 10) ] }); + test({ validator: 'isBefore', + valid: [ '2000-08-04', new Date(0), new Date(Date.now() - 86400000) ], + invalid: [ '2100-07-02', new Date(2017, 10, 10) ] }); + test({ validator: 'isBefore', args: ['2011-08-03'], + valid: [ '1999-12-31' ], + invalid: [ 'invalid date' ] }); + test({ validator: 'isBefore', args: ['invalid date'], + invalid: [ 'invalid date', '1999-12-31' ] }); + }); + + it('should validate that integer strings are divisible by a number', function () { + test({ + validator: 'isDivisibleBy' + , args: [ 2 ] + , valid: [ '2', '4', '100', '1000' ] + , invalid: [ + '1' + , '2.5' + , '101' + , 'foo' + , '' + ] + }); + }); + + it('should validate credit cards', function () { + test({ + validator: 'isCreditCard' + , valid: [ + '375556917985515' + , '36050234196908' + , '4716461583322103' + , '4716-2210-5188-5662' + , '4929 7226 5379 7141' + , '5398228707871527' + ] + , invalid: [ + 'foo' + , 'foo' + , '5398228707871528' + ] + }); + }); + + it('should validate ISINs', function () { + test({ + validator: 'isISIN' + , valid: [ + 'AU0000XVGZA3' + , 'DE000BAY0017' + , 'BE0003796134' + , 'SG1G55870362' + , 'GB0001411924' + , 'DE000WCH8881' + , 'PLLWBGD00016' + ] + , invalid: [ + 'DE000BAY0018' + , 'PLLWBGD00019' + , 'foo' + , '5398228707871528' + ] + }); + }); + + it('should validate ISBNs', function () { + test({ + validator: 'isISBN' + , args: [ 10 ] + , valid: [ + '3836221195', '3-8362-2119-5', '3 8362 2119 5' + , '1617290858', '1-61729-085-8', '1 61729 085-8' + , '0007269706', '0-00-726970-6', '0 00 726970 6' + , '3423214120', '3-423-21412-0', '3 423 21412 0' + , '340101319X', '3-401-01319-X', '3 401 01319 X' + ] + , invalid: [ + '3423214121', '3-423-21412-1', '3 423 21412 1' + , '978-3836221191', '9783836221191' + , '123456789a', 'foo', '' + ] + }); + test({ + validator: 'isISBN' + , args: [ 13 ] + , valid: [ + '9783836221191', '978-3-8362-2119-1', '978 3 8362 2119 1' + , '9783401013190', '978-3401013190', '978 3401013190' + , '9784873113685', '978-4-87311-368-5', '978 4 87311 368 5' + ] + , invalid: [ + '9783836221190', '978-3-8362-2119-0', '978 3 8362 2119 0' + , '3836221195', '3-8362-2119-5', '3 8362 2119 5' + , '01234567890ab', 'foo', '' + ] + }); + test({ + validator: 'isISBN' + , valid: [ + '340101319X' + , '9784873113685' + ] + , invalid: [ + '3423214121' + , '9783836221190' + ] + }); + test({ + validator: 'isISBN' + , args: [ 'foo' ] + , invalid: [ + '340101319X' + , '9784873113685' + ] + }); + }); + + it('should validate JSON', function () { + test({ + validator: 'isJSON' + , valid: [ + '{ "key": "value" }' + , '{}' + ] + , invalid: [ + '{ key: "value" }' + , { "key": "value" } + , { key: 'value' } + , '{ \'key\': \'value\' }' + , 'null' + , '1234' + , 'false' + , '"nope"' + ] + }); + }); + + it('should validate multibyte strings', function () { + test({ + validator: 'isMultibyte' + , valid: [ + 'ひらがな・カタカナ、.漢字' + , 'あいうえお foobar' + , 'test@example.com' + , '1234abcDExyz' + , 'カタカナ' + , '中文' + ] + , invalid: [ + 'abc' + , 'abc123' + , '<>@" *.' + ] + }); + }); + + it('should validate ascii strings', function () { + test({ + validator: 'isAscii' + , valid: [ + 'foobar' + , '0987654321' + , 'test@example.com' + , '1234abcDEF' + ] + , invalid: [ + 'foobar' + , 'xyz098' + , '123456' + , 'カタカナ' + ] + }); + }); + + it('should validate full-width strings', function () { + test({ + validator: 'isFullWidth' + , valid: [ + 'ひらがな・カタカナ、.漢字' + , '3ー0 a@com' + , 'Fカタカナ゙ᆲ' + , 'Good=Parts' + ] + , invalid: [ + 'abc' + , 'abc123' + , '!"#$%&()<>/+=-_? ~^|.,@`{}[]' + ] + }); + }); + + it('should validate half-width strings', function () { + test({ + validator: 'isHalfWidth' + , valid: [ + '!"#$%&()<>/+=-_? ~^|.,@`{}[]' + , 'l-btn_02--active' + , 'abc123い' + , 'カタカナ゙ᆲ←' + ] + , invalid: [ + 'あいうえお' + , '0011' + ] + }); + }); + + it('should validate variable-width strings', function () { + test({ + validator: 'isVariableWidth' + , valid: [ + 'ひらがなカタカナ漢字ABCDE' + , '3ー0123' + , 'Fカタカナ゙ᆲ' + , 'Good=Parts' + ] + , invalid: [ + 'abc' + , 'abc123' + , '!"#$%&()<>/+=-_? ~^|.,@`{}[]' + , 'ひらがな・カタカナ、.漢字' + , '123456' + , 'カタカナ゙ᆲ' + ] + }); + }); + + it('should validate surrogate pair strings', function () { + test({ + validator: 'isSurrogatePair' + , valid: [ + '𠮷野𠮷' + , '𩸽' + , 'ABC千𥧄1-2-3' + ] + , invalid: [ + '吉野竈' + , '鮪' + , 'ABC1-2-3' + ] + }); + }); + + it('should validate base64 strings', function () { + test({ + validator: 'isBase64' + , valid: [ + 'TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=' + , 'Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==' + , 'U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==' + , 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw'+ + 'UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye'+ + 'rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619'+ + 'FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx'+ + 'QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ'+ + 'Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ'+ + 'HQIDAQAB' + ] + , invalid: [ + '12345' + , '' + , 'Vml2YW11cyBmZXJtZtesting123' + ] + }); + for (var i = 0, str = '', encoded; i < 1000; i++) { + str += String.fromCharCode(Math.random() * 26 | 97); + encoded = new Buffer(str).toString('base64'); + if (!validator.isBase64(encoded)) { + var msg = format('validator.isBase64() failed with "%s"', encoded); + throw new Error(msg); + } + } + }); + + it('should validate hex-encoded MongoDB ObjectId', function () { + test({ + validator: 'isMongoId' + , valid: [ + '507f1f77bcf86cd799439011' + ] + , invalid: [ + '507f1f77bcf86cd7994390' + , '507f1f77bcf86cd79943901z' + , '' + , '507f1f77bcf86cd799439011 ' + ] + }); + }); + + it('should define the module using an AMD-compatible loader', function () { + var window = { + validator: null + , define: function (module) { + this.validator = module; + } + }; + window.define.amd = true; + + var sandbox = vm.createContext(window); + vm.runInContext(validator_js, sandbox); + assert.equal(window.validator.trim(' foobar '), 'foobar'); + }); + + it('should bind validator to the window if no module loaders are available', function () { + var window = {}; + var sandbox = vm.createContext(window); + vm.runInContext(validator_js, sandbox); + assert.equal(window.validator.trim(' foobar '), 'foobar'); + }); + + it('should validate mobile phone number', function () { + test({ + validator: 'isMobilePhone' + , valid: [ + '15323456787' + , '13523333233' + , '13898728332' + , '+086-13238234822' + , '08613487234567' + , '8617823492338' + , '86-17823492338' + ] + , invalid: [ + '12345' + , '' + , 'Vml2YW11cyBmZXJtZtesting123' + , '010-38238383' + ], + args: ['zh-CN'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '0987123456' + , '+886987123456' + , '886987123456' + , '+886-987123456' + , '886-987123456' + ] + , invalid: [ + '12345' + , '' + , 'Vml2YW11cyBmZXJtZtesting123' + , '0-987123456' + ], + args: ['zh-TW'] + }); + + test({ + validator: 'isMobilePhone' + , invalid: [ + '15323456787' + , '13523333233' + , '13898728332' + , '+086-13238234822' + , '08613487234567' + , '8617823492338' + , '86-17823492338' + ], + args: ['en'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '0821231234' + , '+27821231234' + , '27821231234' + ] + , invalid: [ + '082123' + , '08212312345' + , '21821231234' + , '+21821231234' + , '+0821231234' + ], + args: ['en-ZA'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '61404111222' + , '+61411222333' + , '0417123456' + ] + , invalid: [ + '082123' + , '08212312345' + , '21821231234' + , '+21821231234' + , '+0821231234' + , '04123456789' + ], + args: ['en-AU'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '91234567' + , '9123-4567' + , '61234567' + , '51234567' + , '+85291234567' + , '+852-91234567' + , '+852-9123-4567' + , '852-91234567' + ] + , invalid: [ + '999' + , '+852-912345678' + , '123456789' + , '+852-1234-56789' + ], + args: ['en-HK'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '0612457898' + , '+33612457898' + , '33612457898' + , '0712457898' + , '+33712457898' + , '33712457898' + ] + , invalid: [ + '061245789' + , '06124578980' + , '0112457898' + , '0212457898' + , '0312457898' + , '0412457898' + , '0512457898' + , '0812457898' + , '0912457898' + , '+34612457898' + , '+336124578980' + , '+3361245789' + ] + , args: ['fr-FR'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '2102323234' + , '+302646041461' + , '+306944848966' + , '6944848966' + ] + , invalid: [ + '120000000' + , '20000000000' + , '68129485729' + , '6589394827' + , '298RI89572' + ] + , args: ['el-GR'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '447789345856' + , '+447861235675' + , '07888814488' + ] + , invalid: [ + '67699567' + , '0773894868' + , '077389f8688' + , '+07888814488' + , '0152456999' + , '442073456754' + , '+443003434751' + , '05073456754' + , '08001123123' + ] + , args: ['en-GB'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '19876543210' + , '8005552222' + , '+15673628910' + ] + , invalid: [ + '564785' + , '0123456789' + , '1437439210' + , '8009112340' + , '+10345672645' + , '11435213543' + , '2436119753' + , '16532116190' + ] + , args: ['en-US'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '0956684590' + , '0966684590' + , '0976684590' + , '+260956684590' + , '+260966684590' + , '+260976684590' + ] + , invalid: [ + '12345' + , '' + , 'Vml2YW11cyBmZXJtZtesting123' + , '010-38238383' + , '966684590' + , '260976684590' + ], + args: ['en-ZM'] + }); + + test({ + validator: 'isMobilePhone' + , valid: [ + '+79676338855' + , '79676338855' + , '89676338855' + , '9676338855' + ] + , invalid: [ + '12345' + , '' + , 'Vml2YW11cyBmZXJtZtesting123' + , '010-38238383' + , '+9676338855' + , '19676338855' + , '6676338855' + , '+99676338855' + ], + args: ['ru-RU'] + }); + + var norwegian = { + valid: [ + '+4796338855' + , '+4746338855' + , '4796338855' + , '4746338855' + , '46338855' + , '96338855' + ] + , invalid: [ + '12345' + , '' + , 'Vml2YW11cyBmZXJtZtesting123' + , '+4676338855' + , '19676338855' + , '+4726338855' + , '4736338855' + , '66338855' + ]}; + test({ + validator: 'isMobilePhone' + , valid: norwegian.valid + , invalid: norwegian.invalid, + args: ['nb-NO'] + }); + test({ + validator: 'isMobilePhone' + , valid: norwegian.valid + , invalid: norwegian.invalid, + args: ['nn-NO'] + }); + }); + + it('should validate currency', function() { + test({ + validator: 'isCurrency' + , args: [ + {} + , '-$##,###.## (en-US, en-CA, en-AU, en-NZ, en-HK)' + ] + , valid: [ + '-$10,123.45' + , '$10,123.45' + , '$10123.45' + , '10,123.45' + , '10123.45' + , '10,123' + , '1,123,456' + , '1123456' + , '1.39' + , '.03' + , '0.10' + , '$0.10' + , '-$0.01' + , '-$.99' + , '$100,234,567.89' + , '$10,123' + , '10,123' + , '-10123' + ] + , invalid: [ + '1.234' + , '$1.1' + , '$ 32.50' + , '500$' + , '.0001' + , '$.001' + , '$0.001' + , '12,34.56' + , '123456,123,123456' + , '123,4' + , ',123' + , '$-,123' + , '$' + , '.' + , ',' + , '00' + , '$-' + , '$-,.' + , '-' + , '-$' + , '' + , '- $' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + { + require_symbol: true + } + , '-$##,###.## with $ required (en-US, en-CA, en-AU, en-NZ, en-HK)' + ] + , valid: [ + '-$10,123.45' + , '$10,123.45' + , '$10123.45' + , '$10,123.45' + , '$10,123' + , '$1,123,456' + , '$1123456' + , '$1.39' + , '$.03' + , '$0.10' + , '$0.10' + , '-$0.01' + , '-$.99' + , '$100,234,567.89' + , '$10,123' + , '-$10123' + ] + , invalid: [ + '1.234' + , '$1.234' + , '1.1' + , '$1.1' + , '$ 32.50' + , ' 32.50' + , '500' + , '10,123,456' + , '.0001' + , '$.001' + , '$0.001' + , '1,234.56' + , '123456,123,123456' + , '$123456,123,123456' + , '123.4' + , '$123.4' + , ',123' + , '$,123' + , '$-,123' + , '$' + , '.' + , '$.' + , ',' + , '$,' + , '00' + , '$00' + , '$-' + , '$-,.' + , '-' + , '-$' + , '' + , '$ ' + , '- $' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + { + symbol:'¥' + , negative_sign_before_digits:true + } + , '¥-##,###.## (zh-CN)' + ] + , valid: [ + '123,456.78' + , '-123,456.78' + , '¥6,954,231' + , '¥-6,954,231' + , '¥10.03' + , '¥-10.03' + , '10.03' + , '1.39' + , '.03' + , '0.10' + , '¥-10567.01' + , '¥0.01' + , '¥1,234,567.89' + , '¥10,123' + , '¥-10,123' + , '¥-10,123.45' + , '10,123' + , '10123' + , '¥-100' + ] + , invalid: [ + '1.234' + , '¥1.1' + , '5,00' + , '.0001' + , '¥.001' + , '¥0.001' + , '12,34.56' + , '123456,123,123456' + , '123 456' + , ',123' + , '¥-,123' + , '' + , ' ' + , '¥' + , '¥-' + , '¥-,.' + , '-' + , '- ¥' + , '-¥' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + { + symbol:'¥' + , allow_negatives: false + } + , '¥##,###.## with no negatives (zh-CN)' + ] + , valid: [ + '123,456.78' + , '¥6,954,231' + , '¥10.03' + , '10.03' + , '1.39' + , '.03' + , '0.10' + , '¥0.01' + , '¥1,234,567.89' + , '¥10,123' + , '10,123' + , '10123' + , '¥100' + ] + , invalid: [ + '1.234' + , '-123,456.78' + , '¥-6,954,231' + , '¥-10.03' + , '¥-10567.01' + , '¥1.1' + , '¥-10,123' + , '¥-10,123.45' + , '5,00' + , '¥-100' + , '.0001' + , '¥.001' + , '¥-.001' + , '¥0.001' + , '12,34.56' + , '123456,123,123456' + , '123 456' + , ',123' + , '¥-,123' + , '' + , ' ' + , '¥' + , '¥-' + , '¥-,.' + , '-' + , '- ¥' + , '-¥' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + { + symbol: 'R' + , negative_sign_before_digits: true + , thousands_separator: ' ' + , decimal_separator: ',' + , allow_negative_sign_placeholder: true + } + , 'R ## ###,## and R-10 123,25 (el-ZA)' + ] + , valid: [ + '123 456,78' + , '-10 123' + , 'R-10 123' + , 'R 6 954 231' + , 'R10,03' + , '10,03' + , '1,39' + , ',03' + , '0,10' + , 'R10567,01' + , 'R0,01' + , 'R1 234 567,89' + , 'R10 123' + , 'R 10 123' + , 'R 10123' + , 'R-10123' + , '10 123' + , '10123' + ] + , invalid: [ + '1,234' + , 'R -10123' + , 'R- 10123' + , 'R,1' + , ',0001' + , 'R,001' + , 'R0,001' + , '12 34,56' + , '123456 123 123456' + , ' 123' + , '- 123' + , '123 ' + , '' + , ' ' + , 'R' + , 'R- .1' + , 'R-' + , '-' + , '-R 10123' + , 'R00' + , 'R -' + , '-R' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + { + symbol: '€' + , thousands_separator: '.' + , decimal_separator: ',' + , allow_space_after_symbol: true + } + , '-€ ##.###,## (it-IT)' + ] + , valid: [ + '123.456,78' + , '-123.456,78' + , '€6.954.231' + , '-€6.954.231' + , '€ 896.954.231' + , '-€ 896.954.231' + , '16.954.231' + , '-16.954.231' + , '€10,03' + , '-€10,03' + , '10,03' + , '-10,03' + , '-1,39' + , ',03' + , '0,10' + , '-€10567,01' + , '-€ 10567,01' + , '€ 0,01' + , '€1.234.567,89' + , '€10.123' + , '10.123' + , '-€10.123' + , '€ 10.123' + , '€10.123' + , '€ 10123' + , '10.123' + , '-10123' + ] + , invalid: [ + '1,234' + , '€ 1,1' + , '50#,50' + , '123,@€ ' + , '€€500' + , ',0001' + , '€ ,001' + , '€0,001' + , '12.34,56' + , '123456.123.123456' + , '€123€' + , '' + , ' ' + , '€' + , ' €' + , '€ ' + , '€€' + , ' 123' + , '- 123' + , '.123' + , '-€.123' + , '123 ' + , '€-' + , '- €' + , '€ - ' + , '-' + , '- ' + , '-€' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + { + symbol: '€' + , thousands_separator: '.' + , symbol_after_digits: true + , decimal_separator: ',' + , allow_space_after_digits: true + } + , '-##.###,## € (el-GR)' + ] + , valid: [ + '123.456,78' + , '-123.456,78' + , '6.954.231 €' + , '-6.954.231 €' + , '896.954.231' + , '-896.954.231' + , '16.954.231' + , '-16.954.231' + , '10,03€' + , '-10,03€' + , '10,03' + , '-10,03' + , '1,39' + , ',03' + , '-,03' + , '-,03 €' + , '-,03€' + , '0,10' + , '10567,01€' + , '0,01 €' + , '1.234.567,89€' + , '10.123€' + , '10.123' + , '10.123€' + , '10.123 €' + , '10123 €' + , '10.123' + , '10123' + ] + , invalid: [ + '1,234' + , '1,1 €' + , ',0001' + , ',001 €' + , '0,001€' + , '12.34,56' + , '123456.123.123456' + , '€123€' + , '' + , ' ' + , '€' + , ' €' + , '€ ' + , ' 123' + , '- 123' + , '.123' + , '-.123€' + , '-.123 €' + , '123 ' + , '-€' + , '- €' + , '-' + , '- ' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + { + symbol: 'kr.' + , negative_sign_before_digits: true + , thousands_separator: '.' + , decimal_separator: ',' + , allow_space_after_symbol: true + } + , 'kr. -##.###,## (da-DK)' + ] + , valid: [ + '123.456,78' + , '-10.123' + , 'kr. -10.123' + , 'kr.-10.123' + , 'kr. 6.954.231' + , 'kr.10,03' + , 'kr. -10,03' + , '10,03' + , '1,39' + , ',03' + , '0,10' + , 'kr. 10567,01' + , 'kr. 0,01' + , 'kr. 1.234.567,89' + , 'kr. -1.234.567,89' + , '10.123' + , 'kr. 10.123' + , 'kr.10.123' + , '10123' + , '10.123' + , 'kr.-10123' + ] + , invalid: [ + '1,234' + , 'kr. -10123' + , 'kr.,1' + , ',0001' + , 'kr. ,001' + , 'kr.0,001' + , '12.34,56' + , '123456.123.123456' + , '.123' + , 'kr.-.123' + , 'kr. -.123' + , '- 123' + , '123 ' + , '' + , ' ' + , 'kr.' + , ' kr.' + , 'kr. ' + , 'kr.-' + , 'kr. -' + , 'kr. - ' + , ' - ' + , '-' + , '- kr.' + , '-kr.' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + { + symbol: 'kr.' + , allow_negatives: false + , negative_sign_before_digits: true + , thousands_separator: '.' + , decimal_separator: ',' + , allow_space_after_symbol: true + } + , 'kr. ##.###,## with no negatives (da-DK)' + ] + , valid: [ + '123.456,78' + , '10.123' + , 'kr. 10.123' + , 'kr.10.123' + , 'kr. 6.954.231' + , 'kr.10,03' + , 'kr. 10,03' + , '10,03' + , '1,39' + , ',03' + , '0,10' + , 'kr. 10567,01' + , 'kr. 0,01' + , 'kr. 1.234.567,89' + , 'kr.1.234.567,89' + , '10.123' + , 'kr. 10.123' + , 'kr.10.123' + , '10123' + , '10.123' + , 'kr.10123' + ] + , invalid: [ + '1,234' + , '-10.123' + , 'kr. -10.123' + , 'kr. -1.234.567,89' + , 'kr.-10123' + , 'kr. -10123' + , 'kr.-10.123' + , 'kr. -10,03' + , 'kr.,1' + , ',0001' + , 'kr. ,001' + , 'kr.0,001' + , '12.34,56' + , '123456.123.123456' + , '.123' + , 'kr.-.123' + , 'kr. -.123' + , '- 123' + , '123 ' + , '' + , ' ' + , 'kr.' + , ' kr.' + , 'kr. ' + , 'kr.-' + , 'kr. -' + , 'kr. - ' + , ' - ' + , '-' + , '- kr.' + , '-kr.' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + { + parens_for_negatives: true + } + , '($##,###.##) (en-US, en-HK)' + ] + , valid: [ + '1,234' + , '(1,234)' + , '($6,954,231)' + , '$10.03' + , '(10.03)' + , '($10.03)' + , '1.39' + , '.03' + , '(.03)' + , '($.03)' + , '0.10' + , '$10567.01' + , '($0.01)' + , '$1,234,567.89' + , '$10,123' + , '(10,123)' + , '10123' + ] + , invalid: [ + '1.234' + , '($1.1)' + , '-$1.10' + , '$ 32.50' + , '500$' + , '.0001' + , '$.001' + , '($0.001)' + , '12,34.56' + , '123456,123,123456' + , '( 123)' + , ',123' + , '$-,123' + , '' + , ' ' + , ' ' + , ' ' + , '$' + , '$ ' + , ' $' + , ' 123' + , '(123) ' + , '.' + , ',' + , '00' + , '$-' + , '$ - ' + , '$- ' + , ' - ' + , '-' + , '- $' + , '-$' + , '()' + , '( )' + , '( -)' + , '( - )' + , '( - )' + , '(-)' + , '(-$)' + ] + }); + + test({ + validator: 'isCurrency' + , args: [ + {allow_negatives: false} + , '$##,###.## with no negatives (en-US, en-CA, en-AU, en-HK)' + ] + , valid: [ + '$10,123.45' + , '$10123.45' + , '10,123.45' + , '10123.45' + , '10,123' + , '1,123,456' + , '1123456' + , '1.39' + , '.03' + , '0.10' + , '$0.10' + , '$100,234,567.89' + , '$10,123' + , '10,123' + ] + , invalid: [ + '1.234' + , '-1.234' + , '-10123' + , '-$0.01' + , '-$.99' + , '$1.1' + , '-$1.1' + , '$ 32.50' + , '500$' + , '.0001' + , '$.001' + , '$0.001' + , '12,34.56' + , '123456,123,123456' + , '-123456,123,123456' + , '123,4' + , ',123' + , '$-,123' + , '$' + , '.' + , ',' + , '00' + , '$-' + , '$-,.' + , '-' + , '-$' + , '' + , '- $' + , '-$10,123.45' + ] + }); + + test({ + validator: 'isBoolean' + , valid: [ + 'true' + , 'false' + , '0' + , '1' + ] + , invalid: [ + '1.0' + , '0.0' + , 'true ' + , 'False' + , 'True' + , 'yes' + ] + }); + }); + + it('should validate ISO 8601 dates', function () { + // from http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/ + test({ + validator: 'isISO8601' + , valid: [ + '2009-12T12:34' + , '2009' + , '2009-05-19' + , '2009-05-19' + , '20090519' + , '2009123' + , '2009-05' + , '2009-123' + , '2009-222' + , '2009-001' + , '2009-W01-1' + , '2009-W51-1' + , '2009-W511' + , '2009-W33' + , '2009W511' + , '2009-05-19' + , '2009-05-19 00:00' + , '2009-05-19 14' + , '2009-05-19 14:31' + , '2009-05-19 14:39:22' + , '2009-05-19T14:39Z' + , '2009-W21-2' + , '2009-W21-2T01:22' + , '2009-139' + , '2009-05-19 14:39:22-06:00' + , '2009-05-19 14:39:22+0600' + , '2009-05-19 14:39:22-01' + , '20090621T0545Z' + , '2007-04-06T00:00' + , '2007-04-05T24:00' + , '2010-02-18T16:23:48.5' + , '2010-02-18T16:23:48,444' + , '2010-02-18T16:23:48,3-06:00' + , '2010-02-18T16:23.4' + , '2010-02-18T16:23,25' + , '2010-02-18T16:23.33+0600' + , '2010-02-18T16.23334444' + , '2010-02-18T16,2283' + , '2009-05-19 143922.500' + , '2009-05-19 1439,55' + ] + , invalid: [ + '200905' + , '2009367' + , '2009-' + , '2007-04-05T24:50' + , '2009-000' + , '2009-M511' + , '2009M511' + , '2009-05-19T14a39r' + , '2009-05-19T14:3924' + , '2009-0519' + , '2009-05-1914:39' + , '2009-05-19 14:' + , '2009-05-19r14:39' + , '2009-05-19 14a39a22' + , '200912-01' + , '2009-05-19 14:39:22+06a00' + , '2009-05-19 146922.500' + , '2010-02-18T16.5:23.35:48' + , '2010-02-18T16:23.35:48' + , '2010-02-18T16:23.35:48.45' + , '2009-05-19 14.5.44' + , '2010-02-18T16:23.33.600' + , '2010-02-18T16,25:23:48,444' + ] + }); + }); +}); diff --git a/node_modules/validator/validator.js b/node_modules/validator/validator.js new file mode 100644 index 0000000..8dd43cc --- /dev/null +++ b/node_modules/validator/validator.js @@ -0,0 +1,863 @@ +/*! + * Copyright (c) 2015 Chris O'Hara + * + * 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 (name, definition) { + if (typeof exports !== 'undefined' && typeof module !== 'undefined') { + module.exports = definition(); + } else if (typeof define === 'function' && typeof define.amd === 'object') { + define(definition); + } else { + this[name] = definition(); + } +})('validator', function (validator) { + + 'use strict'; + + validator = { version: '4.2.1' }; + + var emailUserPart = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i; + var quotedEmailUser = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i; + + var emailUserUtf8Part = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i; + var quotedEmailUserUtf8 = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i; + + var displayName = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\s]*<(.+)>$/i; + + var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/; + + var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/; + + var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/ + , isbn13Maybe = /^(?:[0-9]{13})$/; + + var ipv4Maybe = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/ + , ipv6Block = /^[0-9A-F]{1,4}$/i; + + var uuid = { + '3': /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i + , '4': /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i + , '5': /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i + , all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i + }; + + var alpha = /^[A-Z]+$/i + , alphanumeric = /^[0-9A-Z]+$/i + , numeric = /^[-+]?[0-9]+$/ + , int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/ + , float = /^(?:[-+]?(?:[0-9]+))?(?:\.[0-9]*)?(?:[eE][\+\-]?(?:[0-9]+))?$/ + , hexadecimal = /^[0-9A-F]+$/i + , decimal = /^[-+]?([0-9]+|\.[0-9]+|[0-9]+\.[0-9]+)$/ + , hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{6})$/i; + + var ascii = /^[\x00-\x7F]+$/ + , multibyte = /[^\x00-\x7F]/ + , fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/ + , halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/; + + var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/; + + var base64 = /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i; + + var phones = { + 'zh-CN': /^(\+?0?86\-?)?1[345789]\d{9}$/, + 'zh-TW': /^(\+?886\-?|0)?9\d{8}$/, + 'en-ZA': /^(\+?27|0)\d{9}$/, + 'en-AU': /^(\+?61|0)4\d{8}$/, + 'en-HK': /^(\+?852\-?)?[569]\d{3}\-?\d{4}$/, + 'fr-FR': /^(\+?33|0)[67]\d{8}$/, + 'pt-PT': /^(\+351)?9[1236]\d{7}$/, + 'el-GR': /^(\+30)?((2\d{9})|(69\d{8}))$/, + 'en-GB': /^(\+?44|0)7\d{9}$/, + 'en-US': /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/, + 'en-ZM': /^(\+26)?09[567]\d{7}$/, + 'ru-RU': /^(\+?7|8)?9\d{9}$/, + 'nb-NO': /^(\+?47)?[49]\d{7}$/, + 'nn-NO': /^(\+?47)?[49]\d{7}$/ + }; + + // from http://goo.gl/0ejHHW + var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/; + + validator.extend = function (name, fn) { + validator[name] = function () { + var args = Array.prototype.slice.call(arguments); + args[0] = validator.toString(args[0]); + return fn.apply(validator, args); + }; + }; + + //Right before exporting the validator object, pass each of the builtins + //through extend() so that their first argument is coerced to a string + validator.init = function () { + for (var name in validator) { + if (typeof validator[name] !== 'function' || name === 'toString' || + name === 'toDate' || name === 'extend' || name === 'init') { + continue; + } + validator.extend(name, validator[name]); + } + }; + + validator.toString = function (input) { + if (typeof input === 'object' && input !== null && input.toString) { + input = input.toString(); + } else if (input === null || typeof input === 'undefined' || (isNaN(input) && !input.length)) { + input = ''; + } + return '' + input; + }; + + validator.toDate = function (date) { + if (Object.prototype.toString.call(date) === '[object Date]') { + return date; + } + date = Date.parse(date); + return !isNaN(date) ? new Date(date) : null; + }; + + validator.toFloat = function (str) { + return parseFloat(str); + }; + + validator.toInt = function (str, radix) { + return parseInt(str, radix || 10); + }; + + validator.toBoolean = function (str, strict) { + if (strict) { + return str === '1' || str === 'true'; + } + return str !== '0' && str !== 'false' && str !== ''; + }; + + validator.equals = function (str, comparison) { + return str === validator.toString(comparison); + }; + + validator.contains = function (str, elem) { + return str.indexOf(validator.toString(elem)) >= 0; + }; + + validator.matches = function (str, pattern, modifiers) { + if (Object.prototype.toString.call(pattern) !== '[object RegExp]') { + pattern = new RegExp(pattern, modifiers); + } + return pattern.test(str); + }; + + var default_email_options = { + allow_display_name: false, + allow_utf8_local_part: true, + require_tld: true + }; + + validator.isEmail = function (str, options) { + options = merge(options, default_email_options); + + if (options.allow_display_name) { + var display_email = str.match(displayName); + if (display_email) { + str = display_email[1]; + } + } + + var parts = str.split('@') + , domain = parts.pop() + , user = parts.join('@'); + + var lower_domain = domain.toLowerCase(); + if (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com') { + user = user.replace(/\./g, '').toLowerCase(); + } + + if (!validator.isByteLength(user, 0, 64) || + !validator.isByteLength(domain, 0, 256)) { + return false; + } + + if (!validator.isFQDN(domain, {require_tld: options.require_tld})) { + return false; + } + + if (user[0] === '"') { + user = user.slice(1, user.length - 1); + return options.allow_utf8_local_part ? + quotedEmailUserUtf8.test(user) : + quotedEmailUser.test(user); + } + + var pattern = options.allow_utf8_local_part ? + emailUserUtf8Part : emailUserPart; + + var user_parts = user.split('.'); + for (var i = 0; i < user_parts.length; i++) { + if (!pattern.test(user_parts[i])) { + return false; + } + } + + return true; + }; + + var default_url_options = { + protocols: [ 'http', 'https', 'ftp' ] + , require_tld: true + , require_protocol: false + , require_valid_protocol: true + , allow_underscores: false + , allow_trailing_dot: false + , allow_protocol_relative_urls: false + }; + + validator.isURL = function (url, options) { + if (!url || url.length >= 2083 || /\s/.test(url)) { + return false; + } + if (url.indexOf('mailto:') === 0) { + return false; + } + options = merge(options, default_url_options); + var protocol, auth, host, hostname, port, + port_str, split; + split = url.split('://'); + if (split.length > 1) { + protocol = split.shift(); + if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) { + return false; + } + } else if (options.require_protocol) { + return false; + } else if (options.allow_protocol_relative_urls && url.substr(0, 2) === '//') { + split[0] = url.substr(2); + } + url = split.join('://'); + split = url.split('#'); + url = split.shift(); + + split = url.split('?'); + url = split.shift(); + + split = url.split('/'); + url = split.shift(); + split = url.split('@'); + if (split.length > 1) { + auth = split.shift(); + if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) { + return false; + } + } + hostname = split.join('@'); + split = hostname.split(':'); + host = split.shift(); + if (split.length) { + port_str = split.join(':'); + port = parseInt(port_str, 10); + if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) { + return false; + } + } + if (!validator.isIP(host) && !validator.isFQDN(host, options) && + host !== 'localhost') { + return false; + } + if (options.host_whitelist && + options.host_whitelist.indexOf(host) === -1) { + return false; + } + if (options.host_blacklist && + options.host_blacklist.indexOf(host) !== -1) { + return false; + } + return true; + }; + + validator.isIP = function (str, version) { + version = validator.toString(version); + if (!version) { + return validator.isIP(str, 4) || validator.isIP(str, 6); + } else if (version === '4') { + if (!ipv4Maybe.test(str)) { + return false; + } + var parts = str.split('.').sort(function (a, b) { + return a - b; + }); + return parts[3] <= 255; + } else if (version === '6') { + var blocks = str.split(':'); + var foundOmissionBlock = false; // marker to indicate :: + + // At least some OS accept the last 32 bits of an IPv6 address + // (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says + // that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses, + // and '::a.b.c.d' is deprecated, but also valid. + var foundIPv4TransitionBlock = validator.isIP(blocks[blocks.length - 1], 4); + var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8; + + if (blocks.length > expectedNumberOfBlocks) + return false; + + // initial or final :: + if (str === '::') { + return true; + } else if (str.substr(0, 2) === '::') { + blocks.shift(); + blocks.shift(); + foundOmissionBlock = true; + } else if (str.substr(str.length - 2) === '::') { + blocks.pop(); + blocks.pop(); + foundOmissionBlock = true; + } + + for (var i = 0; i < blocks.length; ++i) { + // test for a :: which can not be at the string start/end + // since those cases have been handled above + if (blocks[i] === '' && i > 0 && i < blocks.length -1) { + if (foundOmissionBlock) + return false; // multiple :: in address + foundOmissionBlock = true; + } else if (foundIPv4TransitionBlock && i == blocks.length - 1) { + // it has been checked before that the last + // block is a valid IPv4 address + } else if (!ipv6Block.test(blocks[i])) { + return false; + } + } + + if (foundOmissionBlock) { + return blocks.length >= 1; + } else { + return blocks.length === expectedNumberOfBlocks; + } + } + return false; + }; + + var default_fqdn_options = { + require_tld: true + , allow_underscores: false + , allow_trailing_dot: false + }; + + validator.isFQDN = function (str, options) { + options = merge(options, default_fqdn_options); + + /* Remove the optional trailing dot before checking validity */ + if (options.allow_trailing_dot && str[str.length - 1] === '.') { + str = str.substring(0, str.length - 1); + } + var parts = str.split('.'); + if (options.require_tld) { + var tld = parts.pop(); + if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) { + return false; + } + } + for (var part, i = 0; i < parts.length; i++) { + part = parts[i]; + if (options.allow_underscores) { + if (part.indexOf('__') >= 0) { + return false; + } + part = part.replace(/_/g, ''); + } + if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) { + return false; + } + if (/[\uff01-\uff5e]/.test(part)) { + // disallow full-width chars + return false; + } + if (part[0] === '-' || part[part.length - 1] === '-' || + part.indexOf('---') >= 0) { + return false; + } + } + return true; + }; + + validator.isBoolean = function(str) { + return (['true', 'false', '1', '0'].indexOf(str) >= 0); + }; + + validator.isAlpha = function (str) { + return alpha.test(str); + }; + + validator.isAlphanumeric = function (str) { + return alphanumeric.test(str); + }; + + validator.isNumeric = function (str) { + return numeric.test(str); + }; + + validator.isDecimal = function (str) { + return str !== '' && decimal.test(str); + }; + + validator.isHexadecimal = function (str) { + return hexadecimal.test(str); + }; + + validator.isHexColor = function (str) { + return hexcolor.test(str); + }; + + validator.isLowercase = function (str) { + return str === str.toLowerCase(); + }; + + validator.isUppercase = function (str) { + return str === str.toUpperCase(); + }; + + validator.isInt = function (str, options) { + options = options || {}; + return int.test(str) && (!options.hasOwnProperty('min') || str >= options.min) && (!options.hasOwnProperty('max') || str <= options.max); + }; + + validator.isFloat = function (str, options) { + options = options || {}; + if (str === '' || str === '.') { + return false; + } + return float.test(str) && (!options.hasOwnProperty('min') || str >= options.min) && (!options.hasOwnProperty('max') || str <= options.max); + }; + + validator.isDivisibleBy = function (str, num) { + return validator.toFloat(str) % validator.toInt(num) === 0; + }; + + validator.isNull = function (str) { + return str.length === 0; + }; + + validator.isLength = function (str, min, max) { + var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []; + var len = str.length - surrogatePairs.length; + return len >= min && (typeof max === 'undefined' || len <= max); + }; + + validator.isByteLength = function (str, min, max) { + var len = encodeURI(str).split(/%..|./).length - 1; + return len >= min && (typeof max === 'undefined' || len <= max); + }; + + validator.isUUID = function (str, version) { + var pattern = uuid[version ? version : 'all']; + return pattern && pattern.test(str); + }; + + function getTimezoneOffset(str) { + var iso8601Parts = str.match(iso8601) + , timezone, sign, hours, minutes; + if (!iso8601Parts) { + str = str.toLowerCase(); + timezone = str.match(/(?:\s|gmt\s*)(-|\+)(\d{1,4})(\s|$)/); + if (!timezone) { + return str.indexOf('gmt') !== -1 ? 0 : null; + } + sign = timezone[1]; + var offset = timezone[2]; + if (offset.length === 3) { + offset = '0' + offset; + } + if (offset.length <= 2) { + hours = 0; + minutes = parseInt(offset); + } else { + hours = parseInt(offset.slice(0, 2)); + minutes = parseInt(offset.slice(2, 4)); + } + } else { + timezone = iso8601Parts[21]; + if (!timezone || timezone === 'z' || timezone === 'Z') { + return 0; + } + sign = iso8601Parts[22]; + if (timezone.indexOf(':') !== -1) { + hours = parseInt(iso8601Parts[23]); + minutes = parseInt(iso8601Parts[24]); + } else { + hours = 0; + minutes = parseInt(iso8601Parts[23]); + } + } + return (hours * 60 + minutes) * (sign === '-' ? 1 : -1); + } + + validator.isDate = function (str) { + var normalizedDate = new Date(Date.parse(str)); + if (isNaN(normalizedDate)) { + return false; + } + // normalizedDate is in the user's timezone. Apply the input + // timezone offset to the date so that the year and day match + // the input + var timezoneOffset = getTimezoneOffset(str); + if (timezoneOffset !== null) { + var timezoneDifference = normalizedDate.getTimezoneOffset() - + timezoneOffset; + normalizedDate = new Date(normalizedDate.getTime() + + 60000 * timezoneDifference); + } + var day = String(normalizedDate.getDate()); + var dayOrYear, dayOrYearMatches, year; + //check for valid double digits that could be late days + //check for all matches since a string like '12/23' is a valid date + //ignore everything with nearby colons + dayOrYearMatches = str.match(/(^|[^:\d])[23]\d([^:\d]|$)/g); + if (!dayOrYearMatches) { + return true; + } + dayOrYear = dayOrYearMatches.map(function(digitString) { + return digitString.match(/\d+/g)[0]; + }).join('/'); + year = String(normalizedDate.getFullYear()).slice(-2); + if (dayOrYear === day || dayOrYear === year) { + return true; + } else if ((dayOrYear === (day + '/' + year)) || (dayOrYear === (year + '/' + day))) { + return true; + } + return false; + }; + + validator.isAfter = function (str, date) { + var comparison = validator.toDate(date || new Date()) + , original = validator.toDate(str); + return !!(original && comparison && original > comparison); + }; + + validator.isBefore = function (str, date) { + var comparison = validator.toDate(date || new Date()) + , original = validator.toDate(str); + return !!(original && comparison && original < comparison); + }; + + validator.isIn = function (str, options) { + var i; + if (Object.prototype.toString.call(options) === '[object Array]') { + var array = []; + for (i in options) { + array[i] = validator.toString(options[i]); + } + return array.indexOf(str) >= 0; + } else if (typeof options === 'object') { + return options.hasOwnProperty(str); + } else if (options && typeof options.indexOf === 'function') { + return options.indexOf(str) >= 0; + } + return false; + }; + + validator.isCreditCard = function (str) { + var sanitized = str.replace(/[^0-9]+/g, ''); + if (!creditCard.test(sanitized)) { + return false; + } + var sum = 0, digit, tmpNum, shouldDouble; + for (var i = sanitized.length - 1; i >= 0; i--) { + digit = sanitized.substring(i, (i + 1)); + tmpNum = parseInt(digit, 10); + if (shouldDouble) { + tmpNum *= 2; + if (tmpNum >= 10) { + sum += ((tmpNum % 10) + 1); + } else { + sum += tmpNum; + } + } else { + sum += tmpNum; + } + shouldDouble = !shouldDouble; + } + return !!((sum % 10) === 0 ? sanitized : false); + }; + + validator.isISIN = function (str) { + if (!isin.test(str)) { + return false; + } + + var checksumStr = str.replace(/[A-Z]/g, function(character) { + return parseInt(character, 36); + }); + + var sum = 0, digit, tmpNum, shouldDouble = true; + for (var i = checksumStr.length - 2; i >= 0; i--) { + digit = checksumStr.substring(i, (i + 1)); + tmpNum = parseInt(digit, 10); + if (shouldDouble) { + tmpNum *= 2; + if (tmpNum >= 10) { + sum += tmpNum + 1; + } else { + sum += tmpNum; + } + } else { + sum += tmpNum; + } + shouldDouble = !shouldDouble; + } + + return parseInt(str.substr(str.length - 1), 10) === (10000 - sum) % 10; + }; + + validator.isISBN = function (str, version) { + version = validator.toString(version); + if (!version) { + return validator.isISBN(str, 10) || validator.isISBN(str, 13); + } + var sanitized = str.replace(/[\s-]+/g, '') + , checksum = 0, i; + if (version === '10') { + if (!isbn10Maybe.test(sanitized)) { + return false; + } + for (i = 0; i < 9; i++) { + checksum += (i + 1) * sanitized.charAt(i); + } + if (sanitized.charAt(9) === 'X') { + checksum += 10 * 10; + } else { + checksum += 10 * sanitized.charAt(9); + } + if ((checksum % 11) === 0) { + return !!sanitized; + } + } else if (version === '13') { + if (!isbn13Maybe.test(sanitized)) { + return false; + } + var factor = [ 1, 3 ]; + for (i = 0; i < 12; i++) { + checksum += factor[i % 2] * sanitized.charAt(i); + } + if (sanitized.charAt(12) - ((10 - (checksum % 10)) % 10) === 0) { + return !!sanitized; + } + } + return false; + }; + + validator.isMobilePhone = function(str, locale) { + if (locale in phones) { + return phones[locale].test(str); + } + return false; + }; + + var default_currency_options = { + symbol: '$' + , require_symbol: false + , allow_space_after_symbol: false + , symbol_after_digits: false + , allow_negatives: true + , parens_for_negatives: false + , negative_sign_before_digits: false + , negative_sign_after_digits: false + , allow_negative_sign_placeholder: false + , thousands_separator: ',' + , decimal_separator: '.' + , allow_space_after_digits: false + }; + + validator.isCurrency = function (str, options) { + options = merge(options, default_currency_options); + + return currencyRegex(options).test(str); + }; + + validator.isJSON = function (str) { + try { + var obj = JSON.parse(str); + return !!obj && typeof obj === 'object'; + } catch (e) {} + return false; + }; + + validator.isMultibyte = function (str) { + return multibyte.test(str); + }; + + validator.isAscii = function (str) { + return ascii.test(str); + }; + + validator.isFullWidth = function (str) { + return fullWidth.test(str); + }; + + validator.isHalfWidth = function (str) { + return halfWidth.test(str); + }; + + validator.isVariableWidth = function (str) { + return fullWidth.test(str) && halfWidth.test(str); + }; + + validator.isSurrogatePair = function (str) { + return surrogatePair.test(str); + }; + + validator.isBase64 = function (str) { + return base64.test(str); + }; + + validator.isMongoId = function (str) { + return validator.isHexadecimal(str) && str.length === 24; + }; + + validator.isISO8601 = function (str) { + return iso8601.test(str); + }; + + validator.ltrim = function (str, chars) { + var pattern = chars ? new RegExp('^[' + chars + ']+', 'g') : /^\s+/g; + return str.replace(pattern, ''); + }; + + validator.rtrim = function (str, chars) { + var pattern = chars ? new RegExp('[' + chars + ']+$', 'g') : /\s+$/g; + return str.replace(pattern, ''); + }; + + validator.trim = function (str, chars) { + var pattern = chars ? new RegExp('^[' + chars + ']+|[' + chars + ']+$', 'g') : /^\s+|\s+$/g; + return str.replace(pattern, ''); + }; + + validator.escape = function (str) { + return (str.replace(/&/g, '&') + .replace(/"/g, '"') + .replace(/'/g, ''') + .replace(//g, '>') + .replace(/\//g, '/') + .replace(/\`/g, '`')); + }; + + validator.stripLow = function (str, keep_new_lines) { + var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F'; + return validator.blacklist(str, chars); + }; + + validator.whitelist = function (str, chars) { + return str.replace(new RegExp('[^' + chars + ']+', 'g'), ''); + }; + + validator.blacklist = function (str, chars) { + return str.replace(new RegExp('[' + chars + ']+', 'g'), ''); + }; + + var default_normalize_email_options = { + lowercase: true + }; + + validator.normalizeEmail = function (email, options) { + options = merge(options, default_normalize_email_options); + if (!validator.isEmail(email)) { + return false; + } + var parts = email.split('@', 2); + parts[1] = parts[1].toLowerCase(); + if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') { + parts[0] = parts[0].toLowerCase().replace(/\./g, ''); + if (parts[0][0] === '+') { + return false; + } + parts[0] = parts[0].split('+')[0]; + parts[1] = 'gmail.com'; + } else if (options.lowercase) { + parts[0] = parts[0].toLowerCase(); + } + return parts.join('@'); + }; + + function merge(obj, defaults) { + obj = obj || {}; + for (var key in defaults) { + if (typeof obj[key] === 'undefined') { + obj[key] = defaults[key]; + } + } + return obj; + } + + function currencyRegex(options) { + var symbol = '(\\' + options.symbol.replace(/\./g, '\\.') + ')' + (options.require_symbol ? '' : '?') + , negative = '-?' + , whole_dollar_amount_without_sep = '[1-9]\\d*' + , whole_dollar_amount_with_sep = '[1-9]\\d{0,2}(\\' + options.thousands_separator + '\\d{3})*' + , valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep] + , whole_dollar_amount = '(' + valid_whole_dollar_amounts.join('|') + ')?' + , decimal_amount = '(\\' + options.decimal_separator + '\\d{2})?'; + var pattern = whole_dollar_amount + decimal_amount; + // default is negative sign before symbol, but there are two other options (besides parens) + if (options.allow_negatives && !options.parens_for_negatives) { + if (options.negative_sign_after_digits) { + pattern += negative; + } + else if (options.negative_sign_before_digits) { + pattern = negative + pattern; + } + } + // South African Rand, for example, uses R 123 (space) and R-123 (no space) + if (options.allow_negative_sign_placeholder) { + pattern = '( (?!\\-))?' + pattern; + } + else if (options.allow_space_after_symbol) { + pattern = ' ?' + pattern; + } + else if (options.allow_space_after_digits) { + pattern += '( (?!$))?'; + } + if (options.symbol_after_digits) { + pattern += symbol; + } else { + pattern = symbol + pattern; + } + if (options.allow_negatives) { + if (options.parens_for_negatives) { + pattern = '(\\(' + pattern + '\\)|' + pattern + ')'; + } + else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) { + pattern = negative + pattern; + } + } + return new RegExp( + '^' + + // ensure there's a dollar and/or decimal amount, and that it doesn't start with a space or a negative sign followed by a space + '(?!-? )(?=.*\\d)' + + pattern + + '$' + ); + } + + validator.init(); + + return validator; + +}); diff --git a/node_modules/validator/validator.min.js b/node_modules/validator/validator.min.js new file mode 100644 index 0000000..1eb9ca9 --- /dev/null +++ b/node_modules/validator/validator.min.js @@ -0,0 +1,23 @@ +/*! + * Copyright (c) 2015 Chris O'Hara + * + * 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(t,e){"undefined"!=typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&"object"==typeof define.amd?define(e):this[t]=e()}("validator",function(t){"use strict";function e(t){var e,r,n,i,o=t.match(C);if(o){if(e=o[21],!e||"z"===e||"Z"===e)return 0;r=o[22],-1!==e.indexOf(":")?(n=parseInt(o[23]),i=parseInt(o[24])):(n=0,i=parseInt(o[23]))}else{if(t=t.toLowerCase(),e=t.match(/(?:\s|gmt\s*)(-|\+)(\d{1,4})(\s|$)/),!e)return-1!==t.indexOf("gmt")?0:null;r=e[1];var u=e[2];3===u.length&&(u="0"+u),u.length<=2?(n=0,i=parseInt(u)):(n=parseInt(u.slice(0,2)),i=parseInt(u.slice(2,4)))}return(60*n+i)*("-"===r?1:-1)}function r(t,e){t=t||{};for(var r in e)"undefined"==typeof t[r]&&(t[r]=e[r]);return t}function n(t){var e="(\\"+t.symbol.replace(/\./g,"\\.")+")"+(t.require_symbol?"":"?"),r="-?",n="[1-9]\\d*",i="[1-9]\\d{0,2}(\\"+t.thousands_separator+"\\d{3})*",o=["0",n,i],u="("+o.join("|")+")?",a="(\\"+t.decimal_separator+"\\d{2})?",s=u+a;return t.allow_negatives&&!t.parens_for_negatives&&(t.negative_sign_after_digits?s+=r:t.negative_sign_before_digits&&(s=r+s)),t.allow_negative_sign_placeholder?s="( (?!\\-))?"+s:t.allow_space_after_symbol?s=" ?"+s:t.allow_space_after_digits&&(s+="( (?!$))?"),t.symbol_after_digits?s+=e:s=e+s,t.allow_negatives&&(t.parens_for_negatives?s="(\\("+s+"\\)|"+s+")":t.negative_sign_before_digits||t.negative_sign_after_digits||(s=r+s)),new RegExp("^(?!-? )(?=.*\\d)"+s+"$")}t={version:"4.2.1"};var i=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i,o=/^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i,u=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i,a=/^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i,s=/^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\s]*<(.+)>$/i,l=/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/,f=/^[A-Z]{2}[0-9A-Z]{9}[0-9]$/,c=/^(?:[0-9]{9}X|[0-9]{10})$/,g=/^(?:[0-9]{13})$/,p=/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/,d=/^[0-9A-F]{1,4}$/i,F={3:/^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,4:/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,5:/^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,all:/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i},_=/^[A-Z]+$/i,x=/^[0-9A-Z]+$/i,h=/^[-+]?[0-9]+$/,v=/^(?:[-+]?(?:0|[1-9][0-9]*))$/,m=/^(?:[-+]?(?:[0-9]+))?(?:\.[0-9]*)?(?:[eE][\+\-]?(?:[0-9]+))?$/,A=/^[0-9A-F]+$/i,$=/^[-+]?([0-9]+|\.[0-9]+|[0-9]+\.[0-9]+)$/,w=/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i,D=/^[\x00-\x7F]+$/,b=/[^\x00-\x7F]/,y=/[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/,I=/[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/,O=/[\uD800-\uDBFF][\uDC00-\uDFFF]/,E=/^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i,S={"zh-CN":/^(\+?0?86\-?)?1[345789]\d{9}$/,"zh-TW":/^(\+?886\-?|0)?9\d{8}$/,"en-ZA":/^(\+?27|0)\d{9}$/,"en-AU":/^(\+?61|0)4\d{8}$/,"en-HK":/^(\+?852\-?)?[569]\d{3}\-?\d{4}$/,"fr-FR":/^(\+?33|0)[67]\d{8}$/,"pt-PT":/^(\+351)?9[1236]\d{7}$/,"el-GR":/^(\+30)?((2\d{9})|(69\d{8}))$/,"en-GB":/^(\+?44|0)7\d{9}$/,"en-US":/^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/,"en-ZM":/^(\+26)?09[567]\d{7}$/,"ru-RU":/^(\+?7|8)?9\d{9}$/,"nb-NO":/^(\+?47)?[49]\d{7}$/,"nn-NO":/^(\+?47)?[49]\d{7}$/},C=/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;t.extend=function(e,r){t[e]=function(){var e=Array.prototype.slice.call(arguments);return e[0]=t.toString(e[0]),r.apply(t,e)}},t.init=function(){for(var e in t)"function"==typeof t[e]&&"toString"!==e&&"toDate"!==e&&"extend"!==e&&"init"!==e&&t.extend(e,t[e])},t.toString=function(t){return"object"==typeof t&&null!==t&&t.toString?t=t.toString():(null===t||"undefined"==typeof t||isNaN(t)&&!t.length)&&(t=""),""+t},t.toDate=function(t){return"[object Date]"===Object.prototype.toString.call(t)?t:(t=Date.parse(t),isNaN(t)?null:new Date(t))},t.toFloat=function(t){return parseFloat(t)},t.toInt=function(t,e){return parseInt(t,e||10)},t.toBoolean=function(t,e){return e?"1"===t||"true"===t:"0"!==t&&"false"!==t&&""!==t},t.equals=function(e,r){return e===t.toString(r)},t.contains=function(e,r){return e.indexOf(t.toString(r))>=0},t.matches=function(t,e,r){return"[object RegExp]"!==Object.prototype.toString.call(e)&&(e=new RegExp(e,r)),e.test(t)};var N={allow_display_name:!1,allow_utf8_local_part:!0,require_tld:!0};t.isEmail=function(e,n){if(n=r(n,N),n.allow_display_name){var l=e.match(s);l&&(e=l[1])}var f=e.split("@"),c=f.pop(),g=f.join("@"),p=c.toLowerCase();if(("gmail.com"===p||"googlemail.com"===p)&&(g=g.replace(/\./g,"").toLowerCase()),!t.isByteLength(g,0,64)||!t.isByteLength(c,0,256))return!1;if(!t.isFQDN(c,{require_tld:n.require_tld}))return!1;if('"'===g[0])return g=g.slice(1,g.length-1),n.allow_utf8_local_part?a.test(g):o.test(g);for(var d=n.allow_utf8_local_part?u:i,F=g.split("."),_=0;_=2083||/\s/.test(e))return!1;if(0===e.indexOf("mailto:"))return!1;n=r(n,j);var i,o,u,a,s,l,f;if(f=e.split("://"),f.length>1){if(i=f.shift(),n.require_valid_protocol&&-1===n.protocols.indexOf(i))return!1}else{if(n.require_protocol)return!1;n.allow_protocol_relative_urls&&"//"===e.substr(0,2)&&(f[0]=e.substr(2))}return e=f.join("://"),f=e.split("#"),e=f.shift(),f=e.split("?"),e=f.shift(),f=e.split("/"),e=f.shift(),f=e.split("@"),f.length>1&&(o=f.shift(),o.indexOf(":")>=0&&o.split(":").length>2)?!1:(a=f.join("@"),f=a.split(":"),u=f.shift(),f.length&&(l=f.join(":"),s=parseInt(l,10),!/^[0-9]+$/.test(l)||0>=s||s>65535)?!1:t.isIP(u)||t.isFQDN(u,n)||"localhost"===u?n.host_whitelist&&-1===n.host_whitelist.indexOf(u)?!1:n.host_blacklist&&-1!==n.host_blacklist.indexOf(u)?!1:!0:!1)},t.isIP=function(e,r){if(r=t.toString(r),!r)return t.isIP(e,4)||t.isIP(e,6);if("4"===r){if(!p.test(e))return!1;var n=e.split(".").sort(function(t,e){return t-e});return n[3]<=255}if("6"===r){var i=e.split(":"),o=!1,u=t.isIP(i[i.length-1],4),a=u?7:8;if(i.length>a)return!1;if("::"===e)return!0;"::"===e.substr(0,2)?(i.shift(),i.shift(),o=!0):"::"===e.substr(e.length-2)&&(i.pop(),i.pop(),o=!0);for(var s=0;s0&&s=1:i.length===a}return!1};var B={require_tld:!0,allow_underscores:!1,allow_trailing_dot:!1};t.isFQDN=function(t,e){e=r(e,B),e.allow_trailing_dot&&"."===t[t.length-1]&&(t=t.substring(0,t.length-1));var n=t.split(".");if(e.require_tld){var i=n.pop();if(!n.length||!/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(i))return!1}for(var o,u=0;u=0)return!1;o=o.replace(/_/g,"")}if(!/^[a-z\u00a1-\uffff0-9-]+$/i.test(o))return!1;if(/[\uff01-\uff5e]/.test(o))return!1;if("-"===o[0]||"-"===o[o.length-1]||o.indexOf("---")>=0)return!1}return!0},t.isBoolean=function(t){return["true","false","1","0"].indexOf(t)>=0},t.isAlpha=function(t){return _.test(t)},t.isAlphanumeric=function(t){return x.test(t)},t.isNumeric=function(t){return h.test(t)},t.isDecimal=function(t){return""!==t&&$.test(t)},t.isHexadecimal=function(t){return A.test(t)},t.isHexColor=function(t){return w.test(t)},t.isLowercase=function(t){return t===t.toLowerCase()},t.isUppercase=function(t){return t===t.toUpperCase()},t.isInt=function(t,e){return e=e||{},v.test(t)&&(!e.hasOwnProperty("min")||t>=e.min)&&(!e.hasOwnProperty("max")||t<=e.max)},t.isFloat=function(t,e){return e=e||{},""===t||"."===t?!1:m.test(t)&&(!e.hasOwnProperty("min")||t>=e.min)&&(!e.hasOwnProperty("max")||t<=e.max)},t.isDivisibleBy=function(e,r){return t.toFloat(e)%t.toInt(r)===0},t.isNull=function(t){return 0===t.length},t.isLength=function(t,e,r){var n=t.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g)||[],i=t.length-n.length;return i>=e&&("undefined"==typeof r||r>=i)},t.isByteLength=function(t,e,r){var n=encodeURI(t).split(/%..|./).length-1;return n>=e&&("undefined"==typeof r||r>=n)},t.isUUID=function(t,e){var r=F[e?e:"all"];return r&&r.test(t)},t.isDate=function(t){var r=new Date(Date.parse(t));if(isNaN(r))return!1;var n=e(t);if(null!==n){var i=r.getTimezoneOffset()-n;r=new Date(r.getTime()+6e4*i)}var o,u,a,s=String(r.getDate());return(u=t.match(/(^|[^:\d])[23]\d([^:\d]|$)/g))?(o=u.map(function(t){return t.match(/\d+/g)[0]}).join("/"),a=String(r.getFullYear()).slice(-2),o===s||o===a?!0:o===s+"/"+a||o===a+"/"+s?!0:!1):!0},t.isAfter=function(e,r){var n=t.toDate(r||new Date),i=t.toDate(e);return!!(i&&n&&i>n)},t.isBefore=function(e,r){var n=t.toDate(r||new Date),i=t.toDate(e);return!!(i&&n&&n>i)},t.isIn=function(e,r){var n;if("[object Array]"===Object.prototype.toString.call(r)){var i=[];for(n in r)i[n]=t.toString(r[n]);return i.indexOf(e)>=0}return"object"==typeof r?r.hasOwnProperty(e):r&&"function"==typeof r.indexOf?r.indexOf(e)>=0:!1},t.isCreditCard=function(t){var e=t.replace(/[^0-9]+/g,"");if(!l.test(e))return!1;for(var r,n,i,o=0,u=e.length-1;u>=0;u--)r=e.substring(u,u+1),n=parseInt(r,10),i?(n*=2,o+=n>=10?n%10+1:n):o+=n,i=!i;return!!(o%10===0?e:!1)},t.isISIN=function(t){if(!f.test(t))return!1;for(var e,r,n=t.replace(/[A-Z]/g,function(t){return parseInt(t,36)}),i=0,o=!0,u=n.length-2;u>=0;u--)e=n.substring(u,u+1),r=parseInt(e,10),o?(r*=2,i+=r>=10?r+1:r):i+=r,o=!o;return parseInt(t.substr(t.length-1),10)===(1e4-i)%10},t.isISBN=function(e,r){if(r=t.toString(r),!r)return t.isISBN(e,10)||t.isISBN(e,13);var n,i=e.replace(/[\s-]+/g,""),o=0;if("10"===r){if(!c.test(i))return!1;for(n=0;9>n;n++)o+=(n+1)*i.charAt(n);if(o+="X"===i.charAt(9)?100:10*i.charAt(9),o%11===0)return!!i}else if("13"===r){if(!g.test(i))return!1;var u=[1,3];for(n=0;12>n;n++)o+=u[n%2]*i.charAt(n);if(i.charAt(12)-(10-o%10)%10===0)return!!i}return!1},t.isMobilePhone=function(t,e){return e in S?S[e].test(t):!1};var z={symbol:"$",require_symbol:!1,allow_space_after_symbol:!1,symbol_after_digits:!1,allow_negatives:!0,parens_for_negatives:!1,negative_sign_before_digits:!1,negative_sign_after_digits:!1,allow_negative_sign_placeholder:!1,thousands_separator:",",decimal_separator:".",allow_space_after_digits:!1};t.isCurrency=function(t,e){return e=r(e,z),n(e).test(t)},t.isJSON=function(t){try{var e=JSON.parse(t);return!!e&&"object"==typeof e}catch(r){}return!1},t.isMultibyte=function(t){return b.test(t)},t.isAscii=function(t){return D.test(t)},t.isFullWidth=function(t){return y.test(t)},t.isHalfWidth=function(t){return I.test(t)},t.isVariableWidth=function(t){return y.test(t)&&I.test(t)},t.isSurrogatePair=function(t){return O.test(t)},t.isBase64=function(t){return E.test(t)},t.isMongoId=function(e){return t.isHexadecimal(e)&&24===e.length},t.isISO8601=function(t){return C.test(t)},t.ltrim=function(t,e){var r=e?new RegExp("^["+e+"]+","g"):/^\s+/g;return t.replace(r,"")},t.rtrim=function(t,e){var r=e?new RegExp("["+e+"]+$","g"):/\s+$/g;return t.replace(r,"")},t.trim=function(t,e){var r=e?new RegExp("^["+e+"]+|["+e+"]+$","g"):/^\s+|\s+$/g;return t.replace(r,"")},t.escape=function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">").replace(/\//g,"/").replace(/\`/g,"`")},t.stripLow=function(e,r){var n=r?"\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F":"\\x00-\\x1F\\x7F";return t.blacklist(e,n)},t.whitelist=function(t,e){return t.replace(new RegExp("[^"+e+"]+","g"),"")},t.blacklist=function(t,e){return t.replace(new RegExp("["+e+"]+","g"),"")};var Z={lowercase:!0};return t.normalizeEmail=function(e,n){if(n=r(n,Z),!t.isEmail(e))return!1;var i=e.split("@",2);if(i[1]=i[1].toLowerCase(),"gmail.com"===i[1]||"googlemail.com"===i[1]){if(i[0]=i[0].toLowerCase().replace(/\./g,""),"+"===i[0][0])return!1;i[0]=i[0].split("+")[0],i[1]="gmail.com"}else n.lowercase&&(i[0]=i[0].toLowerCase());return i.join("@")},t.init(),t}); diff --git a/node_modules/winston/CHANGELOG.md b/node_modules/winston/CHANGELOG.md new file mode 100644 index 0000000..2aac1a1 --- /dev/null +++ b/node_modules/winston/CHANGELOG.md @@ -0,0 +1,188 @@ +## v2.1.1 / 2015-11-18 +### COLOR ME IMPRESSED EDITION + +- [#751](https://github.com/winstonjs/winston/pull/751), Fix colors not appearing in non-tty environments. Fixes [#609](https://github.com/winstonjs/winston/issues/609), [#616](https://github.com/winstonjs/winston/issues/616), [#669](https://github.com/winstonjs/winston/issues/669), [#648](https://github.com/winstonjs/winston/issues/648) (`fiznool`). +- [#752](https://github.com/winstonjs/winston/pull/752) Correct syslog RFC number. 5424 instead of 524. (`jbenoit2011`) + +## v2.1.0 / 2015-11-03 +### TEST ALL THE ECOSYSTEM EDITION + +- [#742](https://github.com/winstonjs/winston/pull/742), [32d52b7](https://github.com/winstonjs/winston/commit/32d52b7) Distribute common test files used by transports in the `winston` ecosystem. + +## v2.0.1 / 2015-11-02 +### BUGS ALWAYS HAPPEN OK EDITION + +- [#739](https://github.com/winstonjs/winston/issues/739), [1f16861](https://github.com/winstonjs/winston/commit/1f16861) Ensure that `logger.log("info", undefined)` does not throw. + +## v2.0.0 / 2015-10-29 +### OMG IT'S MY SISTER'S BIRTHDAY EDITION + +#### Breaking changes + +**Most important** +- **[0f82204](https://github.com/winstonjs/winston/commit/0f82204) Move `winston.transports.DailyRotateFile` [into a separate module](https://github.com/winstonjs/winston-daily-rotate-file)**: `require('winston-daily-rotate-file');` +- **[fb9eec0](https://github.com/winstonjs/winston/commit/fb9eec0) Reverse log levels in `npm` and `cli` configs to conform to [RFC524](https://tools.ietf.org/html/rfc5424). Fixes [#424](https://github.com/winstonjs/winston/pull/424) [#406](https://github.com/winstonjs/winston/pull/406) [#290](https://github.com/winstonjs/winston/pull/290)** +- **[8cd8368](https://github.com/winstonjs/winston/commit/8cd8368) Change the method signature to a `filter` function to be consistent with `rewriter` and log functions:** +``` js +function filter (level, msg, meta, inst) { + // Filter logic goes here... +} +``` + +**Other breaking changes** +- [e0c9dde](https://github.com/winstonjs/winston/commit/e0c9dde) Remove `winston.transports.Webhook`. Use `winston.transports.Http` instead. +- [f71e638](https://github.com/winstonjs/winston/commit/f71e638) Remove `Logger.prototype.addRewriter` and `Logger.prototype.addFilter` since they just push to an Array of functions. Use `logger.filters.push` or `logger.rewriters.push` explicitly instead. +- [a470ab5](https://github.com/winstonjs/winston/commit/a470ab5) No longer respect the `handleExceptions` option to `new winston.Logger`. Instead just pass in the `exceptionHandlers` option itself. +- [8cb7048](https://github.com/winstonjs/winston/commit/8cb7048) Removed `Logger.prototype.extend` functionality + +#### New features +- [3aa990c](https://github.com/winstonjs/winston/commit/3aa990c) Added `Logger.prototype.configure` which now contains all logic previously in the `winston.Logger` constructor function. (`indexzero`) +- [#726](https://github.com/winstonjs/winston/pull/726) Update .npmignore (`coreybutler`) +- [#700](https://github.com/winstonjs/winston/pull/700) Add an `eol` option to the `Console` transport. (`aquavitae`) +- [#731](https://github.com/winstonjs/winston/pull/731) Update `lib/transports.js` for better static analysis. (`indexzero`) + +#### Fixes, refactoring, and optimizations. OH MY! +- [#632](https://github.com/winstonjs/winston/pull/632) Allow `File` transport to be an `objectMode` writable stream. (`stambata`) +- [#527](https://github.com/winstonjs/winston/issues/527), [163f4f9](https://github.com/winstonjs/winston/commit/163f4f9), [3747ccf](https://github.com/winstonjs/winston/commit/3747ccf) Performance optimizations and string interpolation edge cases (`indexzero`) +- [f0edafd](https://github.com/winstonjs/winston/commit/f0edafd) Code cleanup for reability, ad-hoc styleguide enforcement (`indexzero`) + +## v1.1.1 - v1.1.2 / 2015-10 +### MINOR FIXES EDITION + +#### Notable changes + * [727](https://github.com/winstonjs/winston/pull/727) Fix "raw" mode (`jcrugzz`) + * [703](https://github.com/winstonjs/winston/pull/703) Do not modify Error or Date objects when logging. Fixes #610 (`harriha`). + +## v1.1.0 / 2015-10-09 +### GREETINGS FROM CARTAGENA EDITION + +#### Notable Changes + * [#721](https://github.com/winstonjs/winston/pull/721) Fixed octal literal to work with node 4 strict mode (`wesleyeff`) + * [#630](https://github.com/winstonjs/winston/pull/630) Add stderrLevels option to Console Transport and update docs (`paulhroth`) + * [#626](https://github.com/winstonjs/winston/pull/626) Add the logger (this) in the fourth argument in the rewriters and filters functions (`christophehurpeau `) + * [#623](https://github.com/winstonjs/winston/pull/623) Fix Console Transport's align option tests (`paulhroth`, `kikobeats`) + * [#692](https://github.com/winstonjs/winston/pull/692) Adding winston-aws-cloudwatch to transport docs (`timdp`) + +## v1.0.2 2015-09-25 +### LET'S TALK ON GITTER EDITION + +#### Notable Changes + * [de80160](https://github.com/winstonjs/winston/commit/de80160) Add Gitter badge (`The Gitter Badger`) + * [44564de](https://github.com/winstonjs/winston/commit/44564de) [fix] Correct listeners in `logException`. Fixes [#218](https://github.com/winstonjs/winston/issues/218) [#213](https://github.com/winstonjs/winston/issues/213) [#327](https://github.com/winstonjs/winston/issues/327). (`indexzero`) + * [45b1eeb](https://github.com/winstonjs/winston/commit/45b1eeb) [fix] Get `tailFile` function working on latest/all node versions (`Christopher Jeffrey`) + * [c6d45f9](https://github.com/winstonjs/winston/commit/c6d45f9) Fixed event subscription on close (`Roman Stetsyshin`) + +#### Other changes + * TravisCI updates & best practices [87b97cc](https://github.com/winstonjs/winston/commit/87b97cc) [91a5bc4](https://github.com/winstonjs/winston/commit/91a5bc4), [cf24e6a](https://github.com/winstonjs/winston/commit/cf24e6a) (`indexzero`) + * [d5397e7](https://github.com/winstonjs/winston/commit/d5397e7) Bump async version (`Roderick Hsiao`) + * Documentation updates & fixes [86d7527](https://github.com/winstonjs/winston/commit/86d7527), [38254c1](https://github.com/winstonjs/winston/commit/38254c1), [04e2928](https://github.com/winstonjs/winston/commit/04e2928), [61c8a89](https://github.com/winstonjs/winston/commit/61c8a89), [c42a783](https://github.com/winstonjs/winston/commit/c42a783), [0688a22](https://github.com/winstonjs/winston/commit/0688a22), [eabc113](https://github.com/winstonjs/winston/commit/eabc113) [c9506b7](https://github.com/winstonjs/winston/commit/c9506b7), [17534d2](https://github.com/winstonjs/winston/commit/17534d2), [b575e7b](https://github.com/winstonjs/winston/commit/b575e7b) (`Stefan Thies`, `charukiewicz`, `unLucio`, `Adam Cohen`, `Denis Gorbachev`, `Frederik Ring`, `Luigi Pinca`, `jeffreypriebe`) + * Documentation refactor & cleanup [a19607e](https://github.com/winstonjs/winston/commit/a19607e), [d1932b4](https://github.com/winstonjs/winston/commit/d1932b4), [7a13132](https://github.com/winstonjs/winston/commit/7a13132) (`indexzero`) + + +## v1.0.1 / 2015-06-26 +### YAY DOCS EDITION + + * [#639](https://github.com/winstonjs/winston/pull/639) Fix for [#213](https://github.com/winstonjs/winston/issues/213): More than 10 containers triggers EventEmitter memory leak warning (`marcus`) + * Documentation and `package.json` updates [cec892c](https://github.com/winstonjs/winston/commit/cec892c), [2f13b4f](https://github.com/winstonjs/winston/commit/2f13b4f), [b246efd](https://github.com/winstonjs/winston/commit/b246efd), [22a5f5a](https://github.com/winstonjs/winston/commit/22a5f5a), [5868b78](https://github.com/winstonjs/winston/commit/5868b78), [99b6b44](https://github.com/winstonjs/winston/commit/99b6b44), [447a813](https://github.com/winstonjs/winston/commit/447a813), [7f75b48](https://github.com/winstonjs/winston/commit/7f75b48) (`peteward44`, `Gilad Peleg`, `Anton Ian Sipos`, `nimrod-becker`, `LarsTi`, `indexzero`) + +## v1.0.0 / 2015-04-07 +### OMG 1.0.0 FINALLY EDITION + +#### Breaking Changes + * [#587](https://github.com/winstonjs/winston/pull/587) Do not extend `String` prototypes as a side effect of using `colors`. (`kenperkins`) + * [#581](https://github.com/winstonjs/winston/pull/581) File transports now emit `error` on error of the underlying streams after `maxRetries` attempts. (`ambbell`). + * [#583](https://github.com/winstonjs/winston/pull/583), [92729a](https://github.com/winstonjs/winston/commit/92729a68d71d07715501c35d94d2ac06ac03ca08) Use `os.EOL` for all file writing by default. (`Mik13`, `indexzero`) + * [#532](https://github.com/winstonjs/winston/pull/532) Delete logger instance from `Container` when `close` event is emitted. (`snater`) + * [#380](https://github.com/winstonjs/winston/pull/380) Rename `duration` to `durationMs`, which is now a number a not a string ending in `ms`. (`neoziro`) + * [#253](https://github.com/winstonjs/winston/pull/253) Do not set a default level. When `level` is falsey on any `Transport` instance, any `Logger` instance uses the configured level (instead of the Transport level) (`jstamerj`). + +#### Other changes + + * [b83de62](https://github.com/winstonjs/winston/commit/b83de62) Fix rendering of stack traces. + * [c899cc](https://github.com/winstonjs/winston/commit/c899cc1f0719e49b26ec933e0fa263578168ea3b) Update documentation (Fixes [#549](https://github.com/winstonjs/winston/issues/549)) + * [#551](https://github.com/winstonjs/winston/pull/551) Filter metadata along with messages + * [#578](https://github.com/winstonjs/winston/pull/578) Fixes minor issue with `maxFiles` in `File` transport (Fixes [#556](https://github.com/winstonjs/winston/issues/556)). + * [#560](https://github.com/winstonjs/winston/pull/560) Added `showLevel` support to `File` transport. + * [#558](https://github.com/winstonjs/winston/pull/558) Added `showLevel` support to `Console` transport. + +## v0.9.0 / 2015-02-03 + + * [#496](https://github.com/flatiron/winston/pull/496) Updated default option handling for CLI (`oojacoboo`). + * [f37634b](https://github.com/flatiron/winston/commit/f37634b) [dist] Only support `node >= 0.8.0`. (`indexzero`) + * [91a1e90](https://github.com/flatiron/winston/commit/91a1e90), [50163a0](https://github.com/flatiron/winston/commit/50163a0) Fix #84 [Enable a better unhandled exception experience](https://github.com/flatiron/winston/issues/84) (`samz`) + * [8b5fbcd](https://github.com/flatiron/winston/commit/8b5fbcd) #448 Added tailable option to file transport which rolls files backwards instead of creating incrementing appends. Implements #268 (`neouser99`) + * [a34f7d2](https://github.com/flatiron/winston/commit/a34f7d2) Custom log formatter functionality were added. (`Melnyk Andii`) + * [4c08191](https://github.com/flatiron/winston/commit/4c08191) Added showLevel flag to common.js, file*, memory and console transports. (`Tony Germaneri`) + * [64ed8e0](https://github.com/flatiron/winston/commit/64ed8e0) Adding custom pretty print function test. (`Alberto Pose`) + * [3872dfb](https://github.com/flatiron/winston/commit/3872dfb) Adding prettyPrint parameter as function example. (`Alberto Pose`) + * [2b96eee](https://github.com/flatiron/winston/commit/2b96eee) implemented filters #526 (`Chris Oloff`) + * [72273b1](https://github.com/flatiron/winston/commit/72273b1) Added the options to colorize only the level, only the message or all. Default behavior is kept. Using true will only colorize the level and false will not colorize anything. (`Michiel De Mey`) + * [178e8a6](https://github.com/flatiron/winston/commit/178e8a6) Prevent message from meta input being overwritten (`Leonard Martin`) + * [270be86](https://github.com/flatiron/winston/commit/270be86) [api] Allow for transports to be removed by their string name [test fix] Add test coverage for multiple transports of the same type added in #187. [doc] Document using multiple transports of the same type (`indexzero`) + * [0a848fa](https://github.com/flatiron/winston/commit/0a848fa) Add depth options for meta pretty print (`Loïc Mahieu`) + * [106b670](https://github.com/flatiron/winston/commit/106b670) Allow debug messages to be sent to stdout (`John Frizelle`) + * [ad2d5e1](https://github.com/flatiron/winston/commit/ad2d5e1) [fix] Handle Error instances in a sane way since their properties are non-enumerable __by default.__ Fixes #280. (`indexzero`) + * [5109dd0](https://github.com/flatiron/winston/commit/5109dd0) [fix] Have a default `until` before a default `from`. Fixes #478. (`indexzero`) + * [d761960](https://github.com/flatiron/winston/commit/d761960) Fix logging regular expression objects (`Chasen Le Hara`) + * [2632eb8](https://github.com/flatiron/winston/commit/2632eb8) Add option for EOL chars on FileTransport (`José F. Romaniello`) + * [bdecce7](https://github.com/flatiron/winston/commit/bdecce7) Remove duplicate logstash option (`José F. Romaniello`) + * [7a01f9a](https://github.com/flatiron/winston/commit/7a01f9a) Update declaration block according to project's style guide (`Ricardo Torres`) + * [ae27a19](https://github.com/flatiron/winston/commit/ae27a19) Fixes #306: Can't set customlevels to my loggers (RangeError: Maximum call stack size exceeded) (`Alberto Pose`) + * [1ba4f51](https://github.com/flatiron/winston/commit/1ba4f51) [fix] Call `res.resume()` in HttpTransport to get around known issues in streams2. (`indexzero`) + * [39e0258](https://github.com/flatiron/winston/commit/39e0258) Updated default option handling for CLI (`Jacob Thomason`) + * [8252801](https://github.com/flatiron/winston/commit/8252801) Added logstash support to console transport (`Ramon Snir`) + * [18aa301](https://github.com/flatiron/winston/commit/18aa301) Module isStream should be isstream (`Michael Neil`) + * [2f5f296](https://github.com/flatiron/winston/commit/2f5f296) options.prettyPrint can now be a function (`Matt Zukowski`) + * [a87a876](https://github.com/flatiron/winston/commit/a87a876) Adding rotationFormat prop to file.js (`orcaman`) + * [ff187f4](https://github.com/flatiron/winston/commit/ff187f4) Allow custom exception level (`jupiter`) + +## 0.8.3 / 2014-11-04 + +* [fix lowercase issue (`jcrugzz`)](https://github.com/flatiron/winston/commit/b3ffaa10b5fe9d2a510af5348cf4fb3870534123) + +## 0.8.2 / 2014-11-04 + +* [Full fix for #296 with proper streams2 detection with `isstream` for file transport (`jcrugzz`)](https://github.com/flatiron/winston/commit/5c4bd4191468570e46805ed399cad63cfb1856cc) +* [Add isstream module (`jcrugzz`)](https://github.com/flatiron/winston/commit/498b216d0199aebaef72ee4d8659a00fb737b9ae) +* [Partially fix #296 with streams2 detection for file transport (`indexzero`)](https://github.com/flatiron/winston/commit/b0227b6c27cf651ffa8b8192ef79ab24296362e3) +* [add stress test for issue #288 (`indexzero`)](https://github.com/flatiron/winston/commit/e08e504b5b3a00f0acaade75c5ba69e6439c84a6) +* [lessen timeouts to check test sanity (`indexzero`)](https://github.com/flatiron/winston/commit/e925f5bc398a88464f3e796545ff88912aff7568) +* [update winston-graylog2 documentation (`unlucio`)](https://github.com/flatiron/winston/commit/49fa86c31baf12c8ac3adced3bdba6deeea2e363) +* [fix test formatting (`indexzero`)](https://github.com/flatiron/winston/commit/8e2225799520a4598044cdf93006d216812a27f9) +* [fix so options are not redefined (`indexzero`)](https://github.com/flatiron/winston/commit/d1d146e8a5bb73dcb01579ad433f6d4f70b668ea) +* [fix self/this issue that broke `http` transport (`indexzero`)](https://github.com/flatiron/winston/commit/d10cbc07755c853b60729ab0cd14aa665da2a63b) + + +## 0.8.1 / 2014-10-06 + +* [Add label option for DailyRotateFile transport (`francoisTemasys`)](https://github.com/flatiron/winston/pull/459) +* [fix Logger#transports length check upon Logger#log (`adriano-di-giovanni`, `indexzero`)](https://github.com/flatiron/winston/pull/404) +* [err can be a string. (`gdw2`, `indexzero`)](https://github.com/flatiron/winston/pull/396) +* [Added color for pre-defined cli set. (`danilo1105`, `indexzero`)](https://github.com/flatiron/winston/pull/365) +* [Fix dates on transport test (`revington`)](https://github.com/flatiron/winston/pull/346) +* [Included the label from options to the output in JSON mode. (`arxony`)](https://github.com/flatiron/winston/pull/326) +* [Allow using logstash option with the File transport (`gmajoulet`)](https://github.com/flatiron/winston/pull/299) +* [Be more defensive when working with `query` methods from Transports. Fixes #356. (indexzero)](https://github.com/flatiron/winston/commit/b80638974057f74b521dbe6f43fef2105110afa2) +* [Catch exceptions for file transport unlinkSync (`calvinfo`)](https://github.com/flatiron/winston/pull/266) +* [Adding the 'addRewriter' to winston (`machadogj`)](https://github.com/flatiron/winston/pull/258) +* [Updates to transport documentation (`pose`)](https://github.com/flatiron/winston/pull/262) +* [fix typo in "Extending another object with Logging" section.](https://github.com/flatiron/winston/pull/281) +* [Updated README.md - Replaced properties with those listed in winston-mongodb module](https://github.com/flatiron/winston/pull/264) + +## 0.8.0 / 2014-09-15 + * [Fixes for HTTP Transport](https://github.com/flatiron/winston/commit/a876a012641f8eba1a976eada15b6687d4a03f82) + * Removing [jsonquest](https://github.com/flatiron/winston/commit/4f088382aeda28012b7a0498829ceb243ed74ac1) and [request](https://github.com/flatiron/winston/commit/a5676313b4e9744802cc3b8e1468e4af48830876) dependencies. + * Configuration is now [shalow cloned](https://github.com/flatiron/winston/commit/08fccc81d18536d33050496102d98bde648853f2). + * [Added logstash support](https://github.com/flatiron/winston/pull/445/files) + * Fix for ["flush" event should always fire after "flush" call bug](https://github.com/flatiron/winston/pull/446/files) + * Added tests for file: [open and stress](https://github.com/flatiron/winston/commit/47d885797a2dd0d3cd879305ca813a0bd951c378). + * [Test fixes](https://github.com/flatiron/winston/commit/9e39150e0018f43d198ca4c160acef2af9860bf4) + * [Fix ")" on string interpolation](https://github.com/flatiron/winston/pull/394/files) + +## 0.6.2 / 2012-07-08 + + * Added prettyPrint option for console logging + * Multi-line values for conditional returns are not allowed + * Added acceptance of `stringify` option + * Fixed padding for log levels + diff --git a/node_modules/winston/LICENSE b/node_modules/winston/LICENSE new file mode 100644 index 0000000..948d80d --- /dev/null +++ b/node_modules/winston/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Charlie Robbins + +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. \ No newline at end of file diff --git a/node_modules/winston/README.md b/node_modules/winston/README.md new file mode 100644 index 0000000..7f4497d --- /dev/null +++ b/node_modules/winston/README.md @@ -0,0 +1,833 @@ +# winston + +[![Join the chat at https://gitter.im/winstonjs/winston](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/winstonjs/winston?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![Version npm](https://img.shields.io/npm/v/winston.svg?style=flat-square)](https://www.npmjs.com/package/winston)[![npm Downloads](https://img.shields.io/npm/dm/winston.svg?style=flat-square)](https://www.npmjs.com/package/winston)[![Build Status](https://img.shields.io/travis/winstonjs/winston/master.svg?style=flat-square)](https://travis-ci.org/winstonjs/winston)[![Dependencies](https://img.shields.io/david/winstonjs/winston.svg?style=flat-square)](https://david-dm.org/winstonjs/winston) + +[![NPM](https://nodei.co/npm/winston.png?downloads=true&downloadRank=true)](https://nodei.co/npm/winston/) + +A multi-transport async logging library for node.js. "CHILL WINSTON! ... I put it in the logs." + +## Motivation +Winston is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs. Each instance of a winston logger can have multiple transports configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file. + +There also seemed to be a lot of logging libraries out there that coupled their implementation of logging (i.e. how the logs are stored / indexed) to the API that they exposed to the programmer. This library aims to decouple those parts of the process to make it more flexible and extensible. + +## Installation + +```bashp +npm install winston +``` + +## Usage +There are two different ways to use winston: directly via the default logger, or by instantiating your own Logger. The former is merely intended to be a convenient shared logger to use throughout your application if you so choose. + +* [Logging](#logging) + * [Using the Default Logger](#using-the-default-logger) + * [Instantiating your own Logger](#instantiating-your-own-logger) + * [Logging with Metadata](#logging-with-metadata) + * [String interpolation](#string-interpolation) +* [Transports](https://github.com/winstonjs/winston/blob/master/docs/transports.md) + * [Multiple transports of the same type](#multiple-transports-of-the-same-type) +* [Profiling](#profiling) +* [Streaming Logs](#streaming-logs) +* [Querying Logs](#querying-logs) +* [Exceptions](#exceptions) + * [Handling Uncaught Exceptions with winston](#handling-uncaught-exceptions-with-winston) + * [To Exit or Not to Exit](#to-exit-or-not-to-exit) +* [Logging Levels](#logging-levels) + * [Using Logging Levels](#using-logging-levels) + * [Using Custom Logging Levels](#using-custom-logging-levels) +* [Further Reading](#further-reading) + * [Events and Callbacks in Winston](#events-and-callbacks-in-winston) + * [Working with multiple Loggers in winston](#working-with-multiple-loggers-in-winston) + * [Using winston in a CLI tool](#using-winston-in-a-cli-tool) + * [Filters and Rewriters](#filters-and-rewriters) + * [Adding Custom Transports](#adding-custom-transports) +* [Installation](#installation) +* [Run Tests](#run-tests) + + +## Logging + +Logging levels in `winston` conform to the severity ordering specified by [RFC5424](https://tools.ietf.org/html/rfc5424): _severity of all levels is assumed to be numerically **ascending** from most important to least important._ + +### Using the Default Logger +The default logger is accessible through the winston module directly. Any method that you could call on an instance of a logger is available on the default logger: + +``` js + var winston = require('winston'); + + winston.log('info', 'Hello distributed log files!'); + winston.info('Hello again distributed logs'); + + winston.level = 'debug'; + winston.log('debug', 'Now my debug messages are written to console!'); +``` + +By default, only the Console transport is set on the default logger. You can add or remove transports via the add() and remove() methods: + +``` js + winston.add(winston.transports.File, { filename: 'somefile.log' }); + winston.remove(winston.transports.Console); +``` + +For more documentation about working with each individual transport supported by Winston see the [Winston Transports](docs/transports.md) document. + +### Instantiating your own Logger +If you would prefer to manage the object lifetime of loggers you are free to instantiate them yourself: + +``` js + var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)(), + new (winston.transports.File)({ filename: 'somefile.log' }) + ] + }); +``` + +You can work with this logger in the same way that you work with the default logger: + +``` js + // + // Logging + // + logger.log('info', 'Hello distributed log files!'); + logger.info('Hello again distributed logs'); + + // + // Adding / Removing Transports + // (Yes It's chainable) + // + logger + .add(winston.transports.File) + .remove(winston.transports.Console); +``` + +You can also wholesale reconfigure a `winston.Logger` instance using the `configure` method: + +``` js + var logger = new winston.Logger({ + level: 'info', + transports: [ + new (winston.transports.Console)(), + new (winston.transports.File)({ filename: 'somefile.log' }) + ] + }); + + // + // Replaces the previous transports with those in the + // new configuration wholesale. + // + logger.configure({ + level: 'verbose', + transports: [ + new require('winston-daily-rotate-file')(opts) + ] + }); +``` + + +### Logging with Metadata +In addition to logging string messages, winston will also optionally log additional JSON metadata objects. Adding metadata is simple: + +``` js + winston.log('info', 'Test Log Message', { anything: 'This is metadata' }); +``` + +The way these objects are stored varies from transport to transport (to best support the storage mechanisms offered). Here's a quick summary of how each transports handles metadata: + +1. __Console:__ Logged via util.inspect(meta) +2. __File:__ Logged via util.inspect(meta) + +## Multiple transports of the same type + +It is possible to use multiple transports of the same type e.g. `winston.transports.File` by passing in a custom `name` when you construct the transport. + +``` js +var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.File)({ + name: 'info-file', + filename: 'filelog-info.log', + level: 'info' + }), + new (winston.transports.File)({ + name: 'error-file', + filename: 'filelog-error.log', + level: 'error' + }) + ] +}); +``` + +If you later want to remove one of these transports you can do so by using the string name. e.g.: + +``` js +logger.remove('info-file'); +``` + +In this example one could also remove by passing in the instance of the Transport itself. e.g. this is equivalent to the string example above; + +``` js +// Notice it was first in the Array above +var infoFile = logger.transports[0]; +logger.remove(infoFile); +``` + +## Profiling +In addition to logging messages and metadata, winston also has a simple profiling mechanism implemented for any logger: + +``` js + // + // Start profile of 'test' + // Remark: Consider using Date.now() with async operations + // + winston.profile('test'); + + setTimeout(function () { + // + // Stop profile of 'test'. Logging will now take place: + // "17 Jan 21:00:00 - info: test duration=1000ms" + // + winston.profile('test'); + }, 1000); +``` + +All profile messages are set to the 'info' by default and both message and metadata are optional There are no plans in the Roadmap to make this configurable, but I'm open to suggestions / issues. + +### String interpolation +The `log` method provides the same string interpolation methods like [`util.format`][10]. + +This allows for the following log messages. +``` js +logger.log('info', 'test message %s', 'my string'); +// info: test message my string + +logger.log('info', 'test message %d', 123); +// info: test message 123 + +logger.log('info', 'test message %j', {number: 123}, {}); +// info: test message {"number":123} +// meta = {} + +logger.log('info', 'test message %s, %s', 'first', 'second', {number: 123}); +// info: test message first, second +// meta = {number: 123} + +logger.log('info', 'test message', 'first', 'second', {number: 123}); +// info: test message first second +// meta = {number: 123} + +logger.log('info', 'test message %s, %s', 'first', 'second', {number: 123}, function(){}); +// info: test message first, second +// meta = {number: 123} +// callback = function(){} + +logger.log('info', 'test message', 'first', 'second', {number: 123}, function(){}); +// info: test message first second +// meta = {number: 123} +// callback = function(){} +``` + + + + + +## Querying Logs +Winston supports querying of logs with Loggly-like options. [See Loggly Search API](http://wiki.loggly.com/retrieve_events#optional). +Specifically: `File`, `Couchdb`, `Redis`, `Loggly`, `Nssocket`, and `Http`. + +``` js + var options = { + from: new Date - 24 * 60 * 60 * 1000, + until: new Date, + limit: 10, + start: 0, + order: 'desc', + fields: ['message'] + }; + + // + // Find items logged between today and yesterday. + // + winston.query(options, function (err, results) { + if (err) { + throw err; + } + + console.log(results); + }); +``` + +## Streaming Logs +Streaming allows you to stream your logs back from your chosen transport. + +``` js + // + // Start at the end. + // + winston.stream({ start: -1 }).on('log', function(log) { + console.log(log); + }); +``` + +## Exceptions + +### Handling Uncaught Exceptions with winston + +With `winston`, it is possible to catch and log `uncaughtException` events from your process. There are two distinct ways of enabling this functionality either through the default winston logger or your own logger instance. + +If you want to use this feature with the default logger simply call `.handleExceptions()` with a transport instance. + +``` js + // + // You can add a separate exception logger by passing it to `.handleExceptions` + // + winston.handleExceptions(new winston.transports.File({ filename: 'path/to/exceptions.log' })) + + // + // Alternatively you can set `.handleExceptions` to true when adding transports to winston. + // You can use the `.humanReadableUnhandledException` option to get more readable exceptions. + // + winston.add(winston.transports.File, { + filename: 'path/to/all-logs.log', + handleExceptions: true, + humanReadableUnhandledException: true + }); +``` + +### To Exit or Not to Exit + +By default, winston will exit after logging an uncaughtException. if this is not the behavior you want, +set `exitOnError = false` + +``` js + var logger = new (winston.Logger)({ exitOnError: false }); + + // + // or, like this: + // + logger.exitOnError = false; +``` + +When working with custom logger instances, you can pass in separate transports to the `exceptionHandlers` property or set `.handleExceptions` on any transport. + +Example 1 + +``` js + var logger = new (winston.Logger)({ + transports: [ + new winston.transports.File({ filename: 'path/to/all-logs.log' }) + ], + exceptionHandlers: [ + new winston.transports.File({ filename: 'path/to/exceptions.log' }) + ] + }); +``` + +Example 2 + +``` js +var logger = new winston.Logger({ + transports: [ + new winston.transports.Console({ + handleExceptions: true, + json: true + }) + ], + exitOnError: false +}); +``` + +The `exitOnError` option can also be a function to prevent exit on only certain types of errors: + +``` js + function ignoreEpipe(err) { + return err.code !== 'EPIPE'; + } + + var logger = new (winston.Logger)({ exitOnError: ignoreEpipe }); + + // + // or, like this: + // + logger.exitOnError = ignoreEpipe; +``` + +## Logging Levels + +Each `level` is given a specific integer priority. The higher the priority the more important the message is considered to be, and the lower the corresponding integer priority. For example, `npm` logging levels are prioritized from 0 to 5 (highest to lowest): + +``` js +{ error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 } +``` + +Similarly, as specified exactly in RFC5424 the `syslog` levels are prioritized from 0 to 7 (highest to lowest). + +```js +{ emerg: 0, alert: 1, crit: 2, error: 3, warning: 4, notice: 5, info: 6, debug: 7 } +``` + +If you do not explicitly define the levels that `winston` should use the `npm` levels above will be used. + +### Using Logging Levels +Setting the level for your logging message can be accomplished in one of two ways. You can pass a string representing the logging level to the log() method or use the level specified methods defined on every winston Logger. + +``` js + // + // Any logger instance + // + logger.log('silly', "127.0.0.1 - there's no place like home"); + logger.log('debug', "127.0.0.1 - there's no place like home"); + logger.log('verbose', "127.0.0.1 - there's no place like home"); + logger.log('info', "127.0.0.1 - there's no place like home"); + logger.log('warn', "127.0.0.1 - there's no place like home"); + logger.log('error', "127.0.0.1 - there's no place like home"); + logger.info("127.0.0.1 - there's no place like home"); + logger.warn("127.0.0.1 - there's no place like home"); + logger.error("127.0.0.1 - there's no place like home"); + + // + // Default logger + // + winston.log('info', "127.0.0.1 - there's no place like home"); + winston.info("127.0.0.1 - there's no place like home"); +``` + +`winston` allows you to define a `level` property on each transport which specifies the **maximum** level of messages that a transport should log. For example, using the `npm` levels you could log only `error` messages to the console and everything `info` and below to a file (which includes `error` messages): + +``` js + var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)({ level: 'error' }), + new (winston.transports.File)({ + filename: 'somefile.log', + level: 'info' + }) + ] + }); +``` + +You may also dynamically change the log level of a transport: + +``` js + var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)({ level: 'warn' }), + new (winston.transports.File)({ filename: 'somefile.log', level: 'error' }) + ] + }); + logger.debug("Will not be logged in either transport!"); + logger.transports.console.level = 'debug'; + logger.transports.file.level = 'verbose'; + logger.verbose("Will be logged in both transports!"); +``` + +As of 0.2.0, winston supports customizable logging levels, defaulting to [npm][0] style logging levels. Changing logging levels is easy: + +``` js + // + // Change levels on the default winston logger + // + winston.setLevels(winston.config.syslog.levels); + + // + // Change levels on an instance of a logger + // + logger.setLevels(winston.config.syslog.levels); +``` + +Calling `.setLevels` on a logger will remove all of the previous helper methods for the old levels and define helper methods for the new levels. Thus, you should be careful about the logging statements you use when changing levels. For example, if you ran this code after changing to the syslog levels: + +``` js + // + // Logger does not have 'silly' defined since that level is not in the syslog levels + // + logger.silly('some silly message'); +``` + +### Using Custom Logging Levels +In addition to the predefined `npm` and `syslog` levels available in Winston, you can also choose to define your own: + +``` js + var myCustomLevels = { + levels: { + foo: 0, + bar: 1, + baz: 2, + foobar: 3 + }, + colors: { + foo: 'blue', + bar: 'green', + baz: 'yellow', + foobar: 'red' + } + }; + + var customLevelLogger = new (winston.Logger)({ levels: myCustomLevels.levels }); + customLevelLogger.foobar('some foobar level-ed message'); +``` + +Although there is slight repetition in this data structure, it enables simple encapsulation if you do not want to have colors. If you do wish to have colors, in addition to passing the levels to the Logger itself, you must make winston aware of them: + +``` js + // + // Make winston aware of these colors + // + winston.addColors(myCustomLevels.colors); +``` + +This enables transports with the 'colorize' option set to appropriately color the output of custom levels. + +## Further Reading + +### Events and Callbacks in Winston +Each instance of winston.Logger is also an instance of an [EventEmitter][1]. A log event will be raised each time a transport successfully logs a message: + +``` js + logger.on('logging', function (transport, level, msg, meta) { + // [msg] and [meta] have now been logged at [level] to [transport] + }); + + logger.info('CHILL WINSTON!', { seriously: true }); +``` + +It is also worth mentioning that the logger also emits an 'error' event which you should handle or suppress if you don't want unhandled exceptions: + +``` js + // + // Handle errors + // + logger.on('error', function (err) { /* Do Something */ }); + + // + // Or just suppress them. + // + logger.emitErrs = false; +``` + +Every logging method described in the previous section also takes an optional callback which will be called only when all of the transports have logged the specified message. + +``` js + logger.info('CHILL WINSTON!', { seriously: true }, function (err, level, msg, meta) { + // [msg] and [meta] have now been logged at [level] to **every** transport. + }); +``` + +### Working with multiple Loggers in winston + +Often in larger, more complex applications it is necessary to have multiple logger instances with different settings. Each logger is responsible for a different feature area (or category). This is exposed in `winston` in two ways: through `winston.loggers` and instances of `winston.Container`. In fact, `winston.loggers` is just a predefined instance of `winston.Container`: + +``` js + var winston = require('winston'); + + // + // Configure the logger for `category1` + // + winston.loggers.add('category1', { + console: { + level: 'silly', + colorize: true, + label: 'category one' + }, + file: { + filename: '/path/to/some/file' + } + }); + + // + // Configure the logger for `category2` + // + winston.loggers.add('category2', { + couchdb: { + host: '127.0.0.1', + port: 5984 + } + }); +``` + +Now that your loggers are setup you can require winston _in any file in your application_ and access these pre-configured loggers: + +``` js + var winston = require('winston'); + + // + // Grab your preconfigured logger + // + var category1 = winston.loggers.get('category1'); + + category1.info('logging from your IoC container-based logger'); +``` + +If you prefer to manage the `Container` yourself you can simply instantiate one: + +``` js + var winston = require('winston'), + container = new winston.Container(); + + container.add('category1', { + console: { + level: 'silly', + colorize: true + }, + file: { + filename: '/path/to/some/file' + } + }); +``` + +### Sharing transports between Loggers in winston + +``` js + var winston = require('winston'); + + // + // Setup transports to be shared across all loggers + // in three ways: + // + // 1. By setting it on the default Container + // 2. By passing `transports` into the constructor function of winston.Container + // 3. By passing `transports` into the `.get()` or `.add()` methods + // + + // + // 1. By setting it on the default Container + // + winston.loggers.options.transports = [ + // Setup your shared transports here + ]; + + // + // 2. By passing `transports` into the constructor function of winston.Container + // + var container = new winston.Container({ + transports: [ + // Setup your shared transports here + ] + }); + + // + // 3. By passing `transports` into the `.get()` or `.add()` methods + // + winston.loggers.add('some-category', { + transports: [ + // Setup your shared transports here + ] + }); + + container.add('some-category', { + transports: [ + // Setup your shared transports here + ] + }); +``` + +### Using winston in a CLI tool +A common use-case for logging is output to a CLI tool. Winston has a special helper method which will pretty print output from your CLI tool. Here's an example from the [require-analyzer][2] written by [Nodejitsu][3]: + +``` + info: require-analyzer starting in /Users/Charlie/Nodejitsu/require-analyzer + info: Found existing dependencies + data: { + data: colors: '0.x.x', + data: eyes: '0.1.x', + data: findit: '0.0.x', + data: npm: '1.0.x', + data: optimist: '0.2.x', + data: semver: '1.0.x', + data: winston: '0.2.x' + data: } + info: Analyzing dependencies... + info: Done analyzing raw dependencies + info: Retrieved packages from npm + warn: No additional dependencies found +``` + +Configuring output for this style is easy, just use the `.cli()` method on `winston` or an instance of `winston.Logger`: + +``` js + var winston = require('winston'); + + // + // Configure CLI output on the default logger + // + winston.cli(); + + // + // Configure CLI on an instance of winston.Logger + // + var logger = new winston.Logger({ + transports: [ + new (winston.transports.Console)() + ] + }); + + logger.cli(); +``` + +### Filters and Rewriters +Filters allow modifying the contents of **log messages**, and Rewriters allow modifying the contents of **log meta** e.g. to mask data that should not appear in logs. + +Both filters and rewriters are simple Arrays of functions which can be provided when creating a `new winston.Logger(options)`. e.g.: + +``` js +var logger = new winston.Logger({ + rewriters: [function (level, msg, meta) { /* etc etc */ }] + filters: [function (level, msg, meta) { /* etc etc */ }] +}) +``` + +Like any Array they can also be modified at runtime with no adverse side-effects to the `winston` internals. + +``` js +logger.filters.push(function(level, msg, meta) { + return meta.production + ? maskCardNumbers(msg) + : msg; +}); + +logger.info('transaction with card number 123456789012345 successful.'); +``` + +This may result in this output: + +``` +info: transaction with card number 123456****2345 successful. +``` + +Where as for rewriters, if you wanted to sanitize the `creditCard` field of your `meta` you could: + +``` js +logger.rewriters.push(function(level, msg, meta) { + if (meta.creditCard) { + meta.creditCard = maskCardNumbers(meta.creditCard) + } + + return meta; +}); + +logger.info('transaction ok', { creditCard: 123456789012345 }); +``` + +which may result in this output: + +``` +info: transaction ok creditCard=123456****2345 +``` + +See [log-filter-test.js](./test/log-filter-test.js), where card number masking is implemented as an example along with [log-rewriter-test.js](./test/log-rewriter-test.js) + +## Adding Custom Transports +Adding a custom transport is actually pretty easy. All you need to do is accept a couple of options, set a name, implement a log() method, and add it to the set of transports exposed by winston. + +``` js + var util = require('util'), + winston = require('winston'); + + var CustomLogger = winston.transports.CustomLogger = function (options) { + // + // Name this logger + // + this.name = 'customLogger'; + + // + // Set the level from your options + // + this.level = options.level || 'info'; + + // + // Configure your storage backing as you see fit + // + }; + + // + // Inherit from `winston.Transport` so you can take advantage + // of the base functionality and `.handleExceptions()`. + // + util.inherits(CustomLogger, winston.Transport); + + CustomLogger.prototype.log = function (level, msg, meta, callback) { + // + // Store this message and metadata, maybe use some custom logic + // then callback indicating success. + // + callback(null, true); + }; +``` + +### Custom Log Format +To specify custom log format you should set formatter function for transport. Currently supported transports are: Console, File, Memory. +Options object will be passed to the format function. It's general properties are: timestamp, level, message, meta. Depending on the transport type may be additional properties. + +``` js +var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)({ + timestamp: function() { + return Date.now(); + }, + formatter: function(options) { + // Return string will be passed to logger. + return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') + + (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' ); + } + }) + ] +}); +logger.info('Data to log.'); +``` + +### Inspirations +1. [npm][0] +2. [log.js][4] +3. [socket.io][5] +4. [node-rlog][6] +5. [BigBrother][7] +6. [Loggly][8] + +## Installation + +### Installing npm (node package manager) +``` + curl http://npmjs.org/install.sh | sh +``` + +### Installing winston +``` + [sudo] npm install winston +``` + +## Run Tests +All of the winston tests are written in [vows][9], and designed to be run with npm. + +``` bash + $ npm test +``` + +#### Author: [Charlie Robbins](http://twitter.com/indexzero) +#### Contributors: [Matthew Bergman](http://github.com/fotoverite), [Marak Squires](http://github.com/marak) + +[0]: https://github.com/npm/npmlog/blob/master/log.js +[1]: http://nodejs.org/docs/v0.3.5/api/events.html#events.EventEmitter +[2]: http://github.com/nodejitsu/require-analyzer +[3]: http://nodejitsu.com +[4]: https://github.com/visionmedia/log.js +[5]: http://socket.io +[6]: https://github.com/jbrisbin/node-rlog +[7]: https://github.com/feisty/BigBrother +[8]: http://loggly.com +[9]: http://vowsjs.org +[10]: http://nodejs.org/api/util.html#util_util_format_format +[14]: http://nodejs.org/api/stream.html#stream_class_stream_writable +[16]: https://github.com/indexzero/winston-mongodb +[17]: https://github.com/indexzero/winston-riak +[18]: https://github.com/appsattic/winston-simpledb +[19]: https://github.com/wavded/winston-mail +[21]: https://github.com/jesseditson/winston-sns +[22]: https://github.com/flite/winston-graylog2 +[23]: https://github.com/kenperkins/winston-papertrail +[24]: https://github.com/jorgebay/winston-cassandra +[25]: https://github.com/jesseditson/winston-sns +[26]: https://github.com/inspiredjw/winston-dynamodb/ diff --git a/node_modules/winston/lib/winston.js b/node_modules/winston/lib/winston.js new file mode 100644 index 0000000..43aa6d1 --- /dev/null +++ b/node_modules/winston/lib/winston.js @@ -0,0 +1,165 @@ +/* + * winston.js: Top-level include defining Winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var winston = exports; + +// +// Expose version using `pkginfo` +// +require('pkginfo')(module, 'version'); + +// +// Include transports defined by default by winston +// +winston.transports = require('./winston/transports'); + +// +// Expose utility methods +// +var common = require('./winston/common'); +winston.hash = common.hash; +winston.clone = common.clone; +winston.longestElement = common.longestElement; +winston.exception = require('./winston/exception'); +winston.config = require('./winston/config'); +winston.addColors = winston.config.addColors; + +// +// Expose core Logging-related prototypes. +// +winston.Container = require('./winston/container').Container; +winston.Logger = require('./winston/logger').Logger; +winston.Transport = require('./winston/transports/transport').Transport; + +// +// We create and expose a default `Container` to `winston.loggers` so that the +// programmer may manage multiple `winston.Logger` instances without any additional overhead. +// +// ### some-file1.js +// +// var logger = require('winston').loggers.get('something'); +// +// ### some-file2.js +// +// var logger = require('winston').loggers.get('something'); +// +winston.loggers = new winston.Container(); + +// +// We create and expose a 'defaultLogger' so that the programmer may do the +// following without the need to create an instance of winston.Logger directly: +// +// var winston = require('winston'); +// winston.log('info', 'some message'); +// winston.error('some error'); +// +var defaultLogger = new winston.Logger({ + transports: [new winston.transports.Console()] +}); + +// +// Pass through the target methods onto `winston. +// +var methods = [ + 'log', + 'query', + 'stream', + 'add', + 'remove', + 'clear', + 'profile', + 'startTimer', + 'extend', + 'cli', + 'handleExceptions', + 'unhandleExceptions', + 'addRewriter', + 'addFilter' +]; +common.setLevels(winston, null, defaultLogger.levels); +methods.forEach(function (method) { + winston[method] = function () { + return defaultLogger[method].apply(defaultLogger, arguments); + }; +}); + +// +// ### function cli () +// Configures the default winston logger to have the +// settings for command-line interfaces: no timestamp, +// colors enabled, padded output, and additional levels. +// +winston.cli = function () { + winston.padLevels = true; + common.setLevels(winston, defaultLogger.levels, winston.config.cli.levels); + defaultLogger.setLevels(winston.config.cli.levels); + winston.config.addColors(winston.config.cli.colors); + + if (defaultLogger.transports.console) { + defaultLogger.transports.console.colorize = true; + defaultLogger.transports.console.timestamp = false; + } + + return winston; +}; + +// +// ### function setLevels (target) +// #### @target {Object} Target levels to use +// Sets the `target` levels specified on the default winston logger. +// +winston.setLevels = function (target) { + common.setLevels(winston, defaultLogger.levels, target); + defaultLogger.setLevels(target); +}; + +// +// Define getter / setter for the default logger level +// which need to be exposed by winston. +// +Object.defineProperty(winston, 'level', { + get: function () { + return defaultLogger.level; + }, + set: function (val) { + defaultLogger.level = val; + + Object.keys(defaultLogger.transports).forEach(function(key) { + defaultLogger.transports[key].level = val; + }); + } +}); + +// +// Define getters / setters for appropriate properties of the +// default logger which need to be exposed by winston. +// +['emitErrs', 'exitOnError', 'padLevels', 'levelLength', 'stripColors'].forEach(function (prop) { + Object.defineProperty(winston, prop, { + get: function () { + return defaultLogger[prop]; + }, + set: function (val) { + defaultLogger[prop] = val; + } + }); +}); + +// +// @default {Object} +// The default transports and exceptionHandlers for +// the default winston logger. +// +Object.defineProperty(winston, 'default', { + get: function () { + return { + transports: defaultLogger.transports, + exceptionHandlers: defaultLogger.exceptionHandlers + }; + } +}); diff --git a/node_modules/winston/lib/winston/common.js b/node_modules/winston/lib/winston/common.js new file mode 100644 index 0000000..29dfec0 --- /dev/null +++ b/node_modules/winston/lib/winston/common.js @@ -0,0 +1,483 @@ +/* + * common.js: Internal helper and utility functions for winston + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var util = require('util'), + crypto = require('crypto'), + cycle = require('cycle'), + fs = require('fs'), + StringDecoder = require('string_decoder').StringDecoder, + Stream = require('stream').Stream, + config = require('./config'); + +// +// ### function setLevels (target, past, current) +// #### @target {Object} Object on which to set levels. +// #### @past {Object} Previous levels set on target. +// #### @current {Object} Current levels to set on target. +// Create functions on the target objects for each level +// in current.levels. If past is defined, remove functions +// for each of those levels. +// +exports.setLevels = function (target, past, current, isDefault) { + var self = this; + if (past) { + Object.keys(past).forEach(function (level) { + delete target[level]; + }); + } + + target.levels = current || config.npm.levels; + if (target.padLevels) { + target.levelLength = exports.longestElement(Object.keys(target.levels)); + } + + // + // Define prototype methods for each log level + // e.g. target.log('info', msg) <=> target.info(msg) + // + Object.keys(target.levels).forEach(function (level) { + + // TODO Refactor logging methods into a different object to avoid name clashes + if (level === 'log') { + console.warn('Log level named "log" will clash with the method "log". Consider using a different name.'); + return; + } + + target[level] = function (msg) { + // build argument list (level, msg, ... [string interpolate], [{metadata}], [callback]) + var args = [level].concat(Array.prototype.slice.call(arguments)); + target.log.apply(target, args); + }; + }); + + return target; +}; + +// +// ### function longestElement +// #### @xs {Array} Array to calculate against +// Returns the longest element in the `xs` array. +// +exports.longestElement = function (xs) { + return Math.max.apply( + null, + xs.map(function (x) { return x.length; }) + ); +}; + +// +// ### function clone (obj) +// #### @obj {Object} Object to clone. +// Helper method for deep cloning pure JSON objects +// i.e. JSON objects that are either literals or objects (no Arrays, etc) +// +exports.clone = function (obj) { + // + // We only need to clone reference types (Object) + // + var copy = {}; + + if (obj instanceof Error) { + // With potential custom Error objects, this might not be exactly correct, + // but probably close-enough for purposes of this lib. + copy = new Error(obj.message); + Object.getOwnPropertyNames(obj).forEach(function (key) { + copy[key] = obj[key]; + }); + + return copy; + } + else if (!(obj instanceof Object)) { + return obj; + } + else if (obj instanceof Date) { + return new Date(obj.getTime()); + } + + for (var i in obj) { + if (Array.isArray(obj[i])) { + copy[i] = obj[i].slice(0); + } + else if (obj[i] instanceof Buffer) { + copy[i] = obj[i].slice(0); + } + else if (typeof obj[i] != 'function') { + copy[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i]; + } + else if (typeof obj[i] === 'function') { + copy[i] = obj[i]; + } + } + + return copy; +}; + +// +// ### function log (options) +// #### @options {Object} All information about the log serialization. +// Generic logging function for returning timestamped strings +// with the following options: +// +// { +// level: 'level to add to serialized message', +// message: 'message to serialize', +// meta: 'additional logging metadata to serialize', +// colorize: false, // Colorizes output (only if `.json` is false) +// align: false // Align message level. +// timestamp: true // Adds a timestamp to the serialized message +// label: 'label to prepend the message' +// } +// +exports.log = function (options) { + var timestampFn = typeof options.timestamp === 'function' + ? options.timestamp + : exports.timestamp, + timestamp = options.timestamp ? timestampFn() : null, + showLevel = options.showLevel === undefined ? true : options.showLevel, + meta = options.meta !== null && options.meta !== undefined && !(options.meta instanceof Error) + ? exports.clone(cycle.decycle(options.meta)) + : options.meta || null, + output; + + // + // raw mode is intended for outputing winston as streaming JSON to STDOUT + // + if (options.raw) { + if (typeof meta !== 'object' && meta != null) { + meta = { meta: meta }; + } + output = exports.clone(meta) || {}; + output.level = options.level; + // + // Remark (jcrugzz): This used to be output.message = options.message.stripColors. + // I do not know why this is, it does not make sense but im handling that + // case here as well as handling the case that does make sense which is to + // make the `output.message = options.message` + // + output.message = options.message.stripColors + ? options.message.stripColors + : options.message; + + return JSON.stringify(output); + } + + // + // json mode is intended for pretty printing multi-line json to the terminal + // + if (options.json || true === options.logstash) { + if (typeof meta !== 'object' && meta != null) { + meta = { meta: meta }; + } + + output = exports.clone(meta) || {}; + output.level = options.level; + output.message = output.message || ''; + + if (options.label) { output.label = options.label; } + if (options.message) { output.message = options.message; } + if (timestamp) { output.timestamp = timestamp; } + + if (options.logstash === true) { + // use logstash format + var logstashOutput = {}; + if (output.message !== undefined) { + logstashOutput['@message'] = output.message; + delete output.message; + } + + if (output.timestamp !== undefined) { + logstashOutput['@timestamp'] = output.timestamp; + delete output.timestamp; + } + + logstashOutput['@fields'] = exports.clone(output); + output = logstashOutput; + } + + if (typeof options.stringify === 'function') { + return options.stringify(output); + } + + return JSON.stringify(output, function (key, value) { + return value instanceof Buffer + ? value.toString('base64') + : value; + }); + } + + // + // Remark: this should really be a call to `util.format`. + // + if (typeof options.formatter == 'function') { + return String(options.formatter(exports.clone(options))); + } + + output = timestamp ? timestamp + ' - ' : ''; + if (showLevel) { + output += options.colorize === 'all' || options.colorize === 'level' || options.colorize === true + ? config.colorize(options.level) + : options.level; + } + + output += (options.align) ? '\t' : ''; + output += (timestamp || showLevel) ? ': ' : ''; + output += options.label ? ('[' + options.label + '] ') : ''; + output += options.colorize === 'all' || options.colorize === 'message' + ? config.colorize(options.level, options.message) + : options.message; + + if (meta !== null && meta !== undefined) { + if (meta && meta instanceof Error && meta.stack) { + meta = meta.stack; + } + + if (typeof meta !== 'object') { + output += ' ' + meta; + } + else if (Object.keys(meta).length > 0) { + if (typeof options.prettyPrint === 'function') { + output += ' ' + options.prettyPrint(meta); + } else if (options.prettyPrint) { + output += ' ' + '\n' + util.inspect(meta, false, options.depth || null, options.colorize); + } else if ( + options.humanReadableUnhandledException + && Object.keys(meta).length === 5 + && meta.hasOwnProperty('date') + && meta.hasOwnProperty('process') + && meta.hasOwnProperty('os') + && meta.hasOwnProperty('trace') + && meta.hasOwnProperty('stack')) { + + // + // If meta carries unhandled exception data serialize the stack nicely + // + var stack = meta.stack; + delete meta.stack; + delete meta.trace; + output += ' ' + exports.serialize(meta); + output += '\n' + stack.join('\n'); + } else { + output += ' ' + exports.serialize(meta); + } + } + } + + return output; +}; + +exports.capitalize = function (str) { + return str && str[0].toUpperCase() + str.slice(1); +}; + +// +// ### function hash (str) +// #### @str {string} String to hash. +// Utility function for creating unique ids +// e.g. Profiling incoming HTTP requests on the same tick +// +exports.hash = function (str) { + return crypto.createHash('sha1').update(str).digest('hex'); +}; + +// +// ### function pad (n) +// Returns a padded string if `n < 10`. +// +exports.pad = function (n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +}; + +// +// ### function timestamp () +// Returns a timestamp string for the current time. +// +exports.timestamp = function () { + return new Date().toISOString(); +}; + +// +// ### function serialize (obj, key) +// #### @obj {Object|literal} Object to serialize +// #### @key {string} **Optional** Optional key represented by obj in a larger object +// Performs simple comma-separated, `key=value` serialization for Loggly when +// logging to non-JSON inputs. +// +exports.serialize = function (obj, key) { + if (obj === null) { + obj = 'null'; + } + else if (obj === undefined) { + obj = 'undefined'; + } + else if (obj === false) { + obj = 'false'; + } + + if (typeof obj !== 'object') { + return key ? key + '=' + obj : obj; + } + + if (obj instanceof Buffer) { + return key ? key + '=' + obj.toString('base64') : obj.toString('base64'); + } + + var msg = '', + keys = Object.keys(obj), + length = keys.length; + + for (var i = 0; i < length; i++) { + if (Array.isArray(obj[keys[i]])) { + msg += keys[i] + '=['; + + for (var j = 0, l = obj[keys[i]].length; j < l; j++) { + msg += exports.serialize(obj[keys[i]][j]); + if (j < l - 1) { + msg += ', '; + } + } + + msg += ']'; + } + else if (obj[keys[i]] instanceof Date) { + msg += keys[i] + '=' + obj[keys[i]]; + } + else { + msg += exports.serialize(obj[keys[i]], keys[i]); + } + + if (i < length - 1) { + msg += ', '; + } + } + + return msg; +}; + +// +// ### function tailFile (options, callback) +// #### @options {Object} Options for tail. +// #### @callback {function} Callback to execute on every line. +// `tail -f` a file. Options must include file. +// +exports.tailFile = function(options, callback) { + var buffer = new Buffer(64 * 1024) + , decode = new StringDecoder('utf8') + , stream = new Stream + , buff = '' + , pos = 0 + , row = 0; + + if (options.start === -1) { + delete options.start; + } + + stream.readable = true; + stream.destroy = function() { + stream.destroyed = true; + stream.emit('end'); + stream.emit('close'); + }; + + fs.open(options.file, 'a+', '0644', function(err, fd) { + if (err) { + if (!callback) { + stream.emit('error', err); + } else { + callback(err); + } + stream.destroy(); + return; + } + + (function read() { + if (stream.destroyed) { + fs.close(fd); + return; + } + + return fs.read(fd, buffer, 0, buffer.length, pos, function(err, bytes) { + if (err) { + if (!callback) { + stream.emit('error', err); + } else { + callback(err); + } + stream.destroy(); + return; + } + + if (!bytes) { + if (buff) { + if (options.start == null || row > options.start) { + if (!callback) { + stream.emit('line', buff); + } else { + callback(null, buff); + } + } + row++; + buff = ''; + } + return setTimeout(read, 1000); + } + + var data = decode.write(buffer.slice(0, bytes)); + + if (!callback) { + stream.emit('data', data); + } + + var data = (buff + data).split(/\n+/) + , l = data.length - 1 + , i = 0; + + for (; i < l; i++) { + if (options.start == null || row > options.start) { + if (!callback) { + stream.emit('line', data[i]); + } else { + callback(null, data[i]); + } + } + row++; + } + + buff = data[l]; + + pos += bytes; + + return read(); + }); + })(); + }); + + if (!callback) { + return stream; + } + + return stream.destroy; +}; + +// +// ### function stringArrayToSet (array) +// #### @strArray {Array} Array of Set-elements as strings. +// #### @errMsg {string} **Optional** Custom error message thrown on invalid input. +// Returns a Set-like object with strArray's elements as keys (each with the value true). +// +exports.stringArrayToSet = function (strArray, errMsg) { + if (typeof errMsg === 'undefined') { + errMsg = 'Cannot make set from Array with non-string elements'; + } + return strArray.reduce(function (set, el) { + if (!(typeof el === 'string' || el instanceof String)) { + throw new Error(errMsg); + } + set[el] = true; + return set; + }, Object.create(null)); +}; diff --git a/node_modules/winston/lib/winston/config.js b/node_modules/winston/lib/winston/config.js new file mode 100644 index 0000000..1bb52fd --- /dev/null +++ b/node_modules/winston/lib/winston/config.js @@ -0,0 +1,68 @@ +/* + * config.js: Default settings for all levels that winston knows about + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var colors = require('colors/safe'); + +// Fix colors not appearing in non-tty environments +colors.enabled = true; + +var config = exports, + allColors = exports.allColors = {}; + +config.addColors = function (colors) { + mixin(allColors, colors); +}; + +config.colorize = function (level, message) { + if (typeof message === 'undefined') message = level; + + var colorized = message; + if (allColors[level] instanceof Array) { + for (var i = 0, l = allColors[level].length; i < l; ++i) { + colorized = colors[allColors[level][i]](colorized); + } + } + else if (allColors[level].match(/\s/)) { + var colorArr = allColors[level].split(/\s+/); + for (var i = 0; i < colorArr.length; ++i) { + colorized = colors[colorArr[i]](colorized); + } + allColors[level] = colorArr; + } + else { + colorized = colors[allColors[level]](colorized); + } + + return colorized; +}; + +// +// Export config sets +// +config.cli = require('./config/cli-config'); +config.npm = require('./config/npm-config'); +config.syslog = require('./config/syslog-config'); + +// +// Add colors for pre-defined config sets +// +config.addColors(config.cli.colors); +config.addColors(config.npm.colors); +config.addColors(config.syslog.colors); + +function mixin (target) { + var args = Array.prototype.slice.call(arguments, 1); + + args.forEach(function (a) { + var keys = Object.keys(a); + for (var i = 0; i < keys.length; i++) { + target[keys[i]] = a[keys[i]]; + } + }); + return target; +}; diff --git a/node_modules/winston/lib/winston/config/cli-config.js b/node_modules/winston/lib/winston/config/cli-config.js new file mode 100644 index 0000000..764d2a8 --- /dev/null +++ b/node_modules/winston/lib/winston/config/cli-config.js @@ -0,0 +1,35 @@ +/* + * cli-config.js: Config that conform to commonly used CLI logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var cliConfig = exports; + +cliConfig.levels = { + error: 0, + warn: 1, + help: 2, + data: 3, + info: 4, + debug: 5, + prompt: 6, + verbose: 7, + input: 8, + silly: 9, +}; + +cliConfig.colors = { + error: 'red', + warn: 'yellow', + help: 'cyan', + data: 'grey', + info: 'green', + debug: 'blue', + prompt: 'grey', + verbose: 'cyan', + input: 'grey', + silly: 'magenta' +}; diff --git a/node_modules/winston/lib/winston/config/npm-config.js b/node_modules/winston/lib/winston/config/npm-config.js new file mode 100644 index 0000000..6402ab3 --- /dev/null +++ b/node_modules/winston/lib/winston/config/npm-config.js @@ -0,0 +1,27 @@ +/* + * npm-config.js: Config that conform to npm logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var npmConfig = exports; + +npmConfig.levels = { + error: 0, + warn: 1, + info: 2, + verbose: 3, + debug: 4, + silly: 5 +}; + +npmConfig.colors = { + error: 'red', + warn: 'yellow', + info: 'green', + verbose: 'cyan', + debug: 'blue', + silly: 'magenta' +}; diff --git a/node_modules/winston/lib/winston/config/syslog-config.js b/node_modules/winston/lib/winston/config/syslog-config.js new file mode 100644 index 0000000..67c6a09 --- /dev/null +++ b/node_modules/winston/lib/winston/config/syslog-config.js @@ -0,0 +1,31 @@ +/* + * syslog-config.js: Config that conform to syslog logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var syslogConfig = exports; + +syslogConfig.levels = { + emerg: 0, + alert: 1, + crit: 2, + error: 3, + warning: 4, + notice: 5, + info: 6, + debug: 7 +}; + +syslogConfig.colors = { + emerg: 'red', + alert: 'yellow', + crit: 'red', + error: 'red', + warning: 'red', + notice: 'yellow', + info: 'green', + debug: 'blue' +}; diff --git a/node_modules/winston/lib/winston/container.js b/node_modules/winston/lib/winston/container.js new file mode 100644 index 0000000..f5faaa7 --- /dev/null +++ b/node_modules/winston/lib/winston/container.js @@ -0,0 +1,127 @@ +/* + * container.js: Inversion of control container for winston logger instances + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var common = require('./common'), + winston = require('../winston'), + extend = require('util')._extend; + +// +// ### function Container (options) +// #### @options {Object} Default pass-thru options for Loggers +// Constructor function for the Container object responsible for managing +// a set of `winston.Logger` instances based on string ids. +// +var Container = exports.Container = function (options) { + this.loggers = {}; + this.options = options || {}; + this.default = { + transports: [ + new winston.transports.Console({ + level: 'silly', + colorize: false + }) + ] + } +}; + +// +// ### function get / add (id, options) +// #### @id {string} Id of the Logger to get +// #### @options {Object} **Optional** Options for the Logger instance +// Retreives a `winston.Logger` instance for the specified `id`. If +// an instance does not exist, one is created. +// +Container.prototype.get = Container.prototype.add = function (id, options) { + var self = this, + existing; + + if (!this.loggers[id]) { + // + // Remark: Simple shallow clone for configuration options in case we pass in + // instantiated protoypal objects + // + options = extend({}, options || this.options || this.default); + existing = options.transports || this.options.transports; + // + // Remark: Make sure if we have an array of transports we slice it to make copies + // of those references. + // + options.transports = existing ? existing.slice() : []; + + if (options.transports.length === 0 && (!options || !options['console'])) { + options.transports.push(this.default.transports[0]); + } + + Object.keys(options).forEach(function (key) { + if (key === 'transports') { + return; + } + + var name = common.capitalize(key); + + if (!winston.transports[name]) { + throw new Error('Cannot add unknown transport: ' + name); + } + + var namedOptions = options[key]; + namedOptions.id = id; + options.transports.push(new (winston.transports[name])(namedOptions)); + }); + + this.loggers[id] = new winston.Logger(options); + + this.loggers[id].on('close', function () { + self._delete(id); + }); + } + + return this.loggers[id]; +}; + +// +// ### function close (id) +// #### @id {string} **Optional** Id of the Logger instance to find +// Returns a boolean value indicating if this instance +// has a logger with the specified `id`. +// +Container.prototype.has = function (id) { + return !!this.loggers[id]; +}; + +// +// ### function close (id) +// #### @id {string} **Optional** Id of the Logger instance to close +// Closes a `Logger` instance with the specified `id` if it exists. +// If no `id` is supplied then all Loggers are closed. +// +Container.prototype.close = function (id) { + var self = this; + + function _close (id) { + if (!self.loggers[id]) { + return; + } + + self.loggers[id].close(); + self._delete(id); + } + + return id ? _close(id) : Object.keys(this.loggers).forEach(function (id) { + _close(id); + }); +}; + +// +// ### @private function _delete (id) +// #### @id {string} Id of the Logger instance to delete from container +// Deletes a `Logger` instance with the specified `id`. +// +Container.prototype._delete = function (id) { + delete this.loggers[id]; +} + diff --git a/node_modules/winston/lib/winston/exception.js b/node_modules/winston/lib/winston/exception.js new file mode 100644 index 0000000..22717dd --- /dev/null +++ b/node_modules/winston/lib/winston/exception.js @@ -0,0 +1,56 @@ +/* + * exception.js: Utility methods for gathing information about uncaughtExceptions. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var os = require('os'), + stackTrace = require('stack-trace'); + +var exception = exports; + +exception.getAllInfo = function (err) { + return { + date: new Date().toString(), + process: exception.getProcessInfo(), + os: exception.getOsInfo(), + trace: exception.getTrace(err), + stack: err.stack && err.stack.split('\n') + }; +}; + +exception.getProcessInfo = function () { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; +}; + +exception.getOsInfo = function () { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; +}; + +exception.getTrace = function (err) { + var trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(function (site) { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative(), + } + }); +}; diff --git a/node_modules/winston/lib/winston/logger.js b/node_modules/winston/lib/winston/logger.js new file mode 100755 index 0000000..97fba64 --- /dev/null +++ b/node_modules/winston/lib/winston/logger.js @@ -0,0 +1,723 @@ +/* + * logger.js: Core logger object used by winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var events = require('events'), + util = require('util'), + async = require('async'), + config = require('./config'), + common = require('./common'), + exception = require('./exception'), + Stream = require('stream').Stream; + +const formatRegExp = /%[sdj%]/g; + +// +// ### function Logger (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Logger object responsible +// for persisting log messages and metadata to one or more transports. +// +var Logger = exports.Logger = function (options) { + events.EventEmitter.call(this); + this.configure(options); +}; + +// +// Inherit from `events.EventEmitter`. +// +util.inherits(Logger, events.EventEmitter); + +// +// ### function configure (options) +// This will wholesale reconfigure this instance by: +// 1. Resetting all transports. Older transports will be removed implicitly. +// 2. Set all other options including levels, colors, rewriters, filters, +// exceptionHandlers, etc. +// +Logger.prototype.configure = function (options) { + var self = this; + + // + // If we have already been setup with transports + // then remove them before proceeding. + // + if (Array.isArray(this._names) && this._names.length) { + this.clear(); + } + + options = options || {}; + this.transports = {}; + this._names = []; + + if (options.transports) { + options.transports.forEach(function (transport) { + self.add(transport, null, true); + }); + } + + // + // Set Levels and default logging level + // + this.padLevels = options.padLevels || false; + this.setLevels(options.levels); + if (options.colors) { + config.addColors(options.colors); + } + + // + // Hoist other options onto this instance. + // + this.level = options.level || 'info'; + this.emitErrs = options.emitErrs || false; + this.stripColors = options.stripColors || false; + this.exitOnError = typeof options.exitOnError !== 'undefined' + ? options.exitOnError + : true; + + // + // Setup internal state as empty Objects even though it is + // defined lazily later to ensure a strong existential API contract. + // + this.exceptionHandlers = {}; + this.profilers = {}; + + ['rewriters', 'filters'].forEach(function (kind) { + self[kind] = Array.isArray(options[kind]) + ? options[kind] + : []; + }); + + if (options.exceptionHandlers) { + this.handleExceptions(options.exceptionHandlers); + } +}; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +Logger.prototype.log = function (level) { + var args = Array.prototype.slice.call(arguments, 1), + self = this, + transports; + + while (args[args.length - 1] === null) { + args.pop(); + } + + // + // Determining what is `meta` and what are arguments for string interpolation + // turns out to be VERY tricky. e.g. in the cases like this: + // + // logger.info('No interpolation symbols', 'ok', 'why', { meta: 'is-this' }); + // + var callback = typeof args[args.length - 1] === 'function' + ? args.pop() + : null; + + // + // Handle errors appropriately. + // + function onError(err) { + if (callback) { + callback(err); + } + else if (self.emitErrs) { + self.emit('error', err); + } + } + + if (this._names.length === 0) { + return onError(new Error('Cannot log with no transports.')); + } + else if (typeof self.levels[level] === 'undefined') { + return onError(new Error('Unknown log level: ' + level)); + } + + // + // If there are no transports that match the level + // then be eager and return. This could potentially be calculated + // during `setLevels` for more performance gains. + // + var targets = this._names.filter(function (name) { + var transport = self.transports[name]; + return (transport.level && self.levels[transport.level] >= self.levels[level]) + || (!transport.level && self.levels[self.level] >= self.levels[level]); + }); + + if (!targets.length) { + if (callback) { callback(); } + return; + } + + // + // Determining what is `meta` and what are arguments for string interpolation + // turns out to be VERY tricky. e.g. in the cases like this: + // + // logger.info('No interpolation symbols', 'ok', 'why', { meta: 'is-this' }); + // + var metaType = Object.prototype.toString.call(args[args.length - 1]), + fmtMatch = args[0] && args[0].match && args[0].match(formatRegExp), + isFormat = fmtMatch && fmtMatch.length, + validMeta = !isFormat + ? metaType === '[object Object]' || metaType === '[object Error]' || metaType === '[object Array]' + : metaType === '[object Object]', + meta = validMeta ? args.pop() : {}, + msg = util.format.apply(null, args); + + // + // Respond to the callback. + // + function finish(err) { + if (callback) { + if (err) return callback(err); + callback(null, level, msg, meta); + } + + callback = null; + if (!err) { + self.emit('logged', level, msg, meta); + } + } + + // If we should pad for levels, do so + if (this.padLevels) { + msg = new Array(this.levelLength - level.length + 1).join(' ') + msg; + } + + this.rewriters.forEach(function (rewriter) { + meta = rewriter(level, msg, meta, self); + }); + + this.filters.forEach(function(filter) { + var filtered = filter(level, msg, meta, self); + if (typeof filtered === 'string') + msg = filtered; + else { + msg = filtered.msg; + meta = filtered.meta; + } + }); + + // + // For consideration of terminal 'color" programs like colors.js, + // which can add ANSI escape color codes to strings, we destyle the + // ANSI color escape codes when `this.stripColors` is set. + // + // see: http://en.wikipedia.org/wiki/ANSI_escape_code + // + if (this.stripColors) { + var code = /\u001b\[(\d+(;\d+)*)?m/g; + msg = ('' + msg).replace(code, ''); + } + + // + // Log for each transport and emit 'logging' event + // + function transportLog(name, next) { + var transport = self.transports[name]; + transport.log(level, msg, meta, function (err) { + if (err) { + err.transport = transport; + finish(err); + return next(); + } + + self.emit('logging', transport, level, msg, meta); + next(); + }); + } + + async.forEach(targets, transportLog, finish); + return this; +}; + +// +// ### function query (options, callback) +// #### @options {Object} Query options for this instance. +// #### @callback {function} Continuation to respond to when complete. +// Queries the all transports for this instance with the specified `options`. +// This will aggregate each transport's results into one object containing +// a property per transport. +// +Logger.prototype.query = function (options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var self = this, + options = options || {}, + results = {}, + query = common.clone(options.query) || {}, + transports; + + // + // Helper function to query a single transport + // + function queryTransport(transport, next) { + if (options.query) { + options.query = transport.formatQuery(query); + } + + transport.query(options, function (err, results) { + if (err) { + return next(err); + } + + next(null, transport.formatResults(results, options.format)); + }); + } + + // + // Helper function to accumulate the results from + // `queryTransport` into the `results`. + // + function addResults(transport, next) { + queryTransport(transport, function (err, result) { + // + // queryTransport could potentially invoke the callback + // multiple times since Transport code can be unpredictable. + // + if (next) { + result = err || result; + if (result) { + results[transport.name] = result; + } + + next(); + } + + next = null; + }); + } + + // + // If an explicit transport is being queried then + // respond with the results from only that transport + // + if (options.transport) { + options.transport = options.transport.toLowerCase(); + return queryTransport(this.transports[options.transport], callback); + } + + // + // Create a list of all transports for this instance. + // + transports = this._names.map(function (name) { + return self.transports[name]; + }).filter(function (transport) { + return !!transport.query; + }); + + // + // Iterate over the transports in parallel setting the + // appropriate key in the `results` + // + async.forEach(transports, addResults, function () { + callback(null, results); + }); +}; + +// +// ### function stream (options) +// #### @options {Object} Stream options for this instance. +// Returns a log stream for all transports. Options object is optional. +// +Logger.prototype.stream = function (options) { + var self = this, + options = options || {}, + out = new Stream, + streams = [], + transports; + + if (options.transport) { + var transport = this.transports[options.transport]; + delete options.transport; + if (transport && transport.stream) { + return transport.stream(options); + } + } + + out._streams = streams; + out.destroy = function () { + var i = streams.length; + while (i--) streams[i].destroy(); + }; + + // + // Create a list of all transports for this instance. + // + transports = this._names.map(function (name) { + return self.transports[name]; + }).filter(function (transport) { + return !!transport.stream; + }); + + transports.forEach(function (transport) { + var stream = transport.stream(options); + if (!stream) return; + + streams.push(stream); + + stream.on('log', function (log) { + log.transport = log.transport || []; + log.transport.push(transport.name); + out.emit('log', log); + }); + + stream.on('error', function (err) { + err.transport = err.transport || []; + err.transport.push(transport.name); + out.emit('error', err); + }); + }); + + return out; +}; + +// +// ### function close () +// Cleans up resources (streams, event listeners) for all +// transports associated with this instance (if necessary). +// +Logger.prototype.close = function () { + var self = this; + + this._names.forEach(function (name) { + var transport = self.transports[name]; + if (transport && transport.close) { + transport.close(); + } + }); + + this.emit('close'); +}; + +// +// ### function handleExceptions ([tr0, tr1...] || tr0, tr1, ...) +// Handles `uncaughtException` events for the current process by +// ADDING any handlers passed in. +// +Logger.prototype.handleExceptions = function () { + var args = Array.prototype.slice.call(arguments), + handlers = [], + self = this; + + args.forEach(function (a) { + if (Array.isArray(a)) { + handlers = handlers.concat(a); + } + else { + handlers.push(a); + } + }); + + this.exceptionHandlers = this.exceptionHandlers || {}; + handlers.forEach(function (handler) { + self.exceptionHandlers[handler.name] = handler; + }); + + this._hnames = Object.keys(self.exceptionHandlers); + + if (!this.catchExceptions) { + this.catchExceptions = this._uncaughtException.bind(this); + process.on('uncaughtException', this.catchExceptions); + } +}; + +// +// ### function unhandleExceptions () +// Removes any handlers to `uncaughtException` events +// for the current process +// +Logger.prototype.unhandleExceptions = function () { + var self = this; + + if (this.catchExceptions) { + Object.keys(this.exceptionHandlers).forEach(function (name) { + var handler = self.exceptionHandlers[name]; + if (handler.close) { + handler.close(); + } + }); + + this.exceptionHandlers = {}; + Object.keys(this.transports).forEach(function (name) { + var transport = self.transports[name]; + if (transport.handleExceptions) { + transport.handleExceptions = false; + } + }) + + process.removeListener('uncaughtException', this.catchExceptions); + this.catchExceptions = false; + } +}; + +// +// ### function add (transport, [options]) +// #### @transport {Transport} Prototype of the Transport object to add. +// #### @options {Object} **Optional** Options for the Transport to add. +// #### @instance {Boolean} **Optional** Value indicating if `transport` is already instantiated. +// Adds a transport of the specified type to this instance. +// +Logger.prototype.add = function (transport, options, created) { + var instance = created ? transport : (new (transport)(options)); + + if (!instance.name && !instance.log) { + throw new Error('Unknown transport with no log() method'); + } + else if (this.transports[instance.name]) { + throw new Error('Transport already attached: ' + instance.name); + } + + this.transports[instance.name] = instance; + this._names = Object.keys(this.transports); + + // + // Listen for the `error` event on the new Transport + // + instance._onError = this._onError.bind(this, instance) + if (!created) { + instance.on('error', instance._onError); + } + + // + // If this transport has `handleExceptions` set to `true` + // and we are not already handling exceptions, do so. + // + if (instance.handleExceptions && !this.catchExceptions) { + this.handleExceptions(); + } + + return this; +}; + +// +// ### function clear () +// Remove all transports from this instance +// +Logger.prototype.clear = function () { + Object.keys(this.transports).forEach(function (name) { + this.remove({ name: name }); + }, this); +}; + +// +// ### function remove (transport) +// #### @transport {Transport|String} Transport or Name to remove. +// Removes a transport of the specified type from this instance. +// +Logger.prototype.remove = function (transport) { + var name = typeof transport !== 'string' + ? transport.name || transport.prototype.name + : transport; + + if (!this.transports[name]) { + throw new Error('Transport ' + name + ' not attached to this instance'); + } + + var instance = this.transports[name]; + delete this.transports[name]; + this._names = Object.keys(this.transports); + + if (instance.close) { + instance.close(); + } + + if (instance._onError) { + instance.removeListener('error', instance._onError); + } + return this; +}; + +// +// ### function startTimer () +// Returns an object corresponding to a specific timing. When done +// is called the timer will finish and log the duration. e.g.: +// +// timer = winston.startTimer() +// setTimeout(function(){ +// timer.done("Logging message"); +// }, 1000); +// +Logger.prototype.startTimer = function () { + return new ProfileHandler(this); +}; + +// +// ### function profile (id, [msg, meta, callback]) +// #### @id {string} Unique id of the profiler +// #### @msg {string} **Optional** Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} **Optional** Continuation to respond to when complete. +// Tracks the time inbetween subsequent calls to this method +// with the same `id` parameter. The second call to this method +// will log the difference in milliseconds along with the message. +// +Logger.prototype.profile = function (id) { + var now = Date.now(), then, args, + msg, meta, callback; + + if (this.profilers[id]) { + then = this.profilers[id]; + delete this.profilers[id]; + + // Support variable arguments: msg, meta, callback + args = Array.prototype.slice.call(arguments); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : null; + meta = typeof args[args.length - 1] === 'object' ? args.pop() : {}; + msg = args.length === 2 ? args[1] : id; + + // Set the duration property of the metadata + meta.durationMs = now - then; + return this.info(msg, meta, callback); + } + else { + this.profilers[id] = now; + } + + return this; +}; + +// +// ### function setLevels (target) +// #### @target {Object} Target levels to use on this instance +// Sets the `target` levels specified on this instance. +// +Logger.prototype.setLevels = function (target) { + return common.setLevels(this, this.levels, target); +}; + +// +// ### function cli () +// Configures this instance to have the default +// settings for command-line interfaces: no timestamp, +// colors enabled, padded output, and additional levels. +// +Logger.prototype.cli = function () { + this.padLevels = true; + this.setLevels(config.cli.levels); + config.addColors(config.cli.colors); + + if (this.transports.console) { + this.transports.console.colorize = this.transports.console.colorize || true; + this.transports.console.timestamp = this.transports.console.timestamp || false; + } + + return this; +}; + +// +// ### @private function _uncaughtException (err) +// #### @err {Error} Error to handle +// Logs all relevant information around the `err` and +// exits the current process. +// +Logger.prototype._uncaughtException = function (err) { + var self = this, + responded = false, + info = exception.getAllInfo(err), + handlers = this._getExceptionHandlers(), + timeout, + doExit; + + // + // Calculate if we should exit on this error + // + doExit = typeof this.exitOnError === 'function' + ? this.exitOnError(err) + : this.exitOnError; + + function logAndWait(transport, next) { + transport.logException('uncaughtException: ' + (err.message || err), info, next, err); + } + + function gracefulExit() { + if (doExit && !responded) { + // + // Remark: Currently ignoring any exceptions from transports + // when catching uncaught exceptions. + // + clearTimeout(timeout); + responded = true; + process.exit(1); + } + } + + if (!handlers || handlers.length === 0) { + return gracefulExit(); + } + + // + // Log to all transports and allow the operation to take + // only up to `3000ms`. + // + async.forEach(handlers, logAndWait, gracefulExit); + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } +}; + +// +// ### @private function _getExceptionHandlers () +// Returns the list of transports and exceptionHandlers +// for this instance. +// +Logger.prototype._getExceptionHandlers = function () { + var self = this; + + return this._hnames.map(function (name) { + return self.exceptionHandlers[name]; + }).concat(this._names.map(function (name) { + return self.transports[name].handleExceptions && self.transports[name]; + })).filter(Boolean); +}; + +// +// ### @private function _onError (transport, err) +// #### @transport {Object} Transport on which the error occured +// #### @err {Error} Error that occurred on the transport +// Bubbles the error, `err`, that occured on the specified `transport` +// up from this instance if `emitErrs` has been set. +// +Logger.prototype._onError = function (transport, err) { + if (this.emitErrs) { + this.emit('error', err, transport); + } +}; + +// +// ### @private ProfileHandler +// Constructor function for the ProfileHandler instance used by +// `Logger.prototype.startTimer`. When done is called the timer +// will finish and log the duration. +// +function ProfileHandler(logger) { + this.logger = logger; + this.start = Date.now(); +} + +// +// ### function done (msg) +// Ends the current timer (i.e. ProfileHandler) instance and +// logs the `msg` along with the duration since creation. +// +ProfileHandler.prototype.done = function (msg) { + var args = Array.prototype.slice.call(arguments), + callback = typeof args[args.length - 1] === 'function' ? args.pop() : null, + meta = typeof args[args.length - 1] === 'object' ? args.pop() : {}; + + meta.duration = (Date.now()) - this.start + 'ms'; + return this.logger.info(msg, meta, callback); +}; diff --git a/node_modules/winston/lib/winston/transports.js b/node_modules/winston/lib/winston/transports.js new file mode 100644 index 0000000..34f800e --- /dev/null +++ b/node_modules/winston/lib/winston/transports.js @@ -0,0 +1,29 @@ +/* + * transports.js: Set of all transports Winston knows about + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var path = require('path'); + +// +// Setup all transports as lazy-loaded getters. +// +Object.defineProperties( + exports, + ['Console', 'File', 'Http', 'Memory'] + .reduce(function (acc, name) { + acc[name] = { + configurable: true, + enumerable: true, + get: function () { + var fullpath = path.join(__dirname, 'transports', name.toLowerCase()); + return exports[name] = require(fullpath)[name]; + } + }; + + return acc; + }, {}) +); diff --git a/node_modules/winston/lib/winston/transports/console.js b/node_modules/winston/lib/winston/transports/console.js new file mode 100644 index 0000000..f573e17 --- /dev/null +++ b/node_modules/winston/lib/winston/transports/console.js @@ -0,0 +1,130 @@ +/* + * console.js: Transport for outputting to the console + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var events = require('events'), + os = require('os'), + util = require('util'), + common = require('../common'), + Transport = require('./transport').Transport; + +// +// ### function Console (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Console transport object responsible +// for persisting log messages and metadata to a terminal or TTY. +// +var Console = exports.Console = function (options) { + Transport.call(this, options); + options = options || {}; + + this.json = options.json || false; + this.colorize = options.colorize || false; + this.prettyPrint = options.prettyPrint || false; + this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false; + this.showLevel = options.showLevel === undefined ? true : options.showLevel; + this.label = options.label || null; + this.logstash = options.logstash || false; + this.depth = options.depth || null; + this.align = options.align || false; + this.stderrLevels = setStderrLevels(options.stderrLevels, options.debugStdout); + this.eol = options.eol || os.EOL; + + if (this.json) { + this.stringify = options.stringify || function (obj) { + return JSON.stringify(obj, null, 2); + }; + } + + // + // Convert stderrLevels into an Object for faster key-lookup times than an Array. + // + // For backwards compatibility, stderrLevels defaults to ['error', 'debug'] + // or ['error'] depending on whether options.debugStdout is true. + // + function setStderrLevels (levels, debugStdout) { + var defaultMsg = 'Cannot have non-string elements in stderrLevels Array'; + if (debugStdout) { + if (levels) { + // + // Don't allow setting both debugStdout and stderrLevels together, + // since this could cause behaviour a programmer might not expect. + // + throw new Error('Cannot set debugStdout and stderrLevels together'); + } + + return common.stringArrayToSet(['error'], defaultMsg); + } + + if (!levels) { + return common.stringArrayToSet(['error', 'debug'], defaultMsg); + } else if (!(Array.isArray(levels))) { + throw new Error('Cannot set stderrLevels to type other than Array'); + } + + return common.stringArrayToSet(levels, defaultMsg); + }; +}; + +// +// Inherit from `winston.Transport`. +// +util.inherits(Console, Transport); + +// +// Expose the name of this Transport on the prototype +// +Console.prototype.name = 'console'; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +Console.prototype.log = function (level, msg, meta, callback) { + if (this.silent) { + return callback(null, true); + } + + var self = this, + output; + + output = common.log({ + colorize: this.colorize, + json: this.json, + level: level, + message: msg, + meta: meta, + stringify: this.stringify, + timestamp: this.timestamp, + showLevel: this.showLevel, + prettyPrint: this.prettyPrint, + raw: this.raw, + label: this.label, + logstash: this.logstash, + depth: this.depth, + formatter: this.formatter, + align: this.align, + humanReadableUnhandledException: this.humanReadableUnhandledException + }); + + if (this.stderrLevels[level]) { + process.stderr.write(output + '\n'); + } else { + process.stdout.write(output + this.eol); + } + + // + // Emit the `logged` event immediately because the event loop + // will not exit until `process.stdout` has drained anyway. + // + self.emit('logged'); + callback(null, true); +}; diff --git a/node_modules/winston/lib/winston/transports/file.js b/node_modules/winston/lib/winston/transports/file.js new file mode 100644 index 0000000..b3df4b5 --- /dev/null +++ b/node_modules/winston/lib/winston/transports/file.js @@ -0,0 +1,678 @@ +/* + * file.js: Transport for outputting to a local log file + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var events = require('events'), + fs = require('fs'), + path = require('path'), + util = require('util'), + async = require('async'), + zlib = require('zlib'), + common = require('../common'), + Transport = require('./transport').Transport, + isWritable = require('isstream').isWritable, + Stream = require('stream').Stream, + os = require('os'); + +// +// ### function File (options) +// #### @options {Object} Options for this instance. +// Constructor function for the File transport object responsible +// for persisting log messages and metadata to one or more files. +// +var File = exports.File = function (options) { + var self = this; + Transport.call(this, options); + + // + // Helper function which throws an `Error` in the event + // that any of the rest of the arguments is present in `options`. + // + function throwIf (target /*, illegal... */) { + Array.prototype.slice.call(arguments, 1).forEach(function (name) { + if (options[name]) { + throw new Error('Cannot set ' + name + ' and ' + target + 'together'); + } + }); + } + + if (options.filename || options.dirname) { + throwIf('filename or dirname', 'stream'); + this._basename = this.filename = options.filename + ? path.basename(options.filename) + : 'winston.log'; + + this.dirname = options.dirname || path.dirname(options.filename); + this.options = options.options || { flags: 'a' }; + + // + // "24 bytes" is maybe a good value for logging lines. + // + this.options.highWaterMark = this.options.highWaterMark || 24; + } + else if (options.stream) { + throwIf('stream', 'filename', 'maxsize'); + this._stream = options.stream; + this._isStreams2 = isWritable(this._stream); + this._stream.on('error', function(error){ + self.emit('error', error); + }); + // + // We need to listen for drain events when + // write() returns false. This can make node + // mad at times. + // + this._stream.setMaxListeners(Infinity); + } + else { + throw new Error('Cannot log to file without filename or stream.'); + } + + this.json = options.json !== false; + this.logstash = options.logstash || false; + this.colorize = options.colorize || false; + this.maxsize = options.maxsize || null; + this.rotationFormat = options.rotationFormat || false; + this.zippedArchive = options.zippedArchive || false; + this.maxFiles = options.maxFiles || null; + this.prettyPrint = options.prettyPrint || false; + this.label = options.label || null; + this.timestamp = options.timestamp != null ? options.timestamp : true; + this.eol = options.eol || os.EOL; + this.tailable = options.tailable || false; + this.depth = options.depth || null; + this.showLevel = options.showLevel === undefined ? true : options.showLevel; + this.maxRetries = options.maxRetries || 2; + + if (this.json) { + this.stringify = options.stringify; + } + + // + // Internal state variables representing the number + // of files this instance has created and the current + // size (in bytes) of the current logfile. + // + this._size = 0; + this._created = 0; + this._buffer = []; + this._draining = false; + this._opening = false; + this._failures = 0; + this._archive = null; +}; + +// +// Inherit from `winston.Transport`. +// +util.inherits(File, Transport); + +// +// Expose the name of this Transport on the prototype +// +File.prototype.name = 'file'; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +File.prototype.log = function (level, msg, meta, callback) { + if (this.silent) { + return callback(null, true); + } + + // + // If failures exceeds maxRetries then we can't access the + // stream. In this case we need to perform a noop and return + // an error. + // + if (this._failures >= this.maxRetries) { + return callback(new Error('Transport is in a failed state.')); + } + + var self = this; + + if (typeof msg !== 'string') { + msg = '' + msg; + } + + var output = common.log({ + level: level, + message: msg, + meta: meta, + json: this.json, + logstash: this.logstash, + colorize: this.colorize, + prettyPrint: this.prettyPrint, + timestamp: this.timestamp, + showLevel: this.showLevel, + stringify: this.stringify, + label: this.label, + depth: this.depth, + formatter: this.formatter, + humanReadableUnhandledException: this.humanReadableUnhandledException + }); + + if (typeof output === 'string') { + output += this.eol; + } + + if (!this.filename) { + // + // If there is no `filename` on this instance then it was configured + // with a raw `WriteableStream` instance and we should not perform any + // size restrictions. + // + this._write(output, callback); + this._size += output.length; + this._lazyDrain(); + } + else { + this.open(function (err) { + if (err) { + // + // If there was an error enqueue the message + // + return self._buffer.push([output, callback]); + } + + self._write(output, callback); + self._size += output.length; + self._lazyDrain(); + }); + } +}; + +// +// ### function _write (data, cb) +// #### @data {String|Buffer} Data to write to the instance's stream. +// #### @cb {function} Continuation to respond to when complete. +// Write to the stream, ensure execution of a callback on completion. +// +File.prototype._write = function(data, callback) { + if (this._isStreams2) { + this._stream.write(data); + return callback && process.nextTick(function () { + callback(null, true); + }); + } + + // If this is a file write stream, we could use the builtin + // callback functionality, however, the stream is not guaranteed + // to be an fs.WriteStream. + var ret = this._stream.write(data); + if (!callback) return; + if (ret === false) { + return this._stream.once('drain', function() { + callback(null, true); + }); + } + process.nextTick(function () { + callback(null, true); + }); +}; + +// +// ### function query (options, callback) +// #### @options {Object} Loggly-like query options for this instance. +// #### @callback {function} Continuation to respond to when complete. +// Query the transport. Options object is optional. +// +File.prototype.query = function (options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var file = path.join(this.dirname, this.filename), + options = this.normalizeQuery(options), + buff = '', + results = [], + row = 0; + + var stream = fs.createReadStream(file, { + encoding: 'utf8' + }); + + stream.on('error', function (err) { + if (stream.readable) { + stream.destroy(); + } + if (!callback) return; + return err.code !== 'ENOENT' + ? callback(err) + : callback(null, results); + }); + + stream.on('data', function (data) { + var data = (buff + data).split(/\n+/), + l = data.length - 1, + i = 0; + + for (; i < l; i++) { + if (!options.start || row >= options.start) { + add(data[i]); + } + row++; + } + + buff = data[l]; + }); + + stream.on('close', function () { + if (buff) add(buff, true); + if (options.order === 'desc') { + results = results.reverse(); + } + if (callback) callback(null, results); + }); + + function add(buff, attempt) { + try { + var log = JSON.parse(buff); + if (check(log)) push(log); + } catch (e) { + if (!attempt) { + stream.emit('error', e); + } + } + } + + function push(log) { + if (options.rows && results.length >= options.rows) { + if (stream.readable) { + stream.destroy(); + } + return; + } + + if (options.fields) { + var obj = {}; + options.fields.forEach(function (key) { + obj[key] = log[key]; + }); + log = obj; + } + + results.push(log); + } + + function check(log) { + if (!log) return; + + if (typeof log !== 'object') return; + + var time = new Date(log.timestamp); + if ((options.from && time < options.from) + || (options.until && time > options.until)) { + return; + } + + return true; + } +}; + +// +// ### function stream (options) +// #### @options {Object} Stream options for this instance. +// Returns a log stream for this transport. Options object is optional. +// +File.prototype.stream = function (options) { + var file = path.join(this.dirname, this.filename), + options = options || {}, + stream = new Stream; + + var tail = { + file: file, + start: options.start + }; + + stream.destroy = common.tailFile(tail, function (err, line) { + + if(err){ + return stream.emit('error',err); + } + + try { + stream.emit('data', line); + line = JSON.parse(line); + stream.emit('log', line); + } catch (e) { + stream.emit('error', e); + } + }); + + return stream; +}; + +// +// ### function open (callback) +// #### @callback {function} Continuation to respond to when complete +// Checks to see if a new file needs to be created based on the `maxsize` +// (if any) and the current size of the file used. +// +File.prototype.open = function (callback) { + if (this.opening) { + // + // If we are already attempting to open the next + // available file then respond with a value indicating + // that the message should be buffered. + // + return callback(true); + } + else if (!this._stream || (this.maxsize && this._size >= this.maxsize)) { + // + // If we dont have a stream or have exceeded our size, then create + // the next stream and respond with a value indicating that + // the message should be buffered. + // + callback(true); + return this._createStream(); + } + + this._archive = this.zippedArchive ? this._stream.path : null; + + // + // Otherwise we have a valid (and ready) stream. + // + callback(); +}; + +// +// ### function close () +// Closes the stream associated with this instance. +// +File.prototype.close = function () { + var self = this; + + if (this._stream) { + this._stream.end(); + this._stream.destroySoon(); + + this._stream.once('finish', function () { + self.emit('flush'); + self.emit('closed'); + }); + } +}; + +// +// ### function flush () +// Flushes any buffered messages to the current `stream` +// used by this instance. +// +File.prototype.flush = function () { + var self = this; + + // If nothing to flush, there will be no "flush" event from native stream + // Thus, the "open" event will never be fired (see _createStream.createAndFlush function) + // That means, self.opening will never set to false and no logs will be written to disk + if (!this._buffer.length) { + return self.emit('flush'); + } + + // + // Iterate over the `_buffer` of enqueued messaged + // and then write them to the newly created stream. + // + this._buffer.forEach(function (item) { + var str = item[0], + callback = item[1]; + + process.nextTick(function () { + self._write(str, callback); + self._size += str.length; + }); + }); + + // + // Quickly truncate the `_buffer` once the write operations + // have been started + // + self._buffer.length = 0; + + // + // When the stream has drained we have flushed + // our buffer. + // + self._stream.once('drain', function () { + self.emit('flush'); + self.emit('logged'); + }); +}; + +// +// ### @private function _createStream () +// Attempts to open the next appropriate file for this instance +// based on the common state (such as `maxsize` and `_basename`). +// +File.prototype._createStream = function () { + var self = this; + this.opening = true; + + (function checkFile (target) { + var fullname = path.join(self.dirname, target); + + // + // Creates the `WriteStream` and then flushes any + // buffered messages. + // + function createAndFlush (size) { + if (self._stream) { + self._stream.end(); + self._stream.destroySoon(); + } + + self._size = size; + self.filename = target; + self._stream = fs.createWriteStream(fullname, self.options); + self._isStreams2 = isWritable(self._stream); + self._stream.on('error', function(error){ + if (self._failures < self.maxRetries) { + self._createStream(); + self._failures++; + } + else { + self.emit('error', error); + } + }); + // + // We need to listen for drain events when + // write() returns false. This can make node + // mad at times. + // + self._stream.setMaxListeners(Infinity); + + // + // When the current stream has finished flushing + // then we can be sure we have finished opening + // and thus can emit the `open` event. + // + self.once('flush', function () { + // Because "flush" event is based on native stream "drain" event, + // logs could be written inbetween "self.flush()" and here + // Therefore, we need to flush again to make sure everything is flushed + self.flush(); + + self.opening = false; + self.emit('open', fullname); + }); + // + // Remark: It is possible that in the time it has taken to find the + // next logfile to be written more data than `maxsize` has been buffered, + // but for sensible limits (10s - 100s of MB) this seems unlikely in less + // than one second. + // + self.flush(); + compressFile(); + } + + function compressFile() { + if (self._archive) { + var gzip = zlib.createGzip(); + + var inp = fs.createReadStream(String(self._archive)); + var out = fs.createWriteStream(self._archive + '.gz'); + + inp.pipe(gzip).pipe(out); + + fs.unlink(String(self._archive)); + self._archive = ''; + } + } + + fs.stat(fullname, function (err, stats) { + if (err) { + if (err.code !== 'ENOENT') { + return self.emit('error', err); + } + return createAndFlush(0); + } + + if (!stats || (self.maxsize && stats.size >= self.maxsize)) { + // + // If `stats.size` is greater than the `maxsize` for + // this instance then try again + // + return self._incFile(function() { + checkFile(self._getFile()); + }); + } + + createAndFlush(stats.size); + }); + })(this._getFile()); +}; + + +File.prototype._incFile = function (callback) { + var ext = path.extname(this._basename), + basename = path.basename(this._basename, ext), + oldest, + target; + + if (!this.tailable) { + this._created += 1; + this._checkMaxFilesIncrementing(ext, basename, callback); + } + else { + this._checkMaxFilesTailable(ext, basename, callback); + } +}; + +// +// ### @private function _getFile () +// Gets the next filename to use for this instance +// in the case that log filesizes are being capped. +// +File.prototype._getFile = function () { + var ext = path.extname(this._basename), + basename = path.basename(this._basename, ext); + + // + // Caveat emptor (indexzero): rotationFormat() was broken by design + // when combined with max files because the set of files to unlink + // is never stored. + // + return !this.tailable && this._created + ? basename + (this.rotationFormat ? this.rotationFormat() : this._created) + ext + : basename + ext; +}; + +// +// ### @private function _checkMaxFilesIncrementing () +// Increment the number of files created or +// checked by this instance. +// +File.prototype._checkMaxFilesIncrementing = function (ext, basename, callback) { + var oldest, target, + self = this; + + if (self.zippedArchive) { + self._archive = path.join(self.dirname, basename + + ((self._created === 1) ? '' : self._created-1) + + ext); + } + + + // Check for maxFiles option and delete file + if (!self.maxFiles || self._created < self.maxFiles) { + return callback(); + } + + oldest = self._created - self.maxFiles; + target = path.join(self.dirname, basename + (oldest !== 0 ? oldest : '') + ext + + (self.zippedArchive ? '.gz' : '')); + fs.unlink(target, callback); +}; + +// +// ### @private function _checkMaxFilesTailable () +// +// Roll files forward based on integer, up to maxFiles. +// e.g. if base if file.log and it becomes oversized, roll +// to file1.log, and allow file.log to be re-used. If +// file is oversized again, roll file1.log to file2.log, +// roll file.log to file1.log, and so on. +File.prototype._checkMaxFilesTailable = function (ext, basename, callback) { + var tasks = [], + self = this; + + if (!this.maxFiles) + return; + + for (var x = this.maxFiles - 1; x > 0; x--) { + tasks.push(function (i) { + return function (cb) { + var tmppath = path.join(self.dirname, basename + (i - 1) + ext + + (self.zippedArchive ? '.gz' : '')); + fs.exists(tmppath, function (exists) { + if (!exists) { + return cb(null); + } + + fs.rename(tmppath, path.join(self.dirname, basename + i + ext + + (self.zippedArchive ? '.gz' : '')), cb); + }); + }; + }(x)); + } + + if (self.zippedArchive) { + self._archive = path.join(self.dirname, basename + 1 + ext); + } + async.series(tasks, function (err) { + fs.rename( + path.join(self.dirname, basename + ext), + path.join(self.dirname, basename + 1 + ext), + callback + ); + }); +}; + +// +// ### @private function _lazyDrain () +// Lazily attempts to emit the `logged` event when `this.stream` has +// drained. This is really just a simple mutex that only works because +// Node.js is single-threaded. +// +File.prototype._lazyDrain = function () { + var self = this; + + if (!this._draining && this._stream) { + this._draining = true; + + this._stream.once('drain', function () { + this._draining = false; + self.emit('logged'); + }); + } +}; diff --git a/node_modules/winston/lib/winston/transports/http.js b/node_modules/winston/lib/winston/transports/http.js new file mode 100644 index 0000000..f7e1af6 --- /dev/null +++ b/node_modules/winston/lib/winston/transports/http.js @@ -0,0 +1,232 @@ +var util = require('util'), + winston = require('../../winston'), + http = require('http'), + https = require('https'), + Stream = require('stream').Stream, + Transport = require('./transport').Transport; + +// +// ### function Http (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Http transport object responsible +// for persisting log messages and metadata to a terminal or TTY. +// +var Http = exports.Http = function (options) { + Transport.call(this, options); + options = options || {}; + + this.name = 'http'; + this.ssl = !!options.ssl; + this.host = options.host || 'localhost'; + this.port = options.port; + this.auth = options.auth; + this.path = options.path || ''; + + if (!this.port) { + this.port = this.ssl ? 443 : 80; + } +}; + +util.inherits(Http, winston.Transport); + +// +// Expose the name of this Transport on the prototype +// +Http.prototype.name = 'http'; + +// +// ### function _request (options, callback) +// #### @callback {function} Continuation to respond to when complete. +// Make a request to a winstond server or any http server which can +// handle json-rpc. +// +Http.prototype._request = function (options, callback) { + options = options || {}; + + var auth = options.auth || this.auth, + path = options.path || this.path || '', + req; + + delete options.auth; + delete options.path; + + // Prepare options for outgoing HTTP request + req = (this.ssl ? https : http).request({ + host: this.host, + port: this.port, + path: '/' + path.replace(/^\//, ''), + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + auth: (auth) ? auth.username + ':' + auth.password : '' + }); + + req.on('error', callback); + req.on('response', function (res) { + res.on('end', function () { + callback(null, res); + }); + + res.resume(); + }); + + req.end(new Buffer(JSON.stringify(options), 'utf8')); +}; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +Http.prototype.log = function (level, msg, meta, callback) { + var self = this; + + if (typeof meta === 'function') { + callback = meta; + meta = {}; + } + + var options = { + method: 'collect', + params: { + level: level, + message: msg, + meta: meta + } + }; + + if (meta) { + if (meta.path) { + options.path = meta.path; + delete meta.path; + } + + if (meta.auth) { + options.auth = meta.auth; + delete meta.auth; + } + } + + this._request(options, function (err, res) { + if (res && res.statusCode !== 200) { + err = new Error('HTTP Status Code: ' + res.statusCode); + } + + if (err) return callback(err); + + // TODO: emit 'logged' correctly, + // keep track of pending logs. + self.emit('logged'); + + if (callback) callback(null, true); + }); +}; + +// +// ### function query (options, callback) +// #### @options {Object} Loggly-like query options for this instance. +// #### @callback {function} Continuation to respond to when complete. +// Query the transport. Options object is optional. +// +Http.prototype.query = function (options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var self = this, + options = this.normalizeQuery(options); + + options = { + method: 'query', + params: options + }; + + if (options.params.path) { + options.path = options.params.path; + delete options.params.path; + } + + if (options.params.auth) { + options.auth = options.params.auth; + delete options.params.auth; + } + + this._request(options, function (err, res, body) { + if (res && res.statusCode !== 200) { + err = new Error('HTTP Status Code: ' + res.statusCode); + } + + if (err) return callback(err); + + if (typeof body === 'string') { + try { + body = JSON.parse(body); + } catch (e) { + return callback(e); + } + } + + callback(null, body); + }); +}; + +// +// ### function stream (options) +// #### @options {Object} Stream options for this instance. +// Returns a log stream for this transport. Options object is optional. +// +Http.prototype.stream = function (options) { + options = options || {}; + + var self = this, + stream = new Stream, + req, + buff; + + stream.destroy = function () { + req.destroy(); + }; + + options = { + method: 'stream', + params: options + }; + + if (options.params.path) { + options.path = options.params.path; + delete options.params.path; + } + + if (options.params.auth) { + options.auth = options.params.auth; + delete options.params.auth; + } + + req = this._request(options); + buff = ''; + + req.on('data', function (data) { + var data = (buff + data).split(/\n+/), + l = data.length - 1, + i = 0; + + for (; i < l; i++) { + try { + stream.emit('log', JSON.parse(data[i])); + } catch (e) { + stream.emit('error', e); + } + } + + buff = data[l]; + }); + + req.on('error', function (err) { + stream.emit('error', err); + }); + + return stream; +}; diff --git a/node_modules/winston/lib/winston/transports/memory.js b/node_modules/winston/lib/winston/transports/memory.js new file mode 100644 index 0000000..e4f562e --- /dev/null +++ b/node_modules/winston/lib/winston/transports/memory.js @@ -0,0 +1,89 @@ +var events = require('events'), + util = require('util'), + common = require('../common'), + Transport = require('./transport').Transport; + +// +// ### function Memory (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Memory transport object responsible +// for persisting log messages and metadata to a memory array of messages. +// +var Memory = exports.Memory = function (options) { + Transport.call(this, options); + options = options || {}; + + this.errorOutput = []; + this.writeOutput = []; + + this.json = options.json || false; + this.colorize = options.colorize || false; + this.prettyPrint = options.prettyPrint || false; + this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false; + this.showLevel = options.showLevel === undefined ? true : options.showLevel; + this.label = options.label || null; + this.depth = options.depth || null; + + if (this.json) { + this.stringify = options.stringify || function (obj) { + return JSON.stringify(obj, null, 2); + }; + } +}; + +// +// Inherit from `winston.Transport`. +// +util.inherits(Memory, Transport); + +// +// Expose the name of this Transport on the prototype +// +Memory.prototype.name = 'memory'; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +Memory.prototype.log = function (level, msg, meta, callback) { + if (this.silent) { + return callback(null, true); + } + + var self = this, + output; + + output = common.log({ + colorize: this.colorize, + json: this.json, + level: level, + message: msg, + meta: meta, + stringify: this.stringify, + timestamp: this.timestamp, + prettyPrint: this.prettyPrint, + raw: this.raw, + label: this.label, + depth: this.depth, + formatter: this.formatter, + humanReadableUnhandledException: this.humanReadableUnhandledException + }); + + if (level === 'error' || level === 'debug') { + this.errorOutput.push(output); + } else { + this.writeOutput.push(output); + } + + self.emit('logged'); + callback(null, true); +}; + +Memory.prototype.clearLogs = function () { + this.errorOutput = []; + this.writeOutput = []; +}; diff --git a/node_modules/winston/lib/winston/transports/transport.js b/node_modules/winston/lib/winston/transports/transport.js new file mode 100644 index 0000000..d279d00 --- /dev/null +++ b/node_modules/winston/lib/winston/transports/transport.js @@ -0,0 +1,135 @@ +/* + * transport.js: Base Transport object for all Winston transports. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var events = require('events'), + util = require('util'); + +// +// ### function Transport (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Tranport object responsible +// base functionality for all winston transports. +// +var Transport = exports.Transport = function (options) { + events.EventEmitter.call(this); + + options = options || {}; + this.silent = options.silent || false; + this.raw = options.raw || false; + this.name = options.name || this.name; + this.formatter = options.formatter; + + // + // Do not set a default level. When `level` is falsey on any + // `Transport` instance, any `Logger` instance uses the + // configured level (instead of the Transport level) + // + this.level = options.level; + + this.handleExceptions = options.handleExceptions || false; + this.exceptionsLevel = options.exceptionsLevel || 'error'; + this.humanReadableUnhandledException = options.humanReadableUnhandledException || false; +}; + +// +// Inherit from `events.EventEmitter`. +// +util.inherits(Transport, events.EventEmitter); + +// +// ### function formatQuery (query) +// #### @query {string|Object} Query to format +// Formats the specified `query` Object (or string) to conform +// with the underlying implementation of this transport. +// +Transport.prototype.formatQuery = function (query) { + return query; +}; + +// +// ### function normalizeQuery (query) +// #### @options {string|Object} Query to normalize +// Normalize options for query +// +Transport.prototype.normalizeQuery = function (options) { + // + // Use options similar to loggly. + // [See Loggly Search API](http://wiki.loggly.com/retrieve_events#optional) + // + + options = options || {}; + + // limit + options.rows = options.rows || options.limit || 10; + + // starting row offset + options.start = options.start || 0; + + // now + options.until = options.until || new Date; + if (typeof options.until !== 'object') { + options.until = new Date(options.until); + } + + // now - 24 + options.from = options.from || (options.until - (24 * 60 * 60 * 1000)); + if (typeof options.from !== 'object') { + options.from = new Date(options.from); + } + + + // 'asc' or 'desc' + options.order = options.order || 'desc'; + + // which fields to select + options.fields = options.fields; + + return options; +}; + +// +// ### function formatResults (results, options) +// #### @results {Object|Array} Results returned from `.query`. +// #### @options {Object} **Optional** Formatting options +// Formats the specified `results` with the given `options` accordinging +// to the implementation of this transport. +// +Transport.prototype.formatResults = function (results, options) { + return results; +}; + +// +// ### function logException (msg, meta, callback) +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Logs the specified `msg`, `meta` and responds to the callback once the log +// operation is complete to ensure that the event loop will not exit before +// all logging has completed. +// +Transport.prototype.logException = function (msg, meta, callback) { + var self = this, + called; + + if (this.silent) { + return callback(); + } + + function onComplete () { + if (!called) { + called = true; + self.removeListener('logged', onComplete); + self.removeListener('error', onComplete); + callback(); + } + } + + this.once('logged', onComplete); + this.once('error', onComplete); + this.log(self.exceptionsLevel, msg, meta, function () { }); +}; diff --git a/node_modules/winston/node_modules/async/.jshintrc b/node_modules/winston/node_modules/async/.jshintrc new file mode 100644 index 0000000..172f491 --- /dev/null +++ b/node_modules/winston/node_modules/async/.jshintrc @@ -0,0 +1,24 @@ +{ + // Enforcing options + "eqeqeq": false, + "forin": true, + "indent": 4, + "noarg": true, + "undef": true, + "trailing": true, + "evil": true, + "laxcomma": true, + + // Relaxing options + "onevar": false, + "asi": false, + "eqnull": true, + "expr": false, + "loopfunc": true, + "sub": true, + "browser": true, + "node": true, + "globals": { + "define": true + } +} diff --git a/node_modules/winston/node_modules/async/.travis.yml b/node_modules/winston/node_modules/async/.travis.yml new file mode 100644 index 0000000..6064ca0 --- /dev/null +++ b/node_modules/winston/node_modules/async/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/winston/node_modules/async/CHANGELOG.md b/node_modules/winston/node_modules/async/CHANGELOG.md new file mode 100644 index 0000000..7d39c37 --- /dev/null +++ b/node_modules/winston/node_modules/async/CHANGELOG.md @@ -0,0 +1,16 @@ +# v1.0.0 + +No known breaking changes, we are simply complying with semver from here on out. + +Changes: + +- Start using a changelog! +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) (#168 #704 #321) +- Detect deadlocks in `auto` (#663) +- Better support for require.js (#527) +- Throw if queue created with concurrency `0` (#714) +- Fix unneeded iteration in `queue.resume()` (#758) +- Guard against timer mocking overriding `setImmediate` (#609 #611) +- Miscellaneous doc fixes (#542 #596 #615 #628 #631 #690 #729) +- Use single noop function internally (#546) +- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/node_modules/winston/node_modules/async/LICENSE b/node_modules/winston/node_modules/async/LICENSE new file mode 100644 index 0000000..8f29698 --- /dev/null +++ b/node_modules/winston/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2014 Caolan McMahon + +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. diff --git a/node_modules/winston/node_modules/async/README.md b/node_modules/winston/node_modules/async/README.md new file mode 100644 index 0000000..7e5e15f --- /dev/null +++ b/node_modules/winston/node_modules/async/README.md @@ -0,0 +1,1720 @@ +# Async.js + +[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) +[![NPM version](http://img.shields.io/npm/v/async.svg)](https://www.npmjs.org/package/async) + + +Async is a utility module which provides straight-forward, powerful functions +for working with asynchronous JavaScript. Although originally designed for +use with [Node.js](http://nodejs.org) and installable via `npm install async`, +it can also be used directly in the browser. + +Async is also installable via: + +- [bower](http://bower.io/): `bower install async` +- [component](https://github.com/component/component): `component install + caolan/async` +- [jam](http://jamjs.org/): `jam install async` +- [spm](http://spmjs.io/): `spm install async` + +Async provides around 20 functions that include the usual 'functional' +suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns +for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these +functions assume you follow the Node.js convention of providing a single +callback as the last argument of your `async` function. + + +## Quick Examples + +```javascript +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); + +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); + +async.parallel([ + function(){ ... }, + function(){ ... } +], callback); + +async.series([ + function(){ ... }, + function(){ ... } +]); +``` + +There are many more functions available so take a look at the docs below for a +full list. This module aims to be comprehensive, so if you feel anything is +missing please create a GitHub issue for it. + +## Common Pitfalls + +### Binding a context to an iterator + +This section is really about `bind`, not about `async`. If you are wondering how to +make `async` execute your iterators in a given context, or are confused as to why +a method of another library isn't working as an iterator, study this example: + +```js +// Here is a simple object with an (unnecessarily roundabout) squaring method +var AsyncSquaringLibrary = { + squareExponent: 2, + square: function(number, callback){ + var result = Math.pow(number, this.squareExponent); + setTimeout(function(){ + callback(null, result); + }, 200); + } +}; + +async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){ + // result is [NaN, NaN, NaN] + // This fails because the `this.squareExponent` expression in the square + // function is not evaluated in the context of AsyncSquaringLibrary, and is + // therefore undefined. +}); + +async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){ + // result is [1, 4, 9] + // With the help of bind we can attach a context to the iterator before + // passing it to async. Now the square function will be executed in its + // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent` + // will be as expected. +}); +``` + +## Download + +The source is available for download from +[GitHub](https://github.com/caolan/async/blob/master/lib/async.js). +Alternatively, you can install using Node Package Manager (`npm`): + + npm install async + +As well as using Bower: + + bower install async + +__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed + +## In the Browser + +So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. + +Usage: + +```html + + +``` + +## Documentation + +### Collections + +* [`each`](#each) +* [`eachSeries`](#eachSeries) +* [`eachLimit`](#eachLimit) +* [`forEachOf`](#forEachOf) +* [`forEachOfSeries`](#forEachOfSeries) +* [`forEachOfLimit`](#forEachOfLimit) +* [`map`](#map) +* [`mapSeries`](#mapSeries) +* [`mapLimit`](#mapLimit) +* [`filter`](#filter) +* [`filterSeries`](#filterSeries) +* [`reject`](#reject) +* [`rejectSeries`](#rejectSeries) +* [`reduce`](#reduce) +* [`reduceRight`](#reduceRight) +* [`detect`](#detect) +* [`detectSeries`](#detectSeries) +* [`sortBy`](#sortBy) +* [`some`](#some) +* [`every`](#every) +* [`concat`](#concat) +* [`concatSeries`](#concatSeries) + +### Control Flow + +* [`series`](#seriestasks-callback) +* [`parallel`](#parallel) +* [`parallelLimit`](#parallellimittasks-limit-callback) +* [`whilst`](#whilst) +* [`doWhilst`](#doWhilst) +* [`until`](#until) +* [`doUntil`](#doUntil) +* [`forever`](#forever) +* [`waterfall`](#waterfall) +* [`compose`](#compose) +* [`seq`](#seq) +* [`applyEach`](#applyEach) +* [`applyEachSeries`](#applyEachSeries) +* [`queue`](#queue) +* [`priorityQueue`](#priorityQueue) +* [`cargo`](#cargo) +* [`auto`](#auto) +* [`retry`](#retry) +* [`iterator`](#iterator) +* [`apply`](#apply) +* [`nextTick`](#nextTick) +* [`times`](#times) +* [`timesSeries`](#timesSeries) + +### Utils + +* [`memoize`](#memoize) +* [`unmemoize`](#unmemoize) +* [`log`](#log) +* [`dir`](#dir) +* [`noConflict`](#noConflict) + + +## Collections + + + +### each(arr, iterator, callback) + +Applies the function `iterator` to each item in `arr`, in parallel. +The `iterator` is called with an item from the list, and a callback for when it +has finished. If the `iterator` passes an error to its `callback`, the main +`callback` (for the `each` function) is immediately called with the error. + +Note, that since this function applies `iterator` to each item in parallel, +there is no guarantee that the iterator functions will complete in order. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the `callback` should be run without + arguments or with an explicit `null` argument. The array index is not passed + to the iterator. If you need the index, use [`forEachOf`](#forEachOf). +* `callback(err)` - A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Examples__ + + +```js +// assuming openFiles is an array of file names and saveFile is a function +// to save the modified contents of that file: + +async.each(openFiles, saveFile, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +```js +// assuming openFiles is an array of file names + +async.each(openFiles, function(file, callback) { + + // Perform operation on file here. + console.log('Processing file ' + file); + + if( file.length > 32 ) { + console.log('This file name is too long'); + callback('File name too long'); + } else { + // Do work to process file here + console.log('File processed'); + callback(); + } +}, function(err){ + // if any of the file processing produced an error, err would equal that error + if( err ) { + // One of the iterations produced an error. + // All processing will now stop. + console.log('A file failed to process'); + } else { + console.log('All files have been processed successfully'); + } +}); +``` + +--------------------------------------- + + + +### eachSeries(arr, iterator, callback) + +The same as [`each`](#each), only `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +This means the `iterator` functions will complete in order. + + +--------------------------------------- + + + +### eachLimit(arr, limit, iterator, callback) + +The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously +running at any time. + +Note that the items in `arr` are not processed in batches, so there is no guarantee that +the first `limit` `iterator` functions will complete before any others are started. + +__Arguments__ + +* `arr` - An array to iterate over. +* `limit` - The maximum number of `iterator`s to run at any time. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the callback should be run without + arguments or with an explicit `null` argument. +* `callback(err)` - A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Example__ + +```js +// Assume documents is an array of JSON objects and requestApi is a +// function that interacts with a rate-limited REST api. + +async.eachLimit(documents, 20, requestApi, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +--------------------------------------- + + + + +### forEachOf(obj, iterator, callback) + +Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator. + +__Arguments__ + +* `obj` - An object or array to iterate over. +* `iterator(item, key, callback)` - A function to apply to each item in `obj`. +The `key` is the item's key, or index in the case of an array. The iterator is +passed a `callback(err)` which must be called once it has completed. If no +error has occurred, the callback should be run without arguments or with an +explicit `null` argument. +* `callback(err)` - A callback which is called when all `iterator` functions have finished, or an error occurs. + +__Example__ + +```js +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, function (value, key, callback) { + fs.readFile(__dirname + value, "utf8", function (err, data) { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }) +}, function (err) { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}) +``` + +--------------------------------------- + + + + +### forEachOfSeries(obj, iterator, callback) + +Like [`forEachOf`](#forEachOf), except only one `iterator` is run at a time. The order of execution is not guaranteed for objects, but it will be guaranteed for arrays. + +--------------------------------------- + + + + +### forEachOfLimit(obj, limit, iterator, callback) + +Like [`forEachOf`](#forEachOf), except the number of `iterator`s running at a given time is controlled by `limit`. + + +--------------------------------------- + + +### map(arr, iterator, callback) + +Produces a new array of values by mapping each value in `arr` through +the `iterator` function. The `iterator` is called with an item from `arr` and a +callback for when it has finished processing. Each of these callback takes 2 arguments: +an `error`, and the transformed item from `arr`. If `iterator` passes an error to its +callback, the main `callback` (for the `map` function) is immediately called with the error. + +Note, that since this function applies the `iterator` to each item in parallel, +there is no guarantee that the `iterator` functions will complete in order. +However, the results array will be in the same order as the original `arr`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - A callback which is called when all `iterator` + functions have finished, or an error occurs. Results is an array of the + transformed items from the `arr`. + +__Example__ + +```js +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +--------------------------------------- + + +### mapSeries(arr, iterator, callback) + +The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + + +--------------------------------------- + + +### mapLimit(arr, limit, iterator, callback) + +The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously +running at any time. + +Note that the items are not processed in batches, so there is no guarantee that +the first `limit` `iterator` functions will complete before any others are started. + +__Arguments__ + +* `arr` - An array to iterate over. +* `limit` - The maximum number of `iterator`s to run at any time. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - A callback which is called when all `iterator` + calls have finished, or an error occurs. The result is an array of the + transformed items from the original `arr`. + +__Example__ + +```js +async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +--------------------------------------- + + + +### filter(arr, iterator, callback) + +__Alias:__ `select` + +Returns a new array of all the values in `arr` which pass an async truth test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. This operation is +performed in parallel, but the results array will be in the same order as the +original. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The `iterator` is passed a `callback(truthValue)`, which must be called with a + boolean argument once it has completed. +* `callback(results)` - A callback which is called after all the `iterator` + functions have finished. + +__Example__ + +```js +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); +``` + +--------------------------------------- + + + +### filterSeries(arr, iterator, callback) + +__Alias:__ `selectSeries` + +The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + +--------------------------------------- + + +### reject(arr, iterator, callback) + +The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. + +--------------------------------------- + + +### rejectSeries(arr, iterator, callback) + +The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr` +in series. + + +--------------------------------------- + + +### reduce(arr, memo, iterator, callback) + +__Aliases:__ `inject`, `foldl` + +Reduces `arr` into a single value using an async `iterator` to return +each successive step. `memo` is the initial state of the reduction. +This function only operates in series. + +For performance reasons, it may make sense to split a call to this function into +a parallel map, and then use the normal `Array.prototype.reduce` on the results. +This function is for situations where each step in the reduction needs to be async; +if you can get the data before reducing it, then it's probably a good idea to do so. + +__Arguments__ + +* `arr` - An array to iterate over. +* `memo` - The initial state of the reduction. +* `iterator(memo, item, callback)` - A function applied to each item in the + array to produce the next step in the reduction. The `iterator` is passed a + `callback(err, reduction)` which accepts an optional error as its first + argument, and the state of the reduction as the second. If an error is + passed to the callback, the reduction is stopped and the main `callback` is + immediately called with the error. +* `callback(err, result)` - A callback which is called after all the `iterator` + functions have finished. Result is the reduced value. + +__Example__ + +```js +async.reduce([1,2,3], 0, function(memo, item, callback){ + // pointless async: + process.nextTick(function(){ + callback(null, memo + item) + }); +}, function(err, result){ + // result is now equal to the last value of memo, which is 6 +}); +``` + +--------------------------------------- + + +### reduceRight(arr, memo, iterator, callback) + +__Alias:__ `foldr` + +Same as [`reduce`](#reduce), only operates on `arr` in reverse order. + + +--------------------------------------- + + +### detect(arr, iterator, callback) + +Returns the first value in `arr` that passes an async truth test. The +`iterator` is applied in parallel, meaning the first iterator to return `true` will +fire the detect `callback` with that result. That means the result might not be +the first item in the original `arr` (in terms of order) that passes the test. + +If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries). + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The iterator is passed a `callback(truthValue)` which must be called with a + boolean argument once it has completed. +* `callback(result)` - A callback which is called as soon as any iterator returns + `true`, or after all the `iterator` functions have finished. Result will be + the first item in the array that passes the truth test (iterator) or the + value `undefined` if none passed. + +__Example__ + +```js +async.detect(['file1','file2','file3'], fs.exists, function(result){ + // result now equals the first file in the list that exists +}); +``` + +--------------------------------------- + + +### detectSeries(arr, iterator, callback) + +The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr` +in series. This means the result is always the first in the original `arr` (in +terms of array order) that passes the truth test. + + +--------------------------------------- + + +### sortBy(arr, iterator, callback) + +Sorts a list by the results of running each `arr` value through an async `iterator`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, sortValue)` which must be called once it + has completed with an error (which can be `null`) and a value to use as the sort + criteria. +* `callback(err, results)` - A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is the items from + the original `arr` sorted by the values returned by the `iterator` calls. + +__Example__ + +```js +async.sortBy(['file1','file2','file3'], function(file, callback){ + fs.stat(file, function(err, stats){ + callback(err, stats.mtime); + }); +}, function(err, results){ + // results is now the original array of files sorted by + // modified date +}); +``` + +__Sort Order__ + +By modifying the callback parameter the sorting order can be influenced: + +```js +//ascending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x); +}, function(err,result){ + //result callback +} ); + +//descending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x*-1); //<- x*-1 instead of x, turns the order around +}, function(err,result){ + //result callback +} ); +``` + +--------------------------------------- + + +### some(arr, iterator, callback) + +__Alias:__ `any` + +Returns `true` if at least one element in the `arr` satisfies an async test. +_The callback for each iterator call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. Once any iterator +call returns `true`, the main `callback` is immediately called. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a callback(truthValue) which must be + called with a boolean argument once it has completed. +* `callback(result)` - A callback which is called as soon as any iterator returns + `true`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + +__Example__ + +```js +async.some(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then at least one of the files exists +}); +``` + +--------------------------------------- + + +### every(arr, iterator, callback) + +__Alias:__ `all` + +Returns `true` if every element in `arr` satisfies an async test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a callback(truthValue) which must be + called with a boolean argument once it has completed. +* `callback(result)` - A callback which is called after all the `iterator` + functions have finished. Result will be either `true` or `false` depending on + the values of the async tests. + +__Example__ + +```js +async.every(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then every file exists +}); +``` + +--------------------------------------- + + +### concat(arr, iterator, callback) + +Applies `iterator` to each item in `arr`, concatenating the results. Returns the +concatenated list. The `iterator`s are called in parallel, and the results are +concatenated as they return. There is no guarantee that the results array will +be returned in the original order of `arr` passed to the `iterator` function. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, results)` which must be called once it + has completed with an error (which can be `null`) and an array of results. +* `callback(err, results)` - A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is an array containing + the concatenated results of the `iterator` function. + +__Example__ + +```js +async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ + // files is now a list of filenames that exist in the 3 directories +}); +``` + +--------------------------------------- + + +### concatSeries(arr, iterator, callback) + +Same as [`concat`](#concat), but executes in series instead of parallel. + + +## Control Flow + + +### series(tasks, [callback]) + +Run the functions in the `tasks` array in series, each one running once the previous +function has completed. If any functions in the series pass an error to its +callback, no more functions are run, and `callback` is immediately called with the value of the error. +Otherwise, `callback` receives an array of results when `tasks` have completed. + +It is also possible to use an object instead of an array. Each property will be +run as a function, and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`series`](#series). + +**Note** that while many implementations preserve the order of object properties, the +[ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) +explicitly states that + +> The mechanics and order of enumerating the properties is not specified. + +So if you rely on the order in which your series of functions are executed, and want +this to work on all platforms, consider using an array. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +__Example__ + +```js +async.series([ + function(callback){ + // do some stuff ... + callback(null, 'one'); + }, + function(callback){ + // do some more stuff ... + callback(null, 'two'); + } +], +// optional callback +function(err, results){ + // results is now equal to ['one', 'two'] +}); + + +// an example using an object instead of an array +async.series({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equal to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + + +### parallel(tasks, [callback]) + +Run the `tasks` array of functions in parallel, without waiting until the previous +function has completed. If any of the functions pass an error to its +callback, the main `callback` is immediately called with the value of the error. +Once the `tasks` have completed, the results are passed to the final `callback` as an +array. + +It is also possible to use an object instead of an array. Each property will be +run as a function and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`parallel`](#parallel). + + +__Arguments__ + +* `tasks` - An array or object containing functions to run. Each function is passed + a `callback(err, result)` which it must call on completion with an error `err` + (which can be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the task callbacks. + +__Example__ + +```js +async.parallel([ + function(callback){ + setTimeout(function(){ + callback(null, 'one'); + }, 200); + }, + function(callback){ + setTimeout(function(){ + callback(null, 'two'); + }, 100); + } +], +// optional callback +function(err, results){ + // the results array will equal ['one','two'] even though + // the second function had a shorter timeout. +}); + + +// an example using an object instead of an array +async.parallel({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equals to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + + +### parallelLimit(tasks, limit, [callback]) + +The same as [`parallel`](#parallel), only `tasks` are executed in parallel +with a maximum of `limit` tasks executing at any time. + +Note that the `tasks` are not executed in batches, so there is no guarantee that +the first `limit` tasks will complete before any others are started. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `limit` - The maximum number of `tasks` to run at any time. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +--------------------------------------- + + +### whilst(test, fn, callback) + +Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +__Arguments__ + +* `test()` - synchronous truth test to perform before each execution of `fn`. +* `fn(callback)` - A function which is called each time `test` passes. The function is + passed a `callback(err)`, which must be called once it has completed with an + optional `err` argument. +* `callback(err)` - A callback which is called after the test fails and repeated + execution of `fn` has stopped. + +__Example__ + +```js +var count = 0; + +async.whilst( + function () { return count < 5; }, + function (callback) { + count++; + setTimeout(callback, 1000); + }, + function (err) { + // 5 seconds have passed + } +); +``` + +--------------------------------------- + + +### doWhilst(fn, test, callback) + +The post-check version of [`whilst`](#whilst). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + +--------------------------------------- + + +### until(test, fn, callback) + +Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +The inverse of [`whilst`](#whilst). + +--------------------------------------- + + +### doUntil(fn, test, callback) + +Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. + +--------------------------------------- + + +### forever(fn, errback) + +Calls the asynchronous function `fn` with a callback parameter that allows it to +call itself again, in series, indefinitely. + +If an error is passed to the callback then `errback` is called with the +error, and execution stops, otherwise it will never be called. + +```js +async.forever( + function(next) { + // next is suitable for passing to things that need a callback(err [, whatever]); + // it will result in this function being called again. + }, + function(err) { + // if next is called with a value in its first parameter, it will appear + // in here as 'err', and execution will stop. + } +); +``` + +--------------------------------------- + + +### waterfall(tasks, [callback]) + +Runs the `tasks` array of functions in series, each passing their results to the next in +the array. However, if any of the `tasks` pass an error to their own callback, the +next function is not executed, and the main `callback` is immediately called with +the error. + +__Arguments__ + +* `tasks` - An array of functions to run, each function is passed a + `callback(err, result1, result2, ...)` it must call on completion. The first + argument is an error (which can be `null`) and any further arguments will be + passed as arguments in order to the next task. +* `callback(err, [results])` - An optional callback to run once all the functions + have completed. This will be passed the results of the last task's callback. + + + +__Example__ + +```js +async.waterfall([ + function(callback) { + callback(null, 'one', 'two'); + }, + function(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); + }, + function(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); + } +], function (err, result) { + // result now equals 'done' +}); +``` + +--------------------------------------- + +### compose(fn1, fn2...) + +Creates a function which is a composition of the passed asynchronous +functions. Each function consumes the return value of the function that +follows. Composing functions `f()`, `g()`, and `h()` would produce the result of +`f(g(h()))`, only this version uses callbacks to obtain the return values. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +function add1(n, callback) { + setTimeout(function () { + callback(null, n + 1); + }, 10); +} + +function mul3(n, callback) { + setTimeout(function () { + callback(null, n * 3); + }, 10); +} + +var add1mul3 = async.compose(mul3, add1); + +add1mul3(4, function (err, result) { + // result now equals 15 +}); +``` + +--------------------------------------- + +### seq(fn1, fn2...) + +Version of the compose function that is more natural to read. +Each function consumes the return value of the previous function. +It is the equivalent of [`compose`](#compose) with the arguments reversed. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* functions... - the asynchronous functions to compose + + +__Example__ + +```js +// Requires lodash (or underscore), express3 and dresende's orm2. +// Part of an app, that fetches cats of the logged user. +// This example uses `seq` function to avoid overnesting and error +// handling clutter. +app.get('/cats', function(request, response) { + var User = request.models.User; + async.seq( + _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + function(user, fn) { + user.getCats(fn); // 'getCats' has signature (callback(err, data)) + } + )(req.session.user_id, function (err, cats) { + if (err) { + console.error(err); + response.json({ status: 'error', message: err.message }); + } else { + response.json({ status: 'ok', message: 'Cats found', data: cats }); + } + }); +}); +``` + +--------------------------------------- + +### applyEach(fns, args..., callback) + +Applies the provided arguments to each function in the array, calling +`callback` after all functions have completed. If you only provide the first +argument, then it will return a function which lets you pass in the +arguments as if it were a single function call. + +__Arguments__ + +* `fns` - the asynchronous functions to all call with the same arguments +* `args...` - any number of separate arguments to pass to the function +* `callback` - the final argument should be the callback, called when all + functions have completed processing + + +__Example__ + +```js +async.applyEach([enableSearch, updateSchema], 'bucket', callback); + +// partial application example: +async.each( + buckets, + async.applyEach([enableSearch, updateSchema]), + callback +); +``` + +--------------------------------------- + + +### applyEachSeries(arr, args..., callback) + +The same as [`applyEach`](#applyEach) only the functions are applied in series. + +--------------------------------------- + + +### queue(worker, concurrency) + +Creates a `queue` object with the specified `concurrency`. Tasks added to the +`queue` are processed in parallel (up to the `concurrency` limit). If all +`worker`s are in progress, the task is queued until one becomes available. +Once a `worker` completes a `task`, that `task`'s callback is called. + +__Arguments__ + +* `worker(task, callback)` - An asynchronous function for processing a queued + task, which must call its `callback(err)` argument when finished, with an + optional `error` as an argument. +* `concurrency` - An `integer` for determining how many `worker` functions should be + run in parallel. + +__Queue objects__ + +The `queue` object returned by this function has the following properties and +methods: + +* `length()` - a function returning the number of items waiting to be processed. +* `started` - a function returning whether or not any items have been pushed and processed by the queue +* `running()` - a function returning the number of items currently being processed. +* `idle()` - a function returning false if there are items waiting or being processed, or true if not. +* `concurrency` - an integer for determining how many `worker` functions should be + run in parallel. This property can be changed after a `queue` is created to + alter the concurrency on-the-fly. +* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once + the `worker` has finished processing the task. Instead of a single task, a `tasks` array + can be submitted. The respective callback is used for every task in the list. +* `unshift(task, [callback])` - add a new task to the front of the `queue`. +* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, + and further tasks will be queued. +* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`. +* `paused` - a boolean for determining whether the queue is in a paused state +* `pause()` - a function that pauses the processing of tasks until `resume()` is called. +* `resume()` - a function that resumes the processing of queued tasks when the queue is paused. +* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle. + +__Example__ + +```js +// create a queue object with concurrency 2 + +var q = async.queue(function (task, callback) { + console.log('hello ' + task.name); + callback(); +}, 2); + + +// assign a callback +q.drain = function() { + console.log('all items have been processed'); +} + +// add some items to the queue + +q.push({name: 'foo'}, function (err) { + console.log('finished processing foo'); +}); +q.push({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); + +// add some items to the queue (batch-wise) + +q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { + console.log('finished processing item'); +}); + +// add some items to the front of the queue + +q.unshift({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); +``` + + +--------------------------------------- + + +### priorityQueue(worker, concurrency) + +The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects: + +* `push(task, priority, [callback])` - `priority` should be a number. If an array of + `tasks` is given, all tasks will be assigned the same priority. +* The `unshift` method was removed. + +--------------------------------------- + + +### cargo(worker, [payload]) + +Creates a `cargo` object with the specified payload. Tasks added to the +cargo will be processed altogether (up to the `payload` limit). If the +`worker` is in progress, the task is queued until it becomes available. Once +the `worker` has completed some tasks, each callback of those tasks is called. +Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work. + +While [queue](#queue) passes only one task to one of a group of workers +at a time, cargo passes an array of tasks to a single worker, repeating +when the worker is finished. + +__Arguments__ + +* `worker(tasks, callback)` - An asynchronous function for processing an array of + queued tasks, which must call its `callback(err)` argument when finished, with + an optional `err` argument. +* `payload` - An optional `integer` for determining how many tasks should be + processed per round; if omitted, the default is unlimited. + +__Cargo objects__ + +The `cargo` object returned by this function has the following properties and +methods: + +* `length()` - A function returning the number of items waiting to be processed. +* `payload` - An `integer` for determining how many tasks should be + process per round. This property can be changed after a `cargo` is created to + alter the payload on-the-fly. +* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called + once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` + can be submitted. The respective callback is used for every task in the list. +* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued. +* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`. + +__Example__ + +```js +// create a cargo object with payload 2 + +var cargo = async.cargo(function (tasks, callback) { + for(var i=0; i +### auto(tasks, [callback]) + +Determines the best order for running the functions in `tasks`, based on their +requirements. Each function can optionally depend on other functions being completed +first, and each function is run as soon as its requirements are satisfied. + +If any of the functions pass an error to their callback, it will not +complete (so any other functions depending on it will not run), and the main +`callback` is immediately called with the error. Functions also receive an +object containing the results of functions which have completed so far. + +Note, all functions are called with a `results` object as a second argument, +so it is unsafe to pass functions in the `tasks` object which cannot handle the +extra argument. + +For example, this snippet of code: + +```js +async.auto({ + readData: async.apply(fs.readFile, 'data.txt', 'utf-8') +}, callback); +``` + +will have the effect of calling `readFile` with the results object as the last +argument, which will fail: + +```js +fs.readFile('data.txt', 'utf-8', cb, {}); +``` + +Instead, wrap the call to `readFile` in a function which does not forward the +`results` object: + +```js +async.auto({ + readData: function(cb, results){ + fs.readFile('data.txt', 'utf-8', cb); + } +}, callback); +``` + +__Arguments__ + +* `tasks` - An object. Each of its properties is either a function or an array of + requirements, with the function itself the last item in the array. The object's key + of a property serves as the name of the task defined by that property, + i.e. can be used when specifying requirements for other tasks. + The function receives two arguments: (1) a `callback(err, result)` which must be + called when finished, passing an `error` (which can be `null`) and the result of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions. +* `callback(err, results)` - An optional callback which is called when all the + tasks have been completed. It receives the `err` argument if any `tasks` + pass an error to their callback. Results are always returned; however, if + an error occurs, no further `tasks` will be performed, and the results + object will only contain partial results. + + +__Example__ + +```js +async.auto({ + get_data: function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + make_folder: function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + }, + write_file: ['get_data', 'make_folder', function(callback, results){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + callback(null, 'filename'); + }], + email_link: ['write_file', function(callback, results){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + // results.write_file contains the filename returned by write_file. + callback(null, {'file':results.write_file, 'email':'user@example.com'}); + }] +}, function(err, results) { + console.log('err = ', err); + console.log('results = ', results); +}); +``` + +This is a fairly trivial example, but to do this using the basic parallel and +series functions would look like this: + +```js +async.parallel([ + function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + } +], +function(err, results){ + async.series([ + function(callback){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + results.push('filename'); + callback(null); + }, + function(callback){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + callback(null, {'file':results.pop(), 'email':'user@example.com'}); + } + ]); +}); +``` + +For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding +new tasks much easier (and the code more readable). + + +--------------------------------------- + + +### retry([times = 5], task, [callback]) + +Attempts to get a successful response from `task` no more than `times` times before +returning an error. If the task is successful, the `callback` will be passed the result +of the successful task. If all attempts fail, the callback will be passed the error and +result (if any) of the final attempt. + +__Arguments__ + +* `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5. +* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)` + which must be called when finished, passing `err` (which can be `null`) and the `result` of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions (if nested inside another control flow). +* `callback(err, results)` - An optional callback which is called when the + task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. + +The [`retry`](#retry) function can be used as a stand-alone control flow by passing a +callback, as shown below: + +```js +async.retry(3, apiMethod, function(err, result) { + // do something with the result +}); +``` + +It can also be embeded within other control flow functions to retry individual methods +that are not as reliable, like this: + +```js +async.auto({ + users: api.getUsers.bind(api), + payments: async.retry(3, api.getPayments.bind(api)) +}, function(err, results) { + // do something with the results +}); +``` + + +--------------------------------------- + + +### iterator(tasks) + +Creates an iterator function which calls the next function in the `tasks` array, +returning a continuation to call the next one after that. It's also possible to +“peek” at the next iterator with `iterator.next()`. + +This function is used internally by the `async` module, but can be useful when +you want to manually control the flow of functions in series. + +__Arguments__ + +* `tasks` - An array of functions to run. + +__Example__ + +```js +var iterator = async.iterator([ + function(){ sys.p('one'); }, + function(){ sys.p('two'); }, + function(){ sys.p('three'); } +]); + +node> var iterator2 = iterator(); +'one' +node> var iterator3 = iterator2(); +'two' +node> iterator3(); +'three' +node> var nextfn = iterator2.next(); +node> nextfn(); +'three' +``` + +--------------------------------------- + + +### apply(function, arguments..) + +Creates a continuation function with some arguments already applied. + +Useful as a shorthand when combined with other control flow functions. Any arguments +passed to the returned function are added to the arguments originally passed +to apply. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to automatically apply when the + continuation is called. + +__Example__ + +```js +// using apply + +async.parallel([ + async.apply(fs.writeFile, 'testfile1', 'test1'), + async.apply(fs.writeFile, 'testfile2', 'test2'), +]); + + +// the same process without using apply + +async.parallel([ + function(callback){ + fs.writeFile('testfile1', 'test1', callback); + }, + function(callback){ + fs.writeFile('testfile2', 'test2', callback); + } +]); +``` + +It's possible to pass any number of additional arguments when calling the +continuation: + +```js +node> var fn = async.apply(sys.puts, 'one'); +node> fn('two', 'three'); +one +two +three +``` + +--------------------------------------- + + +### nextTick(callback), setImmediate(callback) + +Calls `callback` on a later loop around the event loop. In Node.js this just +calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)` +if available, otherwise `setTimeout(callback, 0)`, which means other higher priority +events may precede the execution of `callback`. + +This is used internally for browser-compatibility purposes. + +__Arguments__ + +* `callback` - The function to call on a later loop around the event loop. + +__Example__ + +```js +var call_order = []; +async.nextTick(function(){ + call_order.push('two'); + // call_order now equals ['one','two'] +}); +call_order.push('one') +``` + + +### times(n, callback) + +Calls the `callback` function `n` times, and accumulates results in the same manner +you would use with [`map`](#map). + +__Arguments__ + +* `n` - The number of times to run the function. +* `iterator` - The function to call `n` times. +* `callback` - see [`map`](#map) + +__Example__ + +```js +// Pretend this is some complicated async factory +var createUser = function(id, callback) { + callback(null, { + id: 'user' + id + }) +} +// generate 5 users +async.times(5, function(n, next){ + createUser(n, function(err, user) { + next(err, user) + }) +}, function(err, users) { + // we should now have 5 users +}); +``` + + +### timesSeries(n, callback) + +The same as [`times`](#times), only the iterator is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + + +## Utils + + +### memoize(fn, [hasher]) + +Caches the results of an `async` function. When creating a hash to store function +results against, the callback is omitted from the hash and an optional hash +function can be used. + +If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function. + +The cache of results is exposed as the `memo` property of the function returned +by `memoize`. + +__Arguments__ + +* `fn` - The function to proxy and cache results from. +* `hasher` - An optional function for generating a custom hash for storing + results. It has all the arguments applied to it apart from the callback, and + must be synchronous. + +__Example__ + +```js +var slow_fn = function (name, callback) { + // do something + callback(null, result); +}; +var fn = async.memoize(slow_fn); + +// fn can now be used as if it were slow_fn +fn('some name', function () { + // callback +}); +``` + + +### unmemoize(fn) + +Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized +form. Handy for testing. + +__Arguments__ + +* `fn` - the memoized function + + +### log(function, arguments) + +Logs the result of an `async` function to the `console`. Only works in Node.js or +in browsers that support `console.log` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.log` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, 'hello ' + name); + }, 1000); +}; +``` +```js +node> async.log(hello, 'world'); +'hello world' +``` + +--------------------------------------- + + +### dir(function, arguments) + +Logs the result of an `async` function to the `console` using `console.dir` to +display the properties of the resulting object. Only works in Node.js or +in browsers that support `console.dir` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.dir` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, {hello: name}); + }, 1000); +}; +``` +```js +node> async.dir(hello, 'world'); +{hello: 'world'} +``` + +--------------------------------------- + + +### noConflict() + +Changes the value of `async` back to its original value, returning a reference to the +`async` object. diff --git a/node_modules/winston/node_modules/async/bower.json b/node_modules/winston/node_modules/async/bower.json new file mode 100644 index 0000000..9e4156d --- /dev/null +++ b/node_modules/winston/node_modules/async/bower.json @@ -0,0 +1,40 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "1.0.0", + "main": "lib/async.js", + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/caolan/async.git" + }, + "devDependencies": { + "benchmark": "~1.0.0", + "jshint": "~2.7.0", + "lodash": ">=2.4.1", + "mkdirp": "~0.5.1", + "nodeunit": ">0.0.0", + "uglify-js": "1.2.x" + }, + "moduleType": [ + "amd", + "globals", + "node" + ], + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ], + "authors": [ + "Caolan McMahon" + ] +} \ No newline at end of file diff --git a/node_modules/winston/node_modules/async/component.json b/node_modules/winston/node_modules/async/component.json new file mode 100644 index 0000000..c876b0a --- /dev/null +++ b/node_modules/winston/node_modules/async/component.json @@ -0,0 +1,17 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "1.0.0", + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "main": "lib/async.js", + "repository": "caolan/async", + "scripts": [ + "lib/async.js" + ] +} \ No newline at end of file diff --git a/node_modules/winston/node_modules/async/lib/async.js b/node_modules/winston/node_modules/async/lib/async.js new file mode 100644 index 0000000..1e76ee8 --- /dev/null +++ b/node_modules/winston/node_modules/async/lib/async.js @@ -0,0 +1,1283 @@ +/*! + * async + * https://github.com/caolan/async + * + * Copyright 2010-2014 Caolan McMahon + * Released under the MIT license + */ +(function () { + + var async = {}; + var noop = function () {}; + + // global on the server, window in the browser + var root, previous_async; + + if (typeof window == 'object' && this === window) { + root = window; + } + else if (typeof global == 'object' && this === global) { + root = global; + } + else { + root = this; + } + + if (root != null) { + previous_async = root.async; + } + + async.noConflict = function () { + root.async = previous_async; + return async; + }; + + function only_once(fn) { + var called = false; + return function() { + if (called) throw new Error("Callback was already called."); + called = true; + fn.apply(root, arguments); + }; + } + + //// cross-browser compatiblity functions //// + + var _toString = Object.prototype.toString; + + var _isArray = Array.isArray || function (obj) { + return _toString.call(obj) === '[object Array]'; + }; + + var _each = function (arr, iterator) { + var index = -1, + length = arr.length; + + while (++index < length) { + iterator(arr[index], index, arr); + } + }; + + var _map = function (arr, iterator) { + var index = -1, + length = arr.length, + result = Array(length); + + while (++index < length) { + result[index] = iterator(arr[index], index, arr); + } + return result; + }; + + var _reduce = function (arr, iterator, memo) { + _each(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + }; + + var _forEachOf = function (object, iterator) { + _each(_keys(object), function (key) { + iterator(object[key], key); + }); + }; + + var _keys = Object.keys || function (obj) { + var keys = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + }; + + var _baseSlice = function (arr, start) { + start = start || 0; + var index = -1; + var length = arr.length; + + if (start) { + length -= start; + length = length < 0 ? 0 : length; + } + var result = Array(length); + + while (++index < length) { + result[index] = arr[index + start]; + } + return result; + }; + + //// exported async module functions //// + + //// nextTick implementation with browser-compatible fallback //// + + // capture the global reference to guard against fakeTimer mocks + var _setImmediate; + if (typeof setImmediate === 'function') { + _setImmediate = setImmediate; + } + + if (typeof process === 'undefined' || !(process.nextTick)) { + if (_setImmediate) { + async.nextTick = function (fn) { + // not a direct alias for IE10 compatibility + _setImmediate(fn); + }; + async.setImmediate = async.nextTick; + } + else { + async.nextTick = function (fn) { + setTimeout(fn, 0); + }; + async.setImmediate = async.nextTick; + } + } + else { + async.nextTick = process.nextTick; + if (_setImmediate) { + async.setImmediate = function (fn) { + // not a direct alias for IE10 compatibility + _setImmediate(fn); + }; + } + else { + async.setImmediate = async.nextTick; + } + } + + async.each = function (arr, iterator, callback) { + callback = callback || noop; + if (!arr.length) { + return callback(); + } + var completed = 0; + _each(arr, function (x) { + iterator(x, only_once(done) ); + }); + function done(err) { + if (err) { + callback(err); + callback = noop; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + } + } + }; + async.forEach = async.each; + + async.eachSeries = function (arr, iterator, callback) { + callback = callback || noop; + if (!arr.length) { + return callback(); + } + var completed = 0; + var iterate = function () { + iterator(arr[completed], function (err) { + if (err) { + callback(err); + callback = noop; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + else { + iterate(); + } + } + }); + }; + iterate(); + }; + async.forEachSeries = async.eachSeries; + + + async.eachLimit = function (arr, limit, iterator, callback) { + var fn = _eachLimit(limit); + fn.apply(null, [arr, iterator, callback]); + }; + async.forEachLimit = async.eachLimit; + + var _eachLimit = function (limit) { + + return function (arr, iterator, callback) { + callback = callback || noop; + if (!arr.length || limit <= 0) { + return callback(); + } + var completed = 0; + var started = 0; + var running = 0; + + (function replenish () { + if (completed >= arr.length) { + return callback(); + } + + while (running < limit && started < arr.length) { + started += 1; + running += 1; + iterator(arr[started - 1], function (err) { + if (err) { + callback(err); + callback = noop; + } + else { + completed += 1; + running -= 1; + if (completed >= arr.length) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + + async.forEachOf = async.eachOf = function (object, iterator, callback) { + callback = callback || function () {}; + var size = object.length || _keys(object).length; + var completed = 0; + if (!size) { + return callback(); + } + _forEachOf(object, function (value, key) { + iterator(object[key], key, function (err) { + if (err) { + callback(err); + callback = function () {}; + } else { + completed += 1; + if (completed === size) { + callback(null); + } + } + }); + }); + }; + + async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { + callback = callback || function () {}; + var keys = _keys(obj); + var size = keys.length; + if (!size) { + return callback(); + } + var completed = 0; + var iterate = function () { + var sync = true; + var key = keys[completed]; + iterator(obj[key], key, function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed >= size) { + callback(null); + } + else { + if (sync) { + async.nextTick(iterate); + } + else { + iterate(); + } + } + } + }); + sync = false; + }; + iterate(); + }; + + + + async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { + _forEachOfLimit(limit)(obj, iterator, callback); + }; + + var _forEachOfLimit = function (limit) { + + return function (obj, iterator, callback) { + callback = callback || function () {}; + var keys = _keys(obj); + var size = keys.length; + if (!size || limit <= 0) { + return callback(); + } + var completed = 0; + var started = 0; + var running = 0; + + (function replenish () { + if (completed >= size) { + return callback(); + } + + while (running < limit && started < size) { + started += 1; + running += 1; + var key = keys[started - 1]; + iterator(obj[key], key, function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + running -= 1; + if (completed >= size) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + var doParallel = function (fn) { + return function () { + var args = _baseSlice(arguments); + return fn.apply(null, [async.each].concat(args)); + }; + }; + var doParallelLimit = function(limit, fn) { + return function () { + var args = _baseSlice(arguments); + return fn.apply(null, [_eachLimit(limit)].concat(args)); + }; + }; + var doSeries = function (fn) { + return function () { + var args = _baseSlice(arguments); + return fn.apply(null, [async.eachSeries].concat(args)); + }; + }; + + + var _asyncMap = function (eachfn, arr, iterator, callback) { + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + if (!callback) { + eachfn(arr, function (x, callback) { + iterator(x.value, function (err) { + callback(err); + }); + }); + } else { + var results = []; + eachfn(arr, function (x, callback) { + iterator(x.value, function (err, v) { + results[x.index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_asyncMap); + async.mapLimit = function (arr, limit, iterator, callback) { + return _mapLimit(limit)(arr, iterator, callback); + }; + + var _mapLimit = function(limit) { + return doParallelLimit(limit, _asyncMap); + }; + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.reduce = function (arr, memo, iterator, callback) { + async.eachSeries(arr, function (x, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); + }; + // inject alias + async.inject = async.reduce; + // foldl alias + async.foldl = async.reduce; + + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, function (x) { + return x; + }).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + // foldr alias + async.foldr = async.reduceRight; + + var _filter = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.filter = doParallel(_filter); + async.filterSeries = doSeries(_filter); + // select alias + async.select = async.filter; + async.selectSeries = async.filterSeries; + + var _reject = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (!v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.reject = doParallel(_reject); + async.rejectSeries = doSeries(_reject); + + var _detect = function (eachfn, arr, iterator, main_callback) { + eachfn(arr, function (x, callback) { + iterator(x, function (result) { + if (result) { + main_callback(x); + main_callback = noop; + } + else { + callback(); + } + }); + }, function (err) { + main_callback(); + }); + }; + async.detect = doParallel(_detect); + async.detectSeries = doSeries(_detect); + + async.some = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (v) { + main_callback(true); + main_callback = noop; + } + callback(); + }); + }, function (err) { + main_callback(false); + }); + }; + // any alias + async.any = async.some; + + async.every = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (!v) { + main_callback(false); + main_callback = noop; + } + callback(); + }); + }, function (err) { + main_callback(true); + }); + }; + // all alias + async.all = async.every; + + async.sortBy = function (arr, iterator, callback) { + async.map(arr, function (x, callback) { + iterator(x, function (err, criteria) { + if (err) { + callback(err); + } + else { + callback(null, {value: x, criteria: criteria}); + } + }); + }, function (err, results) { + if (err) { + return callback(err); + } + else { + var fn = function (left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }; + callback(null, _map(results.sort(fn), function (x) { + return x.value; + })); + } + }); + }; + + async.auto = function (tasks, callback) { + callback = callback || noop; + var keys = _keys(tasks); + var remainingTasks = keys.length; + if (!remainingTasks) { + return callback(); + } + + var results = {}; + + var listeners = []; + var addListener = function (fn) { + listeners.unshift(fn); + }; + var removeListener = function (fn) { + for (var i = 0; i < listeners.length; i += 1) { + if (listeners[i] === fn) { + listeners.splice(i, 1); + return; + } + } + }; + var taskComplete = function () { + remainingTasks--; + _each(listeners.slice(0), function (fn) { + fn(); + }); + }; + + addListener(function () { + if (!remainingTasks) { + var theCallback = callback; + // prevent final callback from calling itself if it errors + callback = noop; + + theCallback(null, results); + } + }); + + _each(keys, function (k) { + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + var taskCallback = function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _each(_keys(results), function(rkey) { + safeResults[rkey] = results[rkey]; + }); + safeResults[k] = args; + callback(err, safeResults); + // stop subsequent errors hitting callback multiple times + callback = noop; + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }; + var requires = task.slice(0, Math.abs(task.length - 1)) || []; + // prevent dead-locks + var len = requires.length; + var dep; + while (len--) { + if (!(dep = tasks[requires[len]])) { + throw new Error('Has inexistant dependency'); + } + if (_isArray(dep) && !!~dep.indexOf(k)) { + throw new Error('Has cyclic dependencies'); + } + } + var ready = function () { + return _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + }; + if (ready()) { + task[task.length - 1](taskCallback, results); + } + else { + var listener = function () { + if (ready()) { + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + }; + addListener(listener); + } + }); + }; + + async.retry = function(times, task, callback) { + var DEFAULT_TIMES = 5; + var attempts = []; + // Use defaults if times not passed + if (typeof times === 'function') { + callback = task; + task = times; + times = DEFAULT_TIMES; + } + // Make sure times is a number + times = parseInt(times, 10) || DEFAULT_TIMES; + var wrappedTask = function(wrappedCallback, wrappedResults) { + var retryAttempt = function(task, finalAttempt) { + return function(seriesCallback) { + task(function(err, result){ + seriesCallback(!err || finalAttempt, {err: err, result: result}); + }, wrappedResults); + }; + }; + while (times) { + attempts.push(retryAttempt(task, !(times-=1))); + } + async.series(attempts, function(done, data){ + data = data[data.length - 1]; + (wrappedCallback || callback)(data.err, data.result); + }); + }; + // If a callback is passed, run this as a controll flow + return callback ? wrappedTask() : wrappedTask; + }; + + async.waterfall = function (tasks, callback) { + callback = callback || noop; + if (!_isArray(tasks)) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + var wrapIterator = function (iterator) { + return function (err) { + if (err) { + callback.apply(null, arguments); + callback = noop; + } + else { + var args = _baseSlice(arguments, 1); + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + async.setImmediate(function () { + iterator.apply(null, args); + }); + } + }; + }; + wrapIterator(async.iterator(tasks))(); + }; + + var _parallel = function(eachfn, tasks, callback) { + callback = callback || noop; + if (_isArray(tasks)) { + eachfn.map(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + eachfn.each(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.parallel = function (tasks, callback) { + _parallel({ map: async.map, each: async.each }, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); + }; + + async.series = function (tasks, callback) { + callback = callback || noop; + if (_isArray(tasks)) { + async.mapSeries(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + async.eachSeries(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.iterator = function (tasks) { + var makeCallback = function (index) { + var fn = function () { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + }; + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + }; + return makeCallback(0); + }; + + async.apply = function (fn) { + var args = _baseSlice(arguments, 1); + return function () { + return fn.apply( + null, args.concat(_baseSlice(arguments)) + ); + }; + }; + + var _concat = function (eachfn, arr, fn, callback) { + var r = []; + eachfn(arr, function (x, cb) { + fn(x, function (err, y) { + r = r.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, r); + }); + }; + async.concat = doParallel(_concat); + async.concatSeries = doSeries(_concat); + + async.whilst = function (test, iterator, callback) { + if (test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.whilst(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doWhilst = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = _baseSlice(arguments, 1); + if (test.apply(null, args)) { + async.doWhilst(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.until = function (test, iterator, callback) { + if (!test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.until(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doUntil = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = _baseSlice(arguments, 1); + if (!test.apply(null, args)) { + async.doUntil(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.queue = function (worker, concurrency) { + if (concurrency === undefined) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + function _insert(q, data, pos, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + callback: typeof callback === 'function' ? callback : null + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + var workers = 0; + var q = { + tasks: [], + concurrency: concurrency, + saturated: null, + empty: null, + drain: null, + started: false, + paused: false, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + kill: function () { + q.drain = null; + q.tasks = []; + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + if (!q.paused && workers < q.concurrency && q.tasks.length) { + var task = q.tasks.shift(); + if (q.empty && q.tasks.length === 0) { + q.empty(); + } + workers += 1; + var next = function () { + workers -= 1; + if (task.callback) { + task.callback.apply(task, arguments); + } + if (q.drain && q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + var cb = only_once(next); + worker(task.data, cb); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + }, + idle: function() { + return q.tasks.length + workers === 0; + }, + pause: function () { + if (q.paused === true) { return; } + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + var resumeCount = Math.min(q.concurrency, q.tasks.length); + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= resumeCount; w++) { + async.setImmediate(q.process); + } + } + }; + return q; + }; + + async.priorityQueue = function (worker, concurrency) { + + function _compareTasks(a, b){ + return a.priority - b.priority; + } + + function _binarySearch(sequence, item, compare) { + var beg = -1, + end = sequence.length - 1; + while (beg < end) { + var mid = beg + ((end - beg + 1) >>> 1); + if (compare(item, sequence[mid]) >= 0) { + beg = mid; + } else { + end = mid - 1; + } + } + return beg; + } + + function _insert(q, data, priority, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + priority: priority, + callback: typeof callback === 'function' ? callback : null + }; + + q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + // Start with a normal queue + var q = async.queue(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function (data, priority, callback) { + _insert(q, data, priority, callback); + }; + + // Remove unshift function + delete q.unshift; + + return q; + }; + + async.cargo = function (worker, payload) { + var working = false, + tasks = []; + + var cargo = { + tasks: tasks, + payload: payload, + saturated: null, + empty: null, + drain: null, + drained: true, + push: function (data, callback) { + if (!_isArray(data)) { + data = [data]; + } + _each(data, function(task) { + tasks.push({ + data: task, + callback: typeof callback === 'function' ? callback : null + }); + cargo.drained = false; + if (cargo.saturated && tasks.length === payload) { + cargo.saturated(); + } + }); + async.setImmediate(cargo.process); + }, + process: function process() { + if (working) return; + if (tasks.length === 0) { + if(cargo.drain && !cargo.drained) cargo.drain(); + cargo.drained = true; + return; + } + + var ts = typeof payload === 'number' ? + tasks.splice(0, payload) : + tasks.splice(0, tasks.length); + + var ds = _map(ts, function (task) { + return task.data; + }); + + if(cargo.empty) cargo.empty(); + working = true; + worker(ds, function () { + working = false; + + var args = arguments; + _each(ts, function (data) { + if (data.callback) { + data.callback.apply(null, args); + } + }); + + process(); + }); + }, + length: function () { + return tasks.length; + }, + running: function () { + return working; + } + }; + return cargo; + }; + + var _console_fn = function (name) { + return function (fn) { + var args = _baseSlice(arguments, 1); + fn.apply(null, args.concat([function (err) { + var args = _baseSlice(arguments, 1); + if (typeof console !== 'undefined') { + if (err) { + if (console.error) { + console.error(err); + } + } + else if (console[name]) { + _each(args, function (x) { + console[name](x); + }); + } + } + }])); + }; + }; + async.log = _console_fn('log'); + async.dir = _console_fn('dir'); + /*async.info = _console_fn('info'); + async.warn = _console_fn('warn'); + async.error = _console_fn('error');*/ + + async.memoize = function (fn, hasher) { + var memo = {}; + var queues = {}; + hasher = hasher || function (x) { + return x; + }; + var memoized = function () { + var args = _baseSlice(arguments); + var callback = args.pop(); + var key = hasher.apply(null, args); + if (key in memo) { + async.nextTick(function () { + callback.apply(null, memo[key]); + }); + } + else if (key in queues) { + queues[key].push(callback); + } + else { + queues[key] = [callback]; + fn.apply(null, args.concat([function () { + memo[key] = _baseSlice(arguments); + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, arguments); + } + }])); + } + }; + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + + async.times = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.map(counter, iterator, callback); + }; + + async.timesSeries = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.mapSeries(counter, iterator, callback); + }; + + async.seq = function (/* functions... */) { + var fns = arguments; + return function () { + var that = this; + var args = _baseSlice(arguments); + var callback = args.pop(); + async.reduce(fns, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat([function () { + var err = arguments[0]; + var nextargs = _baseSlice(arguments, 1); + cb(err, nextargs); + }])); + }, + function (err, results) { + callback.apply(that, [err].concat(results)); + }); + }; + }; + + async.compose = function (/* functions... */) { + return async.seq.apply(null, Array.prototype.reverse.call(arguments)); + }; + + var _applyEach = function (eachfn, fns /*args...*/) { + var go = function () { + var that = this; + var args = _baseSlice(arguments); + var callback = args.pop(); + return eachfn(fns, function (fn, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }; + if (arguments.length > 2) { + var args = _baseSlice(arguments, 2); + return go.apply(this, args); + } + else { + return go; + } + }; + async.applyEach = doParallel(_applyEach); + async.applyEachSeries = doSeries(_applyEach); + + async.forever = function (fn, callback) { + function next(err) { + if (err) { + if (callback) { + return callback(err); + } + throw err; + } + fn(next); + } + next(); + }; + + // Node.js + if (typeof module !== 'undefined' && module.exports) { + module.exports = async; + } + // AMD / RequireJS + else if (typeof define !== 'undefined' && define.amd) { + define([], function () { + return async; + }); + } + // included directly via